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

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

some prep for 2.6

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