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

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

basics of QXF subsetting working

  • 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    newdate=''
25    newtime=''
26    date = str(time).split()[0]
27    t=str(time).split()[1]
28    for item in date.split('-'):
29        if len(item)==1:
30            item='0'+item
31        newdate=newdate + item +'-'
32    for item in t.split(':'):
33        if len(item)==1:
34            item='0'+item+':'
35        elif len(item)==3:
36            item='0'+item
37        else:
38            item=item + ':'
39        newtime=newtime + item
40    if newtime[-1] == ':':
41        csmlt=newdate[:-1]+'T'+newtime[:-1]
42    else:
43        csmlt=newdate[:-1]+'T'+newtime
44    return str(csmlt)
45               
46def setcdtimeCalendar(cal):
47    if cal == 'standard':
48        cdtime.DefaultCalendar= cdtime.MixedCalendar
49    elif cal == 'gregorian':
50        cdtime.DefaultCalendar= cdtime.MixedCalendar
51    elif cal == 'proleptic_gregorian':
52        cdtime.DefaultCalendar= cdtime.GregorianCalendar
53    elif cal=='360_day':
54        cdtime.DefaultCalendar=cdtime.Calendar360
55    elif cal=='noleap':
56        cdtime.DefaultCalendar=  cdtime.NoLeapCalendar
57    elif cal=='365_day':
58        cdtime.DefaultCalendar=  cdtime.NoLeapCalendar
59    elif cal =='julian':
60        cdtime.DefaultCalendar=  cdtime.JulianCalendar
61       
62       
63def identifyTimeAxis(self,listToCheck): 
64    #given a list of possible axes, find the one which is most probably the time axis.
65    for name in listToCheck:
66        if string.upper(name) in ['T', 'TIME']:
67            tname =name
68    return tname
69
70def compareTimes(timemin, timecheck, timemax):
71    timeok=0
72    try:
73        year=int(timecheck.split('-')[0])
74        month=int(timecheck.split('-')[1])
75        day=int(timecheck.split('-')[2].split('T')[0])
76        tcheck=cdtime.comptime(year,month,day)
77        timeok=0
78        if tcheck.cmp(timemin) >= 0:
79            if tcheck.cmp(timemax) < 1:
80                timeok = 1
81    except:
82        #if it's not a proper internet time e.g. time = '6' then just compare numerically
83        timeok=0
84        if timecheck >=timemin:
85            if timecheck <=timemax:
86                timeok = 1
87    return timeok
88
89def getTimeAsValue(time):
90    year=int(time.split('-')[0])
91    month=int(time.split('-')[1])
92    day=int(time.split('-')[2].split('T')[0])
93    hour=int(time.split('-')[2].split('T')[1].split(':')[0])
94    minute=int(time.split('-')[2].split('T')[1].split(':')[1])
95    second=float(time.split('-')[2].split('T')[1].split(':')[2])
96    return (10000000000*year+100000000*month + (1000000 * day) + (10000*hour) + (100*minute) + second)
97
98def convertValueToCSML(t):
99    #this may need to be more robust
100    csmlt='%s-%s-%sT%s:%s:%s.%s'%(int(t/10000000000),str(int(t/100000000))[-2:],str(int(t/1000000))[-2:]
101,str(int(t/10000))[-2:],str(int(t/100))[-2:],str(int(t))[-2:],0)
102    return csmlt
103
104
105def getCDtime(time): 
106    year=int(time.split('-')[0])
107    month=int(time.split('-')[1])
108    day=int(time.split('-')[2].split('T')[0])
109    hour=int(time.split('-')[2].split('T')[1].split(':')[0])
110    minute=int(time.split('-')[2].split('T')[1].split(':')[1])
111    second=float(time.split('-')[2].split('T')[1].split(':')[2])
112    cdTimeVal=cdtime.comptime(year,month,day,hour,minute,second)
113    return cdTimeVal
114
115def getBaseUnits(cdtime):
116    baseunit='days'
117    units=['second', 'minute', 'hour']
118    for unit in units:
119        val=getattr(cdtime, unit)
120        if val > 0:
121            baseunit=unit
122            break
123    return '%s since %s'%(baseunit, cdtime)
124   
125
126
127def getFileTimeList(filelist, timedim):
128        #****************************************************************************************
129        #Given a list of files and a name for the time dimension this function will return a list containing
130        # filename/time pairs eg tuple [(ta,fa),(tb,fb),(tc,fc)] in the correct temporal order.
131        #if files contain more than one time, then the tuple will be of the form:
132        #[(ta1,ta2,ta3,fa),(tb1,tb2,tb3,fb),(tc1,tc2,tc3,fc)]
133        #*****************************************************************************************
134        FileTimeList = []  #list to hold the filesnames and corrsponding times
135        DI=csml.csmllibs.csmldataiface.DataInterface()
136        #grab any (first) file                 
137        DI=DI.getUnknownInterfaceType(filelist[0])
138        count=0
139        for file in filelist:
140                count=count +1
141                DI.openFile(file)
142                try:
143                        DI.setAxis(timedim)
144                        data =DI.getDataForAxis()
145                except:
146                        try:
147                            data=DI.getTimes()
148                        except:
149                            print 'tried alternative method to get time axis and failed'
150                            print "check you have the correct time axis (-t) set"
151                            sys.exit()
152                times=[]
153                for j in range(0,len(data)):
154                        times.append(data[j])
155                refTime=DI.getTimeUnits()   #maybe this can be optional?
156                ftTuple = (times, file,refTime)
157                FileTimeList.append(ftTuple)
158                DI.closeFile()
159                if count % 20 == 0:
160                        print 'scanning file %s of %s'%(count,len(filelist))
161        #get calendar type:
162        DI.openFile(filelist[0])
163        try:
164            DI.setAxis(timedim)
165            cal = DI.getAxisAttribute('calendar')
166            setcdtimeCalendar(cal)
167        except:
168            print 'No calendar attribute, defaulting to CF standard mixed calendar'
169            cal='standard'
170            setcdtimeCalendar(cal)
171        try:
172            units=DI.getAxisAttribute('units')
173        except:
174            print "Could not get time unit info"
175            units =''
176        FileTimeList.sort()
177        #get the reference date for the time reference system.
178        #refTime=DI.getTimeUnits()
179        DI.closeFile()
180        FormattedFileTimeList = []
181        for j in range (0,len(FileTimeList)):
182                timeList = FileTimeList[j][0]
183                refTime=FileTimeList[j][2]
184                #print 'timelist_____________________' +str(timeList)
185                for k in range(0, len(timeList)):
186                        relativetime= cdtime.reltime(timeList[k], refTime)
187                        uduTime=UDtimeToCSMLtime(relativetime.tocomp())
188                        ftTuple = (uduTime, filelist[j])
189                        FormattedFileTimeList.append(ftTuple)                   
190        print  'finished time list'
191        return FormattedFileTimeList, cal,units
Note: See TracBrowser for help on using the repository browser.