source: TI02-CSML/trunk/csml/csmllibs/csmltime.py @ 2206

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI02-CSML/trunk/csml/csmllibs/csmltime.py@2206
Revision 2206, 5.9 KB checked in by domlowe, 13 years ago (diff)

nearest neighbour working for times, plus separation of subsetting into core functions and feature specific ones

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#!/usr/bin/env python
2
3#**************************************************************************************
4#csmltime.py
5#contains time related functions for creating CSML
6#v0.5 split off 11th November 2005
7#v0.51 updated to use datainterface 6th Dec 05
8#!!!!!!!!!!!!!!! NEEDS TIDYING UP!!!!!!!!!!!!!!!!!!!!!!!!!!!
9#Dominic Lowe, BADC
10#**************************************************************************************
11
12import csml.csmllibs
13import datetime
14import sys
15import cdtime
16import pdb
17
18def CSMLtimeToUDtime(time):
19        #time string manipulation  - convert  2783-5-22T0:0:0.0 to 2783-5-22 0:0:0.0
20    return str(time).replace ('T', ' ')
21
22def UDtimeToCSMLtime(time):
23    #time string manipulation  - convert 2783-5-22 0:0:0.0 to 2783-5-22T0:0:0.0
24    return str(time).replace (' ', 'T')
25               
26def setcdtimeCalendar(cal):
27    if cal == 'standard':
28        cdtime.DefaultCalendar= cdtime.MixedCalendar
29    elif cal == 'gregorian':
30        cdtime.DefaultCalendar= cdtime.MixedCalendar
31    elif cal == 'proleptic_gregorian':
32        cdtime.DefaultCalendar= cdtime.GregorianCalendar
33    elif cal=='360_day':
34        cdtime.DefaultCalendar=cdtime.Calendar360
35    elif cal=='noleap':
36        cdtime.DefaultCalendar=  cdtime.NoLeapCalendar
37    elif cal=='365_day':
38        cdtime.DefaultCalendar=  cdtime.NoLeapCalendar
39    elif cal =='julian':
40        cdtime.DefaultCalendar=  cdtime.JulianCalendar
41       
42       
43def identifyTimeAxis(self,listToCheck): 
44    #given a list of possible axes, find the one which is most probably the time axis.
45    for name in listToCheck:
46        if string.upper(name) in ['T', 'TIME']:
47            tname =name
48    return tname
49
50def compareTimes(timemin, timecheck, timemax):
51    timeok=0
52    try:
53        year=int(timecheck.split('-')[0])
54        month=int(timecheck.split('-')[1])
55        day=int(timecheck.split('-')[2].split('T')[0])
56        tcheck=cdtime.comptime(year,month,day)
57        timeok=0
58        if tcheck.cmp(timemin) >= 0:
59            if tcheck.cmp(timemax) < 1:
60                timeok = 1
61    except:
62        #if it's not a proper internet time e.g. time = '6' then just compare numerically
63        timeok=0
64        if timecheck >=timemin:
65            if timecheck <=timemax:
66                timeok = 1
67    return timeok
68
69def getTimeAsValue(time):
70    year=int(time.split('-')[0])
71    month=int(time.split('-')[1])
72    day=int(time.split('-')[2].split('T')[0])
73    hour=int(time.split('-')[2].split('T')[1].split(':')[0])
74    minute=int(time.split('-')[2].split('T')[1].split(':')[1])
75    second=float(time.split('-')[2].split('T')[1].split(':')[2])
76    return (10000000000*year+100000000*month + (1000000 * day) + (10000*hour) + (100*minute) + second)
77
78def convertValueToCSML(t):
79    #this may need to be more robust
80    csmlt='%s-%s-%sT%s:%s:%s.%s'%(int(t/10000000000),str(int(t/100000000))[-2:],str(int(t/1000000))[-2:]
81,str(int(t/10000))[-2:],str(int(t/100))[-2:],str(int(t))[-2:],0)
82    return csmlt
83
84
85def getCDtime(time): 
86    year=int(time.split('-')[0])
87    month=int(time.split('-')[1])
88    day=int(time.split('-')[2].split('T')[0])
89    hour=int(time.split('-')[2].split('T')[1].split(':')[0])
90    minute=int(time.split('-')[2].split('T')[1].split(':')[1])
91    second=float(time.split('-')[2].split('T')[1].split(':')[2])
92    cdTimeVal=cdtime.comptime(year,month,day,hour,minute,second)
93    return cdTimeVal
94
95def getFileTimeList(filelist, timedim):
96        #****************************************************************************************
97        #Given a list of files and a name for the time dimension this function will return a list containing
98        # filename/time pairs eg tuple [(ta,fa),(tb,fb),(tc,fc)] in the correct temporal order.
99        #if files contain more than one time, then the tuple will be of the form:
100        #[(ta1,ta2,ta3,fa),(tb1,tb2,tb3,fb),(tc1,tc2,tc3,fc)]
101        #*****************************************************************************************
102        FileTimeList = []  #list to hold the filesnames and corrsponding times
103        DI=csml.csmllibs.csmldataiface.DataInterface()
104        #grab any (first) file                 
105        DI=DI.getUnknownInterfaceType(filelist[0])
106        count=0
107        for file in filelist:
108                count=count +1
109                DI.openFile(file)
110                try:
111                        DI.setAxis(timedim)
112                        data =DI.getDataForAxis()
113                except:
114                        try:
115                            data=DI.getTimes()
116                        except:
117                            print 'tried alternative method to get time axis and failed'
118                            print "check you have the correct time axis (-t) set"
119                            sys.exit()
120                times=[]
121                for j in range(0,len(data)):
122                        times.append(data[j])
123                refTime=DI.getTimeUnits()   #maybe this can be optional?
124                ftTuple = (times, file,refTime)
125                FileTimeList.append(ftTuple)
126                DI.closeFile()
127                if count % 20 == 0:
128                        print 'scanning file %s of %s'%(count,len(filelist))
129        #get calendar type:
130        DI.openFile(filelist[0])
131        try:
132            DI.setAxis(timedim)
133            cal = DI.getAxisAttribute('calendar')
134            setcdtimeCalendar(cal)
135        except:
136            print 'No calendar attribute, defaulting to CF standard mixed calendar'
137            cal='standard'
138            setcdtimeCalendar(cal)
139        try:
140            units=DI.getAxisAttribute('units')
141        except:
142            print "Could not get time unit info"
143            units =''
144        FileTimeList.sort()
145        #get the reference date for the time reference system.
146        #refTime=DI.getTimeUnits()
147        DI.closeFile()
148        FormattedFileTimeList = []
149        for j in range (0,len(FileTimeList)):
150                timeList = FileTimeList[j][0]
151                refTime=FileTimeList[j][2]
152                #print 'timelist_____________________' +str(timeList)
153                for k in range(0, len(timeList)):
154                        relativetime= cdtime.reltime(timeList[k], refTime)
155                        uduTime=UDtimeToCSMLtime(relativetime.tocomp())
156                        ftTuple = (uduTime, filelist[j])
157                        FormattedFileTimeList.append(ftTuple)                   
158        print  'finished time list'
159        return FormattedFileTimeList, cal,units
Note: See TracBrowser for help on using the repository browser.