source: CMIP6dreq/trunk/dreqPy/scope.py @ 460

Subversion URL: http://proj.badc.rl.ac.uk/svn/exarch/CMIP6dreq/trunk/dreqPy/scope.py@460
Revision 460, 16.1 KB checked in by mjuckes, 5 years ago (diff)

Updated request

Line 
1"""Date Request Scoping module
2---------------------------
3The scope.py module contains the dreqQuery class and a set of ancilliary functions. The dreqQuery class contains methods for analysing the data request.
4"""
5import dreq
6from utilities import cmvFilter
7import collections, string, operator
8import sys
9
10python2 = True
11if sys.version_info.major == 3:
12  python2 = False
13  from functools import reduce
14
15class baseException(Exception):
16  """Basic exception for general use in code."""
17
18  def __init__(self,msg):
19    self.msg = 'scope:: %s' % msg
20
21  def __str__(self):
22    return repr( self.msg )
23
24  def __repr__(self):
25    return self.msg
26
27nt_mcfg = collections.namedtuple( 'mcfg', ['nho','nlo','nha','nla','nlas','nls','nh1'] )
28class cmpd(object):
29  def __init__(self,dct):
30    self.d = dct
31  def cmp(self,x,y,):
32    return cmp( self.d[x], self.d[y] )
33
34    self.default_mcfg = nt_mcfg._make( [259200,60,64800,40,20,5,100] )
35
36def filter1( a, b ):
37  if b < 0:
38    return a
39  else:
40    return min( [a,b] )
41
42npy = {'daily':365, u'Annual':1, u'fx':0.01, u'1hr':24*365, u'3hr':8*365, u'monClim':12, u'Timestep':100, u'6hr':4*365, u'day':365, u'1day':365, u'mon':12, u'yr':1, u'1mon':12, 'month':12, 'year':1, 'monthly':12, 'hr':24*365, 'other':24*365, 'subhr':24*365, 'Day':365, '6h':4*365,
43'3 hourly':8*365, '':1 }
44## There are 4 cmor variables with blank frequency ....
45
46def vol01( sz, v, npy, freq, inx ):
47  n1 = npy[freq]
48  s = sz[inx.uid[v].stid]
49  assert type(s) == type(1), 'Non-integer size found for %s' % v
50  assert type(n1) in (type(1),type(0.)), 'Non-number "npy" found for %s, [%s]' % (v,freq)
51  return s*n1
52
53class col_list(object):
54  def __init__(self):
55    self.a = collections.defaultdict(list)
56
57class col_count(object):
58  def __init__(self):
59    self.a = collections.defaultdict(int)
60
61class dreqQuery(object):
62  __doc__ = """Methods to analyse the data request, including data volume estimates"""
63  def __init__(self,dq=None,tierMax=-1):
64    if dq == None:
65      self.dq = dreq.loadDreq()
66    else:
67      self.dq=dq
68    self.rlu = {}
69    for i in self.dq.coll['objective'].items:
70      k = '%s.%s' % (i.mip,i.label)
71      assert not k in self.rlu, 'Duplicate label in objectives: %s' % k
72      self.rlu[k] = i.uid
73
74    self.cmvFilter = cmvFilter( self )
75    self.tierMax = tierMax
76    self.mips = { i.mip for i in  self.dq.coll['requestItem'].items}
77    self.mipls = sorted( list( self.mips ) )
78
79    self.default_mcfg = nt_mcfg._make( [259200,60,64800,40,20,5,100] )
80    self.mcfg = {}
81    for k in self.default_mcfg.__dict__.keys():
82      self.mcfg[k] = self.default_mcfg.__dict__[k]
83    self.szcfg()
84    self.requestItemExpAll(  )
85
86  def szcfg(self):
87    self.szss = {}
88    self.sz = {}
89    for i in self.dq.coll['spatialShape'].items:
90      type = 'a'
91      if i.levelFlag == False:
92        ds =  i.dimensions.split( '|' )
93        if ds[-1] in ['site', 'basin']:
94          vd = ds[-2]
95        else:
96          vd = ds[-1]
97 
98        if vd[:4] == 'olev' or vd == 'rho':
99          type = 'o'
100          nz = self.mcfg['nlo']
101        elif vd[:4] == 'alev':
102          nz = self.mcfg['nla']
103        elif vd in ['slevel','sdepth']:
104          nz = self.mcfg['nls']
105        elif vd == 'aslevel':
106          nz = self.mcfg['nlas']
107        else:
108          print ( 'Failed to parse dimensions %s' % i.dimensions )
109          raise
110      else:
111        nz = i.levels
112
113      dims = set( i.dimensions.split( '|' ) )
114      if 'latitude' in dims and 'longitude' in dims:
115        if type == 'o':
116          nh = self.mcfg['nho']
117        else:
118          nh = self.mcfg['nha']
119      else:
120        nh = 10
121
122      self.szss[i.uid] = nh*nz
123    for i in self.dq.coll['structure'].items:
124      s = self.szss[i.spid]
125      if i.odims != '':
126        s = s*5
127      self.sz[i.uid] = s
128
129  def getRequestLinkByMip( self, mipSel ):
130    """Return the set of request links which are associated with specified MIP"""
131    if type(mipSel) == type(''):
132      t1 = lambda x: x == mipSel
133    elif type(mipSel) == type({1,2}):
134      t1 = lambda x: x in mipSel
135    self.rqs = list({self.dq.inx.uid[i.rid] for i in self.dq.coll['objectiveLink'].items if t1(i.label) })
136    return self.rqs
137
138  def getRequestLinkByObjective( self, objSel ):
139    """Return the set of request links which are associated with specified objectives"""
140    if type(objSel) == type(''):
141      t1 = lambda x: x == self.rlu[objSel]
142    elif type(objSel) == type({1,2}):
143      t1 = lambda x: x in {self.rlu[i] for i in objSel}
144
145    self.rqs = list({self.dq.inx.uid[i.rid] for i in self.dq.coll['objectiveLink'].items if t1(i.oid) })
146    return self.rqs
147
148  def varGroupXexpt(self, rqList ):
149    """For a list of request links, return a list of variable group IDs for each experiment"""
150    self.cc = collections.defaultdict( list )
151    dummy = {self.cc[i.expt].append(i.rlid) for i in self.dq.coll['requestItem'].items if i.rlid in {j.uid for j in rqList} }
152    return self.cc
153
154  def yearsInRequest(self, rql ):
155    self.ntot = sum( [i.ny for i in self.dq.coll['requestItem'].items if i.rlid == rql.uid] )
156    return self.ntot
157
158  def volByExpt( self, l1, ex, exptList, pmax=2, cc=None, retainRedundantRank=False, intersection=False ):
159    """volByExpt: calculates the total data volume associated with an experiment/experiment group and a list of request items.
160          The calculation has some approximations concerning the number of years in each experiment group."""
161##
162## cc: an optional collector, to accumulate indexed volumes
163##
164    inx = self.dq.inx
165    imips = {i.mip for i in l1}
166##
167## rql is the set of all request links which are associated with a request item for this experiment set
168##
169    l1p = {i for i in l1 if (i.esid == ex) and (i.preset < 0 or i.preset <= pmax) }
170
171    rql0 = {i.rlid for i in l1p}
172
173    rqlInv = {u for u in rql0 if inx.uid[u]._h.label == 'remarks' }
174    if len(rqlInv) != 0:
175      print ( 'WARNING.001.00002: %s invalid request links from request items ...' % len(rqlInv) )
176    rql = {u for u in rql0 if inx.uid[u]._h.label != 'remarks' }
177    if len( rql ) == 0:
178      self.vars = set()
179      return (0,{},{} )
180
181## The complete set of variables associated with these requests:
182    tm = 1
183    if tm == 0:
184      rqvg = list({inx.uid[i].refid for i in rql})
185    else:
186      cc1 = collections.defaultdict( set )
187      for i in rql:
188        cc1[inx.uid[i].mip].add( inx.uid[i].refid )
189
190      if intersection:
191        ccv = {}
192#
193# set of request variables for each MIP
194##
195        for k in cc1:
196          thisc = reduce( operator.or_, [set( inx.iref_by_sect[vg].a['requestVar'] ) for vg in cc1[k] ] )
197          ccv[k] = {inx.uid[l].vid for l in list(thisc) if inx.uid[l].priority <= pmax}
198
199        if len( ccv.keys() ) < len( list(imips) ):
200          vars = set()
201        else:
202          vars =  reduce( operator.and_, [ccv[k] for k in ccv] )
203      else:
204        rqvg = reduce( operator.or_, [cc1[k] for k in cc1] )
205
206###To obtain a set of variables associated with this collection of variable groups:
207
208        col1 = reduce( operator.or_, [set( inx.iref_by_sect[vg].a['requestVar'] ) for vg in rqvg ] )
209
210###The collector col1 here accumulates all the record uids, resulting in a single collection. These are request variables, to get a set of CMOR variables at priority <= pmax:
211        vars = {inx.uid[l].vid for l in list(col1) if inx.uid[l].priority <= pmax}
212##
213## if looking for the union, would have to do a filter here ... after looking up which vars are requested by each MIP ...
214##
215## possibly some code re-arrangement would help.
216## e.g. create a set for each MIP a couple of lines back ....
217
218### filter out cases where the request does not point to a CMOR variable.
219    ##vars = {vid for vid in vars if inx.uid[vid][0] == u'CMORvar'}
220    vars = {vid for vid in vars if inx.uid[vid]._h.label == u'CMORvar'}
221##
222## filter by configuration option and rank
223##
224    if not retainRedundantRank:
225      len1 = len(vars)
226      cmv = self.cmvFilter.filterByChoiceRank(cmv=vars)
227
228      vars = cmv
229   
230    self.vars = vars
231
232    e = {}
233    for u in rql:
234### for request variables which reference the variable group attached to the link, add the associate CMOR variables, subject to priority
235      i = inx.uid[u]
236      e[i.uid] = { inx.uid[x].vid for x in inx.iref_by_sect[i.refid].a['requestVar'] if inx.uid[x].priority <= pmax}
237#
238# for each variable, calculate the maximum number of years across all the request links which reference that variable.
239##
240## for each request item we have nymax, nenmax, nexmax.
241##
242    nym = {}
243    for v in vars:
244      nym[v] = max( {self.rqiExp[i.uid][2] for i in l1p if i.esid == ex and v in e[i.rlid]} )
245
246    szv = {}
247    ov = []
248    for v in vars:
249      szv[v] = self.sz[inx.uid[v].stid]*npy[inx.uid[v].frequency]
250      ov.append( self.dq.inx.uid[v] )
251    ee = self.listIndexDual( ov, 'frequency', 'label', acount=None, alist=None, cdict=szv, cc=cc )
252    ff = {}
253    for v in vars:
254      ff[v] = self.sz[ inx.uid[v].stid ] * npy[inx.uid[v].frequency] * nym[v]
255    self.ngptot = sum( [  ff[v]  for v in vars] )
256    return (self.ngptot, ee, ff )
257
258  def esid_to_exptList(self,esid,deref=False):
259    if not esid in self.dq.inx.uid:
260      print ( 'Attempt to dereferece invalid uid: %s' % esid )
261      raise
262
263    if self.dq.inx.uid[esid]._h.label == 'experiment':
264      expts = [esid,]
265    elif self.dq.inx.uid[esid]._h.label != 'remarks':
266      if esid in self.dq.inx.iref_by_sect and 'experiment' in self.dq.inx.iref_by_sect[esid].a:
267        expts = self.dq.inx.iref_by_sect[esid].a['experiment']
268      else:
269        expts = []
270    else:
271      ##print ( 'WARNING: request link not associated with valid experiment group' )
272      ##raise
273      return None
274
275    if self.tierMax > 0:
276      expts = [i for i in expts if self.dq.inx.uid[i].tier <= self.tierMax]
277
278    if deref:
279      return [self.dq.inx.uid[e] for e in expts]
280    else:
281      return expts
282 
283##
284## need to call this on load
285## then use instead of i.ny etc below
286##
287  def requestItemExpAll( self ):
288    self.rqiExp = {}
289    for rqi in self.dq.coll['requestItem'].items:
290      a,b,c = self.requestItemExp( rqi )
291      if a != None:
292        self.rqiExp[rqi.uid] = (a,b,c)
293
294  def requestItemExp( self, rqi ):
295    assert rqi._h.label == "requestItem", 'Argument to requestItemExp must be a requestItem'
296    u = rqi.esid
297    if self.dq.inx.uid[u]._h.label == 'experiment':
298      expts = [u,]
299    elif self.dq.inx.uid[u]._h.label != 'remarks':
300      if u in self.dq.inx.iref_by_sect and 'experiment' in self.dq.inx.iref_by_sect[u].a:
301        expts = self.dq.inx.iref_by_sect[u].a['experiment']
302      else:
303        expts = []
304    else:
305      # print ( 'WARNING: request link not associated with valid experiment group'  )
306      ##rqi.__info__()
307      ##raise
308      return (None, None, None)
309
310    if self.tierMax > 0:
311      expts = [i for i in expts if self.dq.inx.uid[i].tier <= self.tierMax]
312
313    if len(expts) > 0:
314      e = [self.dq.inx.uid[i] for i in expts]
315      dat = [ (i.ntot, i.yps, i.ensz, i.nstart, filter1(i.yps,rqi.nymax), filter1(i.ensz,rqi.nenmax) ) for i in e]
316      nytot = sum( [x[-2]*x[-1] for x in dat ] )
317    else:
318      dat = [ (0,0,0,0,0) ]
319      nytot = 0
320   
321    return (expts, dat, nytot )
322   
323
324  def setTierMax( self, tierMax ):
325    """Set the maxium tier and recompute request sizes"""
326    if tierMax != self.tierMax:
327      self.tierMax = tierMax
328      self.requestItemExpAll(  )
329
330  def summaryByMip( self, pmax=1 ):
331    bytesPerFloat = 2.
332    for m in self.mipls:
333      v = self.volByMip( m, pmax=pmax )
334      print ( '%12.12s: %6.2fTb' % (m,v*bytesPerFloat*1.e-12) )
335
336  def volByMip( self, mip, pmax=2, retainRedundantRank=False):
337
338    if type(mip) in {type( '' ),type( u'') }:
339      if mip not in self.mips:
340        print ( self.mips )
341        raise baseException( 'volByMip: Name of mip not recognised: %s' % mip )
342      l1 = [i for i in  self.dq.coll['requestItem'].items if i.mip == mip]
343    elif type(mip) == type( set()):
344      nf = [ m for m in mip if m not in self.mips]
345      if len(nf) > 0:
346        raise baseException( 'volByMip: Name of mip(s) not recognised: %s' % str(nf) )
347      l1 = [i for i in  self.dq.coll['requestItem'].items if i.mip in mip]
348    else:
349      raise baseException( 'volByMip: "mip" (1st explicit argument) should be type string or set: %s -- %s' % (mip, type(mip))   )
350     
351    #### The set of experiments/experiment groups:
352    exps = {i.esid for i in l1}
353    self.volByE = {}
354    vtot = 0
355    cc = collections.defaultdict( col_count )
356    self.allVars = set()
357    for e in exps:
358      expts = self.esid_to_exptList(e,deref=True)
359      if expts != None:
360        self.volByE[e] = self.volByExpt( l1, e, expts, pmax=pmax, cc=cc, retainRedundantRank=retainRedundantRank )
361        vtot += self.volByE[e][0]
362        self.allVars = self.allVars.union( self.vars )
363    self.indexedVol = cc
364
365    return vtot
366
367  def listIndexDual(self, ll, a1, a2, acount=None, alist=None, cdict=None, cc=None ):
368    do_count = acount != None
369    do_list = alist != None
370    assert not (do_count and do_list), 'It is an error to request both list and count'
371    if not (do_count or do_list):
372      acount = '__number__'
373      do_count = True
374
375    if cc == None:
376      if do_count:
377        cc = collections.defaultdict( col_count )
378      elif do_list:
379        cc = collections.defaultdict( col_list )
380
381    if do_count:
382      for l in ll:
383        if cdict != None:
384          v = cdict[l.uid]
385        elif acount == '__number__':
386          v = 1
387        else:
388          v = l.__dict__[acount]
389
390        cc[ l.__dict__[a1] ].a[ l.__dict__[a2] ] += v
391    elif do_list:
392      for l in ll:
393        if cdict != None:
394          v = cdict[l.uid]
395        elif alist == '__item__':
396          v = l
397        else:
398          v = l.__dict__[alist]
399        cc[ l.__dict__[a1] ].a[ l.__dict__[a2] ].append( v )
400
401    od = {}
402    for k in cc.keys():
403      d2 = {}
404      for k2 in cc[k].a.keys():
405        d2[k2] = cc[k].a[k2]
406      od[k] = d2
407    return od
408
409class dreqUI(object):
410  """Data Request Command line.
411-------------------------
412      -v : print version and exit;
413      --unitTest : run some simple tests;
414      -m <mip>:  MIP of list of MIPs (comma separated);
415      -h :       help: print help text;
416      -t <tier> maxmum tier;
417      -p <priority>  maximum priority;
418      --printLinesMax <n>: Maximum number of lines to be printed
419      --printVars  : If present, a summary of the variables fitting the selection options will be printed
420"""
421  def __init__(self,args):
422    self.adict = {}
423    self.knownargs = {'-m':('m',True), '-p':('p',True), '-t':('t',True), '-h':('h',False), '--printLinesMax':('plm',True), '--printVars':('vars',False)} 
424    aa = args[:]
425    while len(aa) > 0:
426      a = aa.pop(0)
427      if a in self.knownargs:
428        b = self.knownargs[a][0]
429        if self.knownargs[a][1]:
430          v = aa.pop(0)
431          self.adict[b] = v
432        else:
433          self.adict[b] = True
434
435    if 'm' in self.adict:
436      self.adict['m'] = set(self.adict['m'].split(',') )
437
438    integerArgs = {'p','t','plm'}
439    for i in integerArgs.intersection( self.adict ):
440      self.adict[i] = int( self.adict[i] )
441
442  def run(self, dq=None):
443    if 'h' in self.adict:
444      print ( self.__doc__ )
445      return
446
447    if not 'm' in self.adict:
448      print ( 'Current version requires -m argument'  )
449      print ( self.__doc__ )
450      sys.exit(0)
451
452    if dq == None:
453      self.dq = dreq.loadDreq()
454    else:
455      self.dq = None
456
457    sc = dreqQuery( dq=self.dq )
458
459    ok = True
460    for i in self.adict['m']:
461        if i not in sc.mips:
462          ok = False
463          print ( 'NOT FOUND: ',i )
464    assert ok,'Available MIPs: %s' % str(sc.mips)
465
466    tierMax = self.adict.get( 't', 2 )
467    sc.setTierMax(  tierMax )
468    pmax = self.adict.get( 'p', 2 )
469    v0 = sc.volByMip( self.adict['m'], pmax=pmax )
470    print ( '%7.2fTb' % (v0*2.*1.e-12) )
471    cc = collections.defaultdict( int )
472    for e in sc.volByE:
473      for v in sc.volByE[e][2]:
474          cc[v] += sc.volByE[e][2][v]
475    x = 0
476    for v in cc:
477      x += cc[v]
478   
479    if python2:
480      vl = sorted( cc.keys(), cmp=cmpd(cc).cmp, reverse=True )
481    else:
482      vl = sorted( cc.keys(), key=lambda x: cc[x], reverse=True )
483    if self.adict.get( 'vars', False ):
484      printLinesMax = self.adict.get( 'plm', 20 )
485      if printLinesMax > 0:
486        mx = min( [printLinesMax,len(vl)] )
487      else:
488        mx = len(vl)
489
490      for v in vl[:mx]:
491        print ( self.dq.inx.uid[v].label, '%7.2fTb' % (cc[v]*2.*1.e-12) )
Note: See TracBrowser for help on using the repository browser.