#!/usr/bin/env python # hunger threshold in hours hungerThreshold = 3.0 # sleep threshold in hours sleepThreshold = 8.0 # time since fed, in hours timeSinceFed = 4.0 # time since sleep, in hours timeSinceSleep = 3.0 # Note use of \ as line continuation here # It is poor style to have code lines > 79 characters # # see http://www.python.org/dev/peps/pep-0008/#maximum-line-length # print "Tired and hungry?",(timeSinceSleep >= sleepThreshold) and \ (timeSinceFed >= hungerThreshold) print "Just tired?",(timeSinceSleep >= sleepThreshold) and \ (not (timeSinceFed >= hungerThreshold)) print "Just hungry?",(not (timeSinceSleep >= sleepThreshold)) and \ (timeSinceFed >= hungerThreshold) """ Exercise 2.1 Scientific Computing Thu 3 Oct 2013 10:46:58 BST P. Lewis : p.lewis@ucl.ac.uk This code prints information on whether I am tired and/or hungry. It is controlled by the variables: timeSinceFed timeSinceSleep which are checked against hunger and sleep thresholds: hungerThreshold sleepThreshold All times given as float, in hours It is a modification of the code in Exercise 2.1 of Scientific Computing (https://github.com/profLewis/geogg122) Edits made from original: - added detailed comment strings - neatened up the comments - made code easier to read by setting variables tired and hungry. - added a new result for 'tired or hungry' - added tabs (\t) to the print statements to get neater output formatting. """ # Thresholds hungerThreshold = 3.0 # hunger threshold in hours sleepThreshold = 8.0 # sleep threshold in hours # Control variables timeSinceFed = 4.0 # time since fed, in hour timeSinceSleep = 3.0 # time since sleep, in hours # logical tests for tired and hungry tired = (timeSinceSleep >= sleepThreshold) hungry = (timeSinceFed >= hungerThreshold) # print results print "Tired and hungry?\t", tired and hungry print "Tired or hungry?\t\t", tired or hungry print "Just tired?\t\t", tired and not hungry print "Just hungry?\t\t", hungry and not tired # This imports a module that we can use to access dates from datetime import datetime # set up a list of days of the week, starting Monday # Note the line continuation here with \ week = ['Monday','Tuesday','Wednesday','Thursday',\ 'Friday','Saturday','Sunday'] # This part gives the day of the week # as an integer, 0 -> Monday, 1 -> Tuesday etc. day_number = datetime.now().weekday() # print item day_number in the list week print "today is",week[day_number] ''' Exercise 2.2A Scientific Computing Mon 7 Oct 2013 10:43:38 BST P. Lewis : p.lewis@ucl.ac.uk This code prints a diary for today. ''' '''The following code block is taken verbatim from The Scientific Computing notes ''' # This imports a module that we can use to access dates from datetime import datetime # set up a list of days of the week, starting Monday # Note the line continuation here with \ week = ['Monday','Tuesday','Wednesday','Thursday',\ 'Friday','Saturday','Sunday'] # This part gives the day of the week # as an integer, 0 -> Monday, 1 -> Tuesday etc. day_number = datetime.now().weekday() # print item day_number in the list week print "Today is",week[day_number] '''New code: my own work Following the example in the question for E2.2A ''' if day_number == 0: # Monday print 'Spend the day learning Python' elif day_number == 1: # Tuesday print 'Spend the day learning Python' elif day_number == 2: # Wednesday print 'Go to Python class' elif day_number == 3: # Thursday print 'Spend the day learning Python' elif day_number == 4: # Friday print 'Spend the day learning Python' elif day_number == 5: # Saturday print 'Spend the day learning Python' elif day_number == 6: # Sunday print 'Spend the day learning Python' else: print "get some sleep" my_diary = ['Spend the day practicing Python',\ 'Spend the day practicing Python',\ 'Do some reading in the library at UCL', \ 'Remember to wake up early to get to the Python class at UCL',\ 'Spend the day practicing Python',\ 'Remember to wake up early to go to classes at Imperial College',\ 'Work at Python exercises from home',\ 'Work at Python exercises from home'] ''' Exercise 2.2B Scientific Computing Mon 7 Oct 2013 10:43:38 BST P. Lewis : p.lewis@ucl.ac.uk This code prints a diary for today. ''' '''The following code block is taken verbatim from The Scientific Computing notes ''' # This imports a module that we can use to access dates from datetime import datetime # set up a list of days of the week, starting Monday # Note the line continuation here with \ week = ['Monday','Tuesday','Wednesday','Thursday',\ 'Friday','Saturday','Sunday'] # This part gives the day of the week # as an integer, 0 -> Monday, 1 -> Tuesday etc. day_number = datetime.now().weekday() '''New code: my own work Following the example in the question for E2.2B ''' my_diary = ['spend the day doing Python',\ 'do some reading in the library at UCL', \ 'remember to wake up early to get to the Python class at UCL',\ 'spend the day doing Python',\ 'remember to wake up early to go to classes at Imperial College',\ 'work at Python exercises from home',\ 'work at Python exercises from home'] print "Today is",week[day_number],'so',my_diary[day_number] ''' Exercise 2.2B Scientific Computing Mon 7 Oct 2013 10:43:38 BST P. Lewis : p.lewis@ucl.ac.uk This code prints a diary for today. ''' '''The following code block is taken verbatim from The Scientific Computing notes ''' # This imports a module that we can use to access dates from datetime import datetime # This part gives the day of the week # as an integer, 0 -> Monday, 1 -> Tuesday etc. day_number = datetime.now().weekday() '''New code: my own work Following the example in the question for E2.2B ''' week = {0: 'Monday',\ 1: 'Tuesday',\ 2: 'Wednesday',\ 3: 'Thursday',\ 4: 'Friday',\ 5: 'Saturday',\ 6: 'Sunday'} my_diary = {'Monday': 'spend the day doing Python',\ 'Tuesday': 'do some reading in the library at UCL',\ 'Wednesday': 'remember to wake up early to get to the Python class at UCL',\ 'Thursday': 'spend the day doing Python',\ 'Friday': 'remember to wake up early to go to classes at Imperial College',\ 'Saturday': 'work at Python exercises from home',\ 'Sunday': 'work at Python exercises from home'} today = week[day_number] print "Today is",today,'so',my_diary[today] data = """ 2012 1 8.7 3.1 5 33.1 53.9 2012 2 7.1 1.6 13 13.8 86.6 2012 3 11.3 3.7 2 64.2 141.3 2012 4 10.9 4.3 3 108.9 151.1 2012 5 15.1 8.6 0 46.6 171.3 2012 6 17.9 10.9 0 74.4 189.0 2012 7 20.3 12.8 0 93.6 206.9 2012 8 22.0 14.0 0 59.6 217.3 2012 9 18.9 9.5 0 38.8 200.8 2012 10 13.6 7.9 0 92.7 94.7 2012 11 10.5 4.4 2 62.1 79.6 2012 12 7.9 2.4 8 95.6 41.9 """ print data # import the pylab module import pylab as plt %pylab inline # some e.g. x and y data x = range(100) y = [i**0.5 for i in x] plt.plot(x,y) plt.xlabel('x') plt.ylabel('y') plt.title('Plot of sqrt(x)') ldata = data.split('\n') print ldata # example using first line this_line = ldata[0] items = this_line.split() print items ldata = data.split('\n') # set empty lists to put the data in x = [] y = [] for this_line in ldata: items = this_line.split() # convert from string to float x.append(float(items[1])) # the month y.append(float(items[6])) # sunshine hrs print x print y # import the pylab module import pylab as plt %pylab inline plt.plot(x,y) plt.xlabel('month of 2012') plt.ylabel('Sunshine hours') plt.title('Sunshine hours for Lowestoft, UK, 2012') import pylab as plt %pylab inline items = [[float(i) \ for i in j.split()] \ for j in data.split('\n')] # get specific columns from items x = [i[1] for i in items] y = [i[6] for i in items] # bigger graph if we want plt.figure(figsize=(14, 6)) plt.plot(x,y) plt.xlabel('month of 2012') plt.ylabel('Sunshine hours') plt.title('Sunshine hours for Lowestoft, UK, 2012') import pylab as plt %pylab inline items = [[float(i) \ for i in j.split()] \ for j in data.split('\n')] # get specific columns from items x = [int(i[1]) for i in items] y = [i[6] for i in items] months = ["Jan", "Feb", "Mar", "Apr", \ "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] # need access to ax to mess with xticks fig, ax = plt.subplots(figsize=(14, 6)) plt.plot(x,y) # lots of hassle to do this sort of thing ... # but it is possible # # first set the limits to be the # same as x plt.xlim(x[0],x[-1]) # then set the xticks to the values of x # to make sure there are 12 of them ax.set_xticks(x) # then replace these by the months ax.set_xticklabels(months) plt.xlabel('month of 2012') plt.ylabel('Sunshine hours') plt.title('Sunshine hours for Lowestoft, UK, 2012') !head -10 < files/data/modis_files.txt # ls /data/geospatial_19/ucfajlg/fire/Angola/MOD09/*.hdf > /tmp/modis_files.txt fp = open('files/data/modis_files.txt','r') for line in fp.readlines(): print line break # break in here just so it doesnt print too much # dont put that in your code !!! fp.close() # split the string on '/', the file separator aline = line.split('/') print aline # and all we want is the last item: fname = line.split('/')[-1] print fname fname = line.split('/')[-1] fbits = fname.split('.') print fbits datebit = fbits[1] print datebit doy = int(datebit[-3:]) print doy date_range = range(214,245) # ls /data/geospatial_19/ucfajlg/fire/Angola/MOD09/*.hdf > /tmp/modis_files.txt fp = open('files/data/modis_files.txt','r') for line in fp.readlines(): fname = line.split('/')[-1] fbits = fname.split('.') datebit = fbits[1] doy = int(datebit[-3:]) if doy in date_range: print line break fp.close() ifile = 'files/data/modis_files.txt' ofile = 'files/data/some_modis_files.txt' ifp = open(ifile,'r') ofp = open(ofile,'w') for line in ifp.readlines(): fname = line.split('/')[-1] fbits = fname.split('.') datebit = fbits[1] doy = int(datebit[-3:]) if doy in date_range: ofp.write(line) ifp.close() ofp.close() # or in a more compressed form ifile = 'files/data/modis_files.txt' ofile = 'files/data/some_modis_files.txt' ifp = open(ifile,'r') ofp = open(ofile,'w') for line in ifp.readlines(): doy = int(line.split('/')[-1].split('.')[1][-3:]) if doy in date_range: ofp.write(line) ifp.close() ofp.close() !head -1 < files/data/some_modis_files.txt !tail -1 < files/data/some_modis_files.txt # specify filename filename = 'files/data/HadSEEP_monthly_qc.txt' # read the data, chop off first 4 lines # and store in required_data fp = open(filename,'r') raw_data = fp.readlines() fp.close() required_data = raw_data[4:] # set up list to store data in data = [] # loop over each line for line_data in required_data: # split on white space year_data = line_data.split() # convert data to float for column,this_element in enumerate(year_data): year_data[column] = float(this_element) data.append(year_data) # select years c20_data = [] for line in data: if (line[0] >= 1900) and (line[0] < 2000): c20_data.append(line[1:-1]) # Aside: show which month that was month_names = [ "Jan", "Feb", "Mar", "Apr", \ "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] print "In South East England" for row in xrange(0,100,1): year = 1900 + row max_precip = max(c20_data[row]) month = c20_data[row].index(max_precip) print "In the year",year,"the rainiest month was",month_names[month],"with",max_precip,"mm" # specify filename filename = 'files/data/HadSEEP_monthly_qc.txt' fp = open(filename,'r') # years range years = range(1900,2000) # set up list to store data in c20_data = [] # loop over each line for line_data in fp.readlines()[4:]: # split on white space # convert data to float year_data = [float(i) for i in line_data.split()] if year_data[0] in years: c20_data.append(year_data) # Aside: show which month that was month_names = [ "Jan", "Feb", "Mar", "Apr", \ "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] print "In South East England" for row,year in enumerate(years): max_precip = max(c20_data[row]) month = c20_data[row].index(max_precip) print "In the year",year,"the rainiest month was",month_names[month],"with",max_precip,"mm" fp.close() !wget -O files/data/heathrowdata.txt http://www.metoffice.gov.uk/climate/uk/stationdata/heathrowdata.txt ifile = 'files/data/heathrowdata.txt' fp = open(ifile) raw_data = fp.readlines() fp.close() raw_data = raw_data[7:] # Skip headers # set up the problem start_year = 1960 end_year = 1990 tmax = [] for l in raw_data: s = l.split() year = int( s[0] ) if year >= start_year and year < end_year: month = int ( s[1] ) if month == 1: tmax.append([]) tmax[-1].append(float ( s[2] )) for l in tmax: print l monthly_avg = [] n_years = len(tmax) for month in xrange ( len(tmax[0]) ): temp = 0. for year in xrange (n_years): temp += tmax[year][month] monthly_avg.append(temp/n_years) print "T results for",n_years,"years:",start_year,"to",end_year month_names = [ "Jan", "Feb", "Mar", "Apr", \ "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] print "\n\tMonth\tTmaxAvg\n" for i, mname in enumerate ( month_names ): print '\t',mname,'\t',monthly_avg[i] # 1. Read the configuration file # into the dict modis import ConfigParser config = ConfigParser.ConfigParser() config.read('files/data/modis.cfg') # we can convert this to a normal dictionary modis = {} for k in config.sections(): modis[k] = dict(config.items(k)) # 2. Now, loop over config sections # and get the sub-dictionary which we call sub_dict # 3. set up anb empty list to contain the # files we want to process wanted_files = [] for k,v in modis.items(): sub_dict = v # 3a. Read the file list fp = open(sub_dict['file_list'],'r') file_data = fp.readlines() fp.close() # 3b. find the doy range doy_range = range(int(sub_dict['doy_start']),\ int(sub_dict['doy_end'])) # 3c. loop over each file read from # sub_dict['file_list'] for count in xrange(len(file_data)): # 3d. extract doy from the file name this_file = file_data[count] doy = int(this_file.split('.')[1][-3:]) # 3e. see if doy is in the range we want? if doy in doy_range: # 3f. put the directory on the fornt full_name = sub_dict['dir'] + \ '/' + this_file wanted_files.append(full_name) print "I found %d files to process"%len(wanted_files) # I won't print the whole list as its too long # just the first 10 for f in wanted_files[:10]: print f # 1. Read the configuration file # into the dict modis import ConfigParser # good to open the file early on # in case it fails ofile = 'files/data/modis_files.dat' ofp = open(ofile,"w") config = ConfigParser.ConfigParser() config.read('files/data/modis.cfg') # we can convert this to a normal dictionary modis = {} for k in config.sections(): modis[k] = dict(config.items(k)) # 2. Now, loop over config sections # and get the sub-dictionary which we call sub_dict # 3. set up anb empty list to contain the # files we want to process wanted_files = [] for k,v in modis.items(): sub_dict = v # 3a. Read the file list fp = open(sub_dict['file_list'],'r') # 3b. find the doy range doy_range = range(int(sub_dict['doy_start']),\ int(sub_dict['doy_end'])) # 3c. loop over each file read from # sub_dict['file_list'] for this_file in fp.readlines(): # 3d. extract doy from the file name doy = int(this_file.split('.')[1][-3:]) # 3e. see if doy is in the range we want # and put in list if so doy in doy_range and \ wanted_files.append("%s/%s"%(sub_dict['dir'],this_file)) fp.close() print "I found %d files to process"%len(wanted_files) ofp.writelines(wanted_files) ofp.close() !head -10 < files/data/modis_files.dat # 1. Read the configuration file # into the dict modis import ConfigParser # good to open the file early on # in case it fails ofile = 'files/data/modis_files.dat' ofp = open(ofile,"w") config = ConfigParser.ConfigParser() config.read('files/data/modis.cfg') # we can convert this to a normal dictionary modis = {} for k in config.sections(): modis[k] = dict(config.items(k)) # 2. Now, loop over config sections # and get the sub-dictionary which we call sub_dict # 3. set up anb empty list to contain the # files we want to process wanted_files = [] for k,v in modis.items(): sub_dict = v # 3a. Read the file list fp = open(sub_dict['file_list'],'r') # 3b. find the doy range doy_range = range(int(sub_dict['doy_start']),\ int(sub_dict['doy_end'])) # 3c. loop over each file read from # sub_dict['file_list'] for this_file in fp.readlines(): # 3d. extract doy from the file name # 3e. see if doy is in the range we want # and put in list if so (int(this_file.split('.')[1][-3:]) in doy_range) and \ ofp.write("%s/%s"%(sub_dict['dir'],this_file)) fp.close() ofp.close() !head -10 < files/data/modis_files.dat