source: CMIP6dreqbuild/trunk/srcMisc/sx202.py @ 926

Subversion URL: http://proj.badc.rl.ac.uk/svn/exarch/CMIP6dreqbuild/trunk/srcMisc/sx202.py@926
Revision 926, 40.7 KB checked in by mjuckes, 3 years ago (diff)

stripped sx203.py from sx202.py

Line 
1
2##
3# still missing map from new groups to old table variables.
4## need a key lookup by variable in each table.
5##
6
7import collections, string, hashlib, uuid, os, sys, json
8import shelve
9import dreqSX as sx
10import dreq_utils
11import utils_wb
12
13from dreq_utils import labcoerce
14odir = 'sh20150827'
15
16vdate = '20150907'
17vdate = '20160309'
18if not os.path.isdir( odir ):
19  os.mkdir( odir )
20
21class uid1(object):
22  def __init__(self, uid=None):
23    if uid == None:
24      self.uid = str( uuid.uuid1() )
25    else:
26      self.uid = uid
27
28uidgen = collections.defaultdict( uid1 )
29
30if sx.doCmipVar:
31  sh1 = shelve.open( '%s/cmip5Groups' % odir, 'n' )
32##
33## list of CMIP5 tables which have groups
34##
35  cmip5GroupsIx = set()
36##
37## dictionary, specifying group for each variable in table
38##
39  cmip5GroupsIVAR = collections.defaultdict( dict )
40  for k in sx.cmip5so.sop.keys():
41    sh1[k] = sx.cmip5so.sop[k][:]
42    cmip5GroupsIx.add( string.split( k, '_' )[0] )
43    for v in sx.cmip5so.sop[k]:
44      cmip5GroupsIVAR[ string.split( k, '_' )[0] ][v] = k
45    if sx.cmip5so.omipInsert and k in sx.cmip5so.sxp:
46      for v in sx.cmip5so.sxp[k]:
47        cmip5GroupsIVAR[ string.split( k, '_' )[0] ][v] = k
48  sh1.close()
49#### 'uuid', 'mip', 'label','title','ref','refNote'
50####  i, "CMIP6",  key, ...., "CMIP5", ''
51cmip5tbs = []
52cmip5tbs0 = set()
53cmip5gps = []
54cmip5gplk = {}
55for k in sx.cmip5so.so.keys():
56  u = str( uuid.uuid1() )
57  cmip5gplk[k] = u
58  cmip5tbs0.add( k )
59  cmip5tbs.append( [u,"CMIP6",k,"CMIP6 CMOR Table: %s" % k, "CMIP5", "CMIP5 MIP Table: %s" % k] )
60
61for k in ['aermonthly','aerhourly','aerfixed','aerdaily','aerannual']:
62  u = str( uuid.uuid1() )
63  cmip5gplk[k] = u
64  cmip5tbs0.add( k )
65  cmip5tbs.append( [u,"AerChemMIP",k,"CMIP6 CMOR Table: %s" % k, "CMIP6 [AerChemMIP]", "MIP Table: %s" % k] )
66
67for k in sx.cmip5so.sop.keys():
68  u = str( uuid.uuid1() )
69  cmip5gplk[k] = u
70  t,s = string.split( k, '_' )
71  assert sx.cmip5so.so.has_key(t), 'Table for group %s not found' % k
72  u2 = cmip5gplk[t]
73  cmip5gps.append( [u,u2,"CMIP6",k,"CMIP6 Variable Group: %s" % k, "CMIP5", "CMIP5 MIP Table section: %s" % k] )
74  u3 = str( uuid.uuid1() )
75### section link .... variables in sections are linked to a section which carries a link to the group.
76### request links can refer to a section or a group .....
77
78cmip5vgr = ['Omon','fx','Oyr','Oclim','Omon_3d','Omon_oth','Amon','Lmon','LImon','OImon','aero_3d','aero_oth','cfDay_2d','cfDay_3d','cfMon_3dstd','cfMon_3dmod','cfMon_2dmod','cfMon_sim','day_oth','day_ss','cfOff','cfSites','6hrLev','6hrPlev','3hr','cf3hr_grid','cf3hr_sim']
79ccmivgrdict = {'fixed':'fx','annual':'yr','monthly':'mon','daily':'day','hourly':'hr'}
80specsvgr =  ['fx','mon','day','6hr']
81
82ee_var_nv1 = collections.defaultdict( list )
83ee_tabs = collections.defaultdict( list )
84ee_grps = collections.defaultdict( list )
85ee_usedVars = collections.defaultdict( list )
86
87kmap = { 'cfday':'cfDay', 'Limon':'LImon', 'CMIP5_Llmon':'CMIP5_LImon', 'CMIP5 day':'CMIP5_day', 'NEW':'new', 'New':'new', \
88         'CCMI monthly mean 3d':'CCMI1_monthly', \
89         'CCMI Daily zonal mean 2d':'CCMI1_daily', \
90         'CCMI monthly mean zonal mean 2d':'CCMI1_monthly', \
91         'PMIP-LImon':'PMIP_LImon', 'CMIP5 Amon':'CMIP5_Amon', 'CCMI monthly':'CCMI1_monthly', 'PMIP-OImon':'PMIP_OImon'}
92
93##
94## sx.eenv: from dreq_consol_tables_nv_shelve_v ... which is from dreq_consol_tables.py
95for k in sx.eenv.keys():
96  mip = string.strip(sx.eenv[k][1])
97  var = string.strip(sx.eenv[k][5])
98  uid = sx.eenv[k][-1]
99  ## ee_var_nv1 used to check ee0 ...
100  ee_var_nv1[var].append( k )
101  assert uid == k, 'mismatch in uid in record %s' % k
102
103def tabref1( ti ):
104  if ti == 'new BUT':
105    return 'CMIP5_Lmon'
106  elif ti == 'new':
107    return 'new'
108  else:
109    return ti
110
111for k in sx.ee0.keys():
112  r = sx.ee0[k]
113  mip = r[10]
114  assert mip == r[-3],'Double check failed'
115  tab = r[2]
116  grp = r[0]
117  thistab = tabref1(tab)
118  ##ee_tabs[tab].append(k)
119  ee_tabs[thistab].append(k)
120  if grp == 'icesheetmon':
121    ee_grps['LImonant'].append(k)
122    ee_grps['LImongre'].append(k)
123  elif grp == 'icesheetyear':
124    ee_grps['LIyrant'].append(k)
125    ee_grps['LIyrgre'].append(k)
126  elif grp == 'icesheetfx':
127    ee_grps['LIfxant'].append(k)
128    ee_grps['LIfxgre'].append(k)
129  else:
130    ee_grps[grp].append(k)
131
132import sys
133
134kf = []
135kfn = []
136kfxx = []
137kfgp = []
138knf = []
139kmapmap = {}
140for k in ee_tabs.keys():
141  k1 = kmap.get( k,k)
142  if string.find( k1, ' ' ) != -1:
143    k2 = string.split(k1)[0]
144  else:
145    k2 = k
146
147  k2 = kmap.get( k2,k2)
148
149  if k2 in ['new','']:
150     kfn.append(k)
151     kmapmap[k] = 'new'
152  elif sx.ee_miptables_old.has_key(k2):
153     kf.append(k)
154     kmapmap[k] = k2
155  elif ee_grps.has_key(k2):
156     kfgp.append(k)
157     kmapmap[k] = k2
158  else:
159    if sx.ee_miptables_old.has_key('CMIP5_%s' % k2 ):
160      kfxx.append(k)
161      kmapmap[k] = 'CMIP5_%s' % k2
162    else:
163      knf.append(k)
164
165thisd = {}
166print 'Missing groups'
167for k in knf:
168  thise = collections.defaultdict( int )
169  for k2 in ee_tabs[k]:
170    thise[sx.ee0[k2][12-2]] += 1
171  keys = thise.keys()
172  keys.sort()
173  thisd[k] = keys[:]
174  print 'ERROR.020.0001: Missing Group: %s :: %s' % (k, keys)
175   
176### look for new variables in variable groups.
177class d1(object):
178  def __init__(self):
179    self.d = collections.defaultdict( list )
180    self.onItemNotFound = 'error'
181
182  def keys(self):
183    return self.d.keys()
184
185  def __setitem__(self,k,v):
186    self.d[k].append(v)
187
188  def __itemNotFound__(self,k):
189    if self.onItemNotFound == 'error':
190      raise  KeyError( 'Key %s not found in dictionary keys' % k)
191   
192  def __getitem__(self,k):
193    if self.d.has_key(k):
194      return self.d[k]
195    else:
196      return self.__itemNotFound__(k)
197
198## look up table, giving uuid from old mip tables for each mip, var combination.
199mvlookup = collections.defaultdict( d1 )
200mvlookup2 = collections.defaultdict( list )
201
202ee_unusedVars = []
203nok = 0
204nn = 0
205ee0_null = collections.defaultdict( list )
206ee0_xref = collections.defaultdict( list )
207ee0_xref_old = collections.defaultdict( list )
208for t in sx.ee_miptables_old.keys():
209  for u in sx.ee_miptables_old[t]:
210    v1 = sx.ee_mip[u][15]
211    v2 = sx.ee_mip[u][21]
212    if v2 != '':
213      vid = v2
214    else:
215      vid = v1
216    mvlookup[t].d[vid].append( u )
217
218for u in sx.eeold.keys():
219  pr = sx.eeold[u][6].split(',')
220  if all( [x.find('SPECS') for x in pr] ):
221    pass
222  else:
223    mvlookup2[sx.eeold[u][1]].append(  u )
224
225##
226## ee0_xref values are values of ee_var_nv1 
227## ee0_xref is used to generate vid .... later done in importShDreq2.py .... could simplify this ....
228## get vars table from workbooks/inputs and cut out that section of dreq_consol_....
229## and add section to review consistency of above with templates.
230##
231for u in sx.ee0.keys():
232    var = string.strip(sx.ee0[u][1])
233    tab =  kmapmap.get(tabref1(sx.ee0[u][2]), None )
234    if ee_var_nv1.has_key(var):
235      nok += 1
236      ee_usedVars[var].append( u )
237## reference to kex in eenv
238      ee0_xref[u] += ((0,ee_var_nv1[var] ),)
239    elif ee_var_nv1.has_key(var + "**"):
240      nok += 1
241      ee_usedVars[var].append( u )
242      ee0_xref[u] += ((0,ee_var_nv1[var + "**"] ),)
243    else:
244      ok = False
245      if mvlookup.has_key(tab):
246        if mvlookup[tab].d.has_key( var ):
247          ul = mvlookup[tab].d[var]
248          if len(ul) > 1:
249            print 'ERROR.001.011: variable %s has multiple entries %s' % (var,tab)
250          ee0_xref[u] += ((1,[ul[0],]),)
251          ok = True
252        else:
253          emsg = '.001.010: variable %s not found in %s' % (var,tab)
254      else:
255          emsg = '.001.012: [%s] table not found: %s' % (var,tab)
256
257      if not ok:
258        if mvlookup2.has_key( var ):
259          if len( mvlookup2[var] ) == 1:
260             ee0_xref[u] += ((2,[mvlookup2[var][0],]),)
261             ok = True
262             print 'WARN' + emsg + ' [alternative found]'
263          else:
264            print 'ERROR' + emsg
265
266      if not ok:
267        print 'ERROR.090.077000:',tab,sx.ee0[u]
268        ee0_xref[u] += ((-1,['__var_not_found_012__',]),)
269 
270        if ( len(sx.ee0[u][1]) > 0 and sx.ee0[u][1][0] == '#' ) or ( len(sx.ee0[u][0]) > 0 and sx.ee0[u][0][0] == '#' ):
271          ee0_null[u].append( '# comment' )
272        elif ( len(sx.ee0[u][0]) > 5 and sx.ee0[u][0][:4] == 'PMIP' ) and ( sx.ee0[u][1] in ['','*'] ):
273          ee0_null[u].append( 'PMIP bulk copy' )
274        elif len(sx.ee0[u][1]) == 0 and  len(sx.ee0[u][2]) == 0:
275          ee0_null[u].append( 'comment' )
276        else:
277          nn += 1
278          ee_unusedVars.append((u,var))
279   
280print nn, nok
281nok = 0
282nn = 0
283thise1 = []
284uclear = {}
285### run through CMIP5 variables which are modified, re-used etc in new CMIP6 groups.
286### 43 not found .... as above .....
287for k in kf + kfxx:
288  k2 = kmapmap[k]
289  for u in ee_tabs[k]:
290    var = string.strip(sx.ee0[u][1] )
291    if not var in sx.ee_miptables_vars_old[k2]:
292       print 'ERROR.0001.002: variables in sx.ee0 [new groups] not found: ',k,var,sx.ee0[u]
293       nn += 1
294    else:
295       ee_usedVars[var].append( u )
296
297    ok = False
298    if sx.ee_ovars_old.has_key('%s.%s' % (k2,var)):
299      uclear[u] = sx.ee_ovars_old['%s.%s' % (k2,var)]
300      ok = True
301    elif sx.ee_ovars_old.has_key('%s.%s**' % (k2,var)):
302      uclear[u] = sx.ee_ovars_old['%s.%s**' % (k2,var)]
303      ok = True
304    elif len(string.split( k, ' ')) > 1:
305      bits = string.split( k, ' ')
306      v1 = string.strip(bits[1])[1:-1]
307      if sx.ee_ovars_old.has_key('%s.%s' % (k2,v1)):
308        uclear[u] = sx.ee_ovars_old['%s.%s' % (k2,v1)]
309        ok = True
310     
311    if not ok:
312      thise1.append((u,k2,var))
313       ##ee0_xref_old[u]
314
315ee_mv0 = {}
316ee_mv1 = {}
317ee_mv2 = {}
318ee_mv3 = {}
319for k in sx.eeold.keys():
320  k1 = sx.eeold[k][7]
321  assert k1[:3] == 'mv.', 'Key not in correct syntax: %s' % k1
322  ee_mv0[k1] = k
323  k2 = sx.eeold[k][8]
324  if k2 != "":
325    if k2 in ["*omit",'null','Depricated']:
326      if k2 in ["*omit",'Depricated']:
327        ee_mv3[ k1 ] = k2
328    else:
329      starflag = False
330      if k2[0] == '*':
331        k2 = k2[1:]
332        starflag = True
333      assert k2[:3] == 'mv.', 'target key not in correct syntax: %s' % k2
334      if starflag:
335        ee_mv2[k1] = k2
336      else:
337        ee_mv1[k1] = k2
338
339for k in ee_mv1.keys():
340  assert ee_mv0.has_key(k), 'key cross-ref not found: %s' % k
341
342ll_ov = []
343for k in ee_mv0.keys():
344  if not (ee_mv3.has_key(k) or ee_mv1.has_key(k)):
345    ll_ov.append( ee_mv0[k] )
346print 'Number of old variables: %s [%s]' % (len(ll_ov), len(ee_mv0.keys()) )
347print len(sx.eenv.keys())
348print "Number of new variables: %s" % ( len(sx.eenv.keys()) )
349##
350## extract variable name, units, standard name, long name, comment
351nt_vrecix = collections.namedtuple( 'vrecix', ['v','u','s','l','c'] )
352vrecix_new = nt_vrecix._make( (5,9,6,10,11) )
353vrecix_old = nt_vrecix._make( (1,5,3,2,4) )
354
355nnf = 0
356nnm = 0
357nno = 0
358for k in sx.ee_mip.keys():
359   t = map( lambda x: sx.ee_mip[k][x], [15,10,8,1,17] )
360   h = hashlib.md5(string.join(t) ).hexdigest()
361   if not sx.ee_xref_bck.has_key(k):
362     r1 = sx.ee_mip[k][1]
363     if r1 in ['','29'] or r1[:23] == 'Reference to literature' or r1[:15] == '(copied from 3D':
364       print 'WARN.002.0010: dud record',sx.ee_mip[k], sx.ee_mip[k][-2][:4] 
365     else:
366       print 'ERROR.002.0010: missing back reference',sx.ee_mip[k], sx.ee_mip[k][-2][:4] 
367       nnf += 1
368   elif len(sx.ee_xref_bck[k]) > 1:
369     nnm += 1
370     print 'ERROR.0001.001: #######', sx.ee_mip[k]
371     for k2 in sx.ee_xref_bck[k]:
372       print sx.eeold[k2]
373
374print '#### Number of missing back references: %s (%s)' % (nnf,nno)
375
376class dopenxx(object):
377  def __init__(self):
378    self.fn = 'xx_%s' % str( uuid.uuid1() )
379    self.oo = open('%s/%s' % (self.odir,self.fn), 'w' )
380  def write(self,x):
381    self.oo.write(x)
382  def close(self,rename=None):
383    self.oo.close()
384    if rename != None:
385      os.rename( '%s/%s' % (self.odir,self.fn), '%s/%s' % (self.odir,rename) )
386
387class dopen(object):
388  def __init__(self,odir='./'):
389    if not os.path.isdir(odir):
390      os.mkdir(odir)
391    self.odir = odir
392    self.a = collections.defaultdict( self.ClassFact() )
393  def close(self,k,rename=None):
394    if self.a.has_key(k):
395      self.a[k].close(rename=rename)
396      self.a.__delitem__(k)
397
398  def ClassFact(self):
399     class dopenyy(dopenxx):
400       """Inherits all methods from dreqItemBase"""
401
402     dopenyy.odir = self.odir
403     return dopenyy
404print 'INFO 001 ##################',nnf, nnm
405
406if sx.doCmipVar:
407##sh = shelve.open( 'shelve_vars' )
408  sh = shelve.open( '%s/cmipVars' % odir, 'n' )
409  sh['__info__'] = { 'label':'cmipVars', 'title':'CMIP variables', 'prov':'sx.eenv and sx.eeold' }
410  sh['__cols__'] = ['label','title','sn','units','description','procnote','procComment','prov','priority0','realm0']
411
412  ee = {}
413  for k in sx.eenv.keys():
414    this = nt_vrecix._make( map( lambda x: sx.eenv[k][x], vrecix_new ) )
415    ##sh[k] = { 'label':this.v, 'title':this.l, 'sn':this.s, 'units':this.u, 'description':this.c, 'procnote':'', 'procComment':'','prov':'CMIP6 endorsement' }
416    prov = 'CMIP6 endorsement [%s]' % sx.eenv[k][1]
417    sh[k] = [ this.v, this.l, this.s, this.u, this.c, '', '',prov, sx.eenv[k][0], sx.eenv[k][8] ]
418    ee[this.u] = k
419    if this.u == 'atmos':
420       print 'ERROR: bad units',k, sx.eenv[k]
421  print '################################### var units #################'
422  print ee.keys()
423  print '##########################################################'
424
425  nk = 0
426  for k in ll_ov:
427    this = nt_vrecix._make( map( lambda x: sx.eeold[k][x], vrecix_old ) )
428  ##sh[k] = { 'label':this.v, 'title':this.l, 'sn':this.s, 'units':this.u, 'description':this.c, 'procnote':'', 'procComment':'','prov':sx.eeold[k][6]}
429    if this.v in sx.cmip5ByVar.keys():
430      s = set()
431      for t in sx.cmip5ByVar[this.v]:
432        s.add( sx.cmip5so.so[t].a[this.v][18] )
433
434      s = list(s)
435      rlm0 = string.join( s )
436    elif this.v in sx.eenvo:
437      rlm0 = sx.eenvo[this.v][0][8]
438      print 'INFO.llll: using eenvo .....',this.v
439    else:
440      rlm0 = '__na__'
441     
442    sh[k] = [ this.v, this.l, this.s, this.u, this.c, '', '',sx.eeold[k][6], 101, rlm0 ]
443    nk += 1
444
445  print len( sx.eenv.keys() ) + len(ll_ov), len( sh.keys() ),  len( sx.eenv.keys() )
446  sh.close()
447 
448###
449###  shelve contains 1682 variables, of which 561 are new.
450###
451   
452### have lost somewhere the var/cmor var distinction. E.g. hfibthermds/hfibthermds2d  --- 2 CMOR variable names with a single output variable name.
453### But this will not be in the physical variable -- so should come in the output variable record.
454
455class c1(object):
456  def __init__(self):
457    self.d = collections.defaultdict( int )
458class c2(object):
459  def __init__(self):
460    self.d = collections.defaultdict( list )
461ee = collections.defaultdict( int )
462ff = collections.defaultdict( c1 )
463#count different shapes:
464blk = collections.defaultdict( c2 )
465for k in sx.ee0.keys():
466  ee[sx.ee0[k][5]] += 1
467  ff[sx.ee0[k][5]].d[sx.ee0[k][10]] += 1
468  blk[sx.ee0[k][5]].d[sx.ee0[k][10]].append(k)
469keys = ee.keys()
470keys.sort()
471print keys
472#######################################
473eeo = collections.defaultdict( int )
474ffo = collections.defaultdict( c1 )
475#count different shapes:
476hdims = [ 'latitude','longitude']
477vdims = [ 'alevel','alevhalf', 'olevel', 'rho', 'alt40', 'location', 'plev','alev1', 'plev3', 'plev7', 'plev8', 'plevs', 'sdepth']
478
479catdims = ['site', 'basin', 'oline', 'dbze', 'scatratio', 'sza5', 'tau', 'vegtype', 'vgidx']
480tdims = ['time','time1','time2']
481
482knowndims = hdims + vdims + catdims + tdims
483
484nsmap = {'':'MISC...', u'XYZKT':'lon.lat.ATMOS.other.time', u'XKT':'PMIP....', u'4-element vector':'..transsi.time', u'KZT':'RFMIP...', u'2D vector field':'lon.lat..sithick.time', u'XYZ':'lon.lat.olevel..time', u'XYZT':'lon.lat.ATMOS..time', u'2D':'SIMIP ... (xYT?)', u'scalar':'?...', u'XY':'FAFMIP, ISMIP6....', u'YZT':'MISC....', u'XYKT':'lon.lat..other.time', u'XYT':'lon.lat...time', u'ZST1':'..alevel.site.time', u'?':'PMIP', u'BasinYT':'.lat..basin.time'}
485## XYZ: this occurs only in FAFMIP
486## XYZT:  {'C4MIP': 80, 'PMIP': 10, 'RFMIP': 3, 'CFMIP': 19, 'LS3MIP': 8, 'GeoMIP': 1, 'HighResMIP': 82}
487##   need to follow up on what is vertical.  # of levels is captured in most cases.
488##   PMIP: email sent -- 29th June : some ocean, some atmos
489##   LS3MIP: soil or snow layers,
490## RFMIP: all levels.
491## XYZKT: CFMIP  -- K has various forms.
492## XKT: PMIP  -- salt transport -- should be lat-basin-time?
493## blank:  {'LUMIP': 40, 'PMIP': 11, 'RFMIP': 4, 'HighResMIP': 11, 'FAFMIP': 3, 'DynVar': 10}
494#-----  RFMIP: scalar .... email sent -- these ar OfflineRad varibles.
495#-----  LUMIP: XYT
496#-----  PMIP: occurs in bulk copy requests .....
497#-----  HighResMip: occurs in comment lines
498#-----  FAFMIP: occurs in comment lines
499#-----  DynVar: probably XYZT -- need to check whether on model or pressure levels.
500## YZT: 'DAMIP': 4, 'VolMIP': 2, 'HighResMIP': 10, 'SolarMIP': 4
501# ----  DAMIP: zonal mean, 17 or 23 levels (pressure) ..
502# ----  VolMIP: zonal mean, all levels
503# ----  HighResMIP: zonal mean, 36 levels
504# ----  SolarMIP: zonal mean, 17 or 23 levels.  (withdrawn and merged with DAMIP ....).
505## scalar: 'ISMIP6': 8, 'SIMIP': 6
506##  --> to KT, with K set to icesheet/hemisphere
507## ----- SIMIP: time (monthly)
508## '?': PMIP, for variables specified in C4MIP.
509##
510
511ed = collections.defaultdict( c1 )
512for k in sx.ee_mip.keys():
513  dl = sx.ee_mip[k][-1]
514  if dl == 's|c|a|l|a|r':
515     dl = 'scalar'
516  dd = string.split( dl, '|' )
517  for d in dd[:-1]:
518   
519    ed[d].d[dd.index(d)] += 1
520  ed[dd[-1]].d['f'] += 1
521  eeo[sx.ee_mip[k][-1]] += 1
522  ffo[sx.ee_mip[k][-1]].d[sx.ee_mip[k][-2]] += 1
523keys = eeo.keys()
524keys.sort()
525
526nkn = []
527for k in ed.keys():
528  if k not in knowndims:
529    nkn.append(k)
530nkn.sort()
531
532presetlinks = {}
533shlnks = shelve.open( '%s/requestLinks_tmp' % odir, 'r' )
534for k in shlnks.keys():
535  if k[0] != '_':
536    if shlnks[k][9] > -1:
537      print 'INFO.aaa.00001: Priority reset ',shlnks[k]
538      presetlinks[ '%s.%s' % (shlnks[k][1],shlnks[k][2]) ] = shlnks[k][9]
539
540##
541## read in provisional request groups --- based on request scoping sheet
542##
543shrvg = shelve.open( '%s/requestVarGroup_tmp' % odir, 'r' )
544eervg = collections.defaultdict( list )
545##
546## construct look-up by label
547##
548for k in shrvg.keys():
549  if k[0] != '_':
550    ##assert not eervg.has_key( shrvg[k][2] ), 'Duplicate rvg: %s' % shrvg[k][2]
551    eervg[shrvg[k][2]].append( k )
552     
553
554sh = shelve.open( 'dreq_consol_tables_reviewed_b_v%s' % vdate, 'r' )
555revTabIds = set( sh.keys()[:] )
556sh.close()
557
558## parse 1
559ee0_p1 = {}
560ee0_gp = collections.defaultdict( d1 )
561st1 = set()
562for k in sx.ee0.keys():
563  r = list(sx.ee0[k][:] )
564  if r[1] != '' and r[1][0] != '#':
565    if ee0_xref.has_key(k):
566      r1 = ee0_xref[k]
567      assert len(r1) == 1, 'FATAL:001.0001: unexpected duplicate cross ref, %s   %s %s' % (k,str(r1),str(r) )
568      assert len(r1[0][1]) == 1, 'FATAL:001.0002: unexpected duplicate cross ref, %s   %s %s' % (k,str(r1),str(r) )
569      r += [r1[0][0],r1[0][1][0]]
570    else:
571      r += [-1,'__none__']
572    ee0_p1[k] = r[:]
573    ee0_gp[r[0]][r[10]] = k
574    st1.add( r[10] )
575    if r[0] == '':
576       print '################'
577       print r
578
579##assert 'CFMIP' in st1, 'FAILED sanity check 1 ... CFMIP not in st1 %s' % str(st1)
580assert len( list(st1) ) < 40, 'FAILED sanity check 2 ... too many items in st1 [should be list of MIPs] %s' % len(list(st1))
581print '###################   groups referenced from new groups sheets'
582print ee0_gp.keys()
583k1 = ee0_gp.keys()
584k1.sort()
585kmapk1 = {}
586for k in k1:
587  assert len(ee0_gp[k].keys()) in  [0,1], 'Multiple references to %s [%s]' % (k,str( ee0_gp[k].keys() ) ) 
588  for k2 in ee0_gp[k].keys():
589    if eervg.has_key( '%s.%s' % (k2,k) ):
590      kmapk1[k] = ('%s.%s' % (k2,k),'newGp')
591    else:
592      kmapk1[k] = ('%s.%s' % (k2,k),'unresolved')
593
594gpids = []
595for k in kmapk1.keys():
596  gpids.append(kmapk1[k][0])
597kmapk2 = {}
598
599mmmm = [('C_OceanT1', 'C_Ocean_T1'), ('C_OceanT2', 'C_Ocean_T2'), ('3hr_extreme','3hr_extr'), ('Amon_extreme','Amon_ext'), \
600        ('Amon_convection','Amon_conv'), ('L3hr','L_3hr'), ('LEday','L_day'), ('DYNVAR_day','DYVR_daily') ]
601mmmm = [('C_OceanT1', 'C_Ocean_T1'), ('C_OceanT2', 'C_Ocean_T2'), ('3hr_extreme','3hr_extr'), ('Amon_extreme','Amon_ext'), \
602        ('Amon_convection','Amon_conv'), ('L3hr','L_3hr'), ('DYNVAR_day','DYVR_daily') ]
603kmap000 = {}
604for t in mmmm:
605  kmap000[t[0]] = t[1]
606
607##
608## check links from variable output specs to group.
609## need to identify what is meant by group labels in "Request Scoping" -- now in eervg.keys()
610##
611## 29th July: loosing some links for groups of revised table items ....
612##
613## these are the reviewed cmip5 standard output tables.
614##
615tabuuidrefs = collections.defaultdict( int )
616
617###
618### get some tables for looking up links from shelve
619###
620shbx = dreq_utils.parseShb(vdate,sx,cmip5gplk)
621
622gpids = gpids + shbx.revisedTabKeysff
623ks = eervg.keys()
624ks.sort()
625for k0 in ks:
626  if k0.find( '.' ) == -1:
627    a = 'CMIP5'
628    b = k0
629  else:
630    a,b = string.split(k0,'.')
631  print 'k0:: ',a,b
632  if kmap000.has_key(b):
633    k = '%s.%s' % (a,kmap000[b])
634  else:
635    k = k0
636  ok = False
637  if b[:5] == 'CCMI1':
638    b1,b2 = string.split(b, '_' )
639    if ccmivgrdict.has_key( b2):
640      ok = True
641      kmapk2[k0] = ('CCMI',b2)
642  elif b[:5] == 'SPECS':
643    b1,b2 = string.split(b, '_' )
644    if b2 in specsvgr:
645      ok = True
646      kmapk2[k0] = ('SPECS',b2)
647    elif b2 == 'Amon':
648      kmapk2[k0] = ('SPECS','mon')
649      ok = True
650  if not ok:
651    if k in gpids:
652    ## print 'OK1: ',k
653      kmapk2[k0] = ('new',k)
654      ok = True
655    elif a in ['LUMIP','LS3MIP']:
656      tk = 'C4MIP.%s' % kmap000.get(b,b)
657      if tk in gpids:
658        kmapk2[k0] = ('new',tk)
659        ok = True
660    elif a in ['VolMIP','DAMIP']:
661      tk = 'DynVar.%s' % kmap000.get(b,b)
662      if tk in gpids:
663        kmapk2[k0] = ('new',tk)
664        ok = True
665    ##elif a in ['HighResMIP'] and b in subgroups:
666        ##kmapk2[k0] = ('CMIP5',tk)
667        ##ok = True
668  if not ok:
669## revTabIds has table names, revGpIds has group names
670    if k in revTabIds or k in shbx.revGpIds:
671      if k in shbx.revGpIds:
672         print 'OK2: ',k
673      kmapk2[k0] = ('CMIP5Rev',k)
674    else:
675      if b in cmip5vgr:
676        kmapk2[k0] = ('CMIP5',b)
677      elif b in cmip5tbs0:
678        kmapk2[k0] = ('CMIP5',b)
679      else:
680        print 'WARN.080.09001: nomap for ',b,k
681        kmapk2[k0] = ('nomap',k)
682   
683print '###############################################################'
684print '###############################################################'
685##
686## following list currently contains separate entries for group references from different MIPs --- want to have a single one
687## here, and multiple references to it ...
688##
689rvgref2 = collections.defaultdict( list )
690lookup1a = collections.defaultdict( d1 )
691lookup1b = {}
692lookup1 = collections.defaultdict( d1 )
693lookup2 = collections.defaultdict( d1 )
694import sx2_extra as sx2e
695rvguids = set()
696#### prepare for requestVarGroup ###########
697## C4MIP-OceanT2        C4MIP: C4MIP-OceanT2    C4MIP   new     C4MIP.C_Ocean_T2
698## label title mip ref refNote
699
700####
701#### reconfigure to uuid, mip, label (no "."), title, class, refNote
702#### for "ttt==new", use sx2e.ngmap( kkk ) to give labels, keep kkk as refNote, ttt --> class
703###
704### lookup1: constructed from requestVarGroup list
705### lookip1[<project>][<table>] = uid
706### e.g. lookup1['CMIP5']['Oyr'] = ['f729b7e4-3e99-11e6-b9b2-5404a60d96b5']
707###      lookup1['new']['FAFMIP.fafOyr'] = ['f7f40742-3e99-11e6-b9b2-5404a60d96b5']
708### uid is key in cmip5tbs or generated new ....
709### lookup1a: similar, uid is from shrvg.
710### shrvg = shelve.open( '%s/requestVarGroup_tmp' % odir, 'r' ), generated by dreq_consol_dreq
711
712for k in shrvg.keys():
713  if k[0] != '_':
714    id0 = shrvg[k][2]
715    ttt,kkk = kmapk2[id0]
716    lookup1a[ttt].d[kkk].append(k)
717    if ttt == 'new':
718      rvgref2[kkk].append( shrvg[k][0] )
719
720for k in lookup1a.keys():
721  for k2 in lookup1a[k].d.keys():
722    id0 = lookup1a[k].d[k2][0]
723    id =  str( uuid.uuid1() )
724    lookup1[k].d[k2].append( id)
725    lookup1b[id0] = id
726
727###
728## add cmip5tbs to lookup, so that these will be picked up in links from "rqeuestLinks"
729for g in cmip5tbs:
730  ####cmip5tbs.append( [u,"CMIP6",k,"CMIP6 CMOR Table: %s" % k, "CMIP5", "CMIP5 MIP Table: %s" % k] )
731  k = g[2]
732  u = g[0]
733  lookup1['CMIP5'].d[k] = [u,]
734 
735
736##
737## problem is trying to ensure that groups are properly referenced.
738## naming etc problematic here.
739##
740tmp = collections.defaultdict( list )
741for k in lookup1.keys():
742  for k2 in lookup1[k].d.keys():
743    assert len( lookup1[k].d[k2] ) == 1, 'Ambiguous lookup1: %s, %s: %s' % (k,k2,str( lookup1[k].d[k2] ) )
744    id = lookup1[k].d[k2][0]
745    if k2 in presetlinks:
746      print 'INFO.aaa.00200: preset refound,', k2
747
748    for idi in lookup1a[k].d[k2]:
749      print 'INFO.bbb.0001: ',k,shrvg[idi]
750      id0 = shrvg[idi][2]
751      mip = shrvg[idi][1]
752      ttt,kkk = kmapk2[id0]
753      cls = k
754      assert  cls == k, 'Mismatch in lookup1'
755      refNote = k2
756      kl = 0
757      lab = '__unset__'
758
759      if cls == 'new':
760        if kkk in shbx.revisedTabKeys:
761          lab = kkk
762          cls = 'rev'
763          lab = string.replace( kkk, '.', '-' )
764          kl = 1
765        else:
766          if not sx2e.ngmap.has_key(kkk):
767            print 'ERROR.002.0001: key %s not found' % kkk
768          else:
769            lab = sx2e.ngmap[kkk]
770            kl = 2
771      elif cls == 'CMIP5':
772        lab = string.replace( k2, '_', '-' )
773        kl = 3
774      elif cls in ['CMIP5Rev','rev']:
775        lab = string.replace( k2, '.', '-' )
776        kl = 4
777      elif cls == 'nomap':
778        lab = string.replace( k2, '.', '-' )
779        kl = 5
780        lab = string.replace( lab, '_', '-' )
781        print 'INFO.nomap.00001: ',cls,k2,lab
782      else:
783        lab = '%s-%s' % (mip,k2)
784        kl = 6
785      if sx2e.r1.match( lab ) == None:
786        print 'NON_COMPLIANT label', lab,k2, cls
787
788      rec, sup = ([id,mip,lab,'%s: %s' % (mip,lab), cls, refNote],[ttt,kkk])
789
790      if string.find( string.join( rec ), '__unset__' ) != -1:
791         print 'INFO.ppp.00003: ',rec, sup, lab,k2, cls, kl
792
793      if refNote == 'C4MIP.Lmon':
794        print 'WARN.051.00001: ',rec,sup, lab,k2, cls, kl
795
796##['6a7ed72e-98d7-11e5-9c3a-ac72891c3257', 'LUMIP', u'C4MIP-Lmon', u'LUMIP: C4MIP-Lmon', 'rev', u'C4MIP.Lmon'] ['new', u'C4MIP.Lmon'] C4MIP-Lmon C4MIP.Lmon rev 1
797      print 'INFO.bbb.0002: ',id,rec,sup
798##
799## create a set of requestVarGroup records ... to be reviewed below for duplicates ....
800##
801      tmp[id].append(  (rec, sup) )
802
803
804
805##
806## links to variables in ee0_xref ...
807##
808err001 = collections.defaultdict( int )
809sh = shelve.open( '%s/groupItems' % odir, 'n' )
810sh['__info__'] =  {'label':'groupItems', 'title':'List of items in new groups', 'description':"New groups" }
811##(u'DYVR_daily', u'utendnogw', '', u'daily', '', '', '', '', '', u'DynVar', 'DynVar', '772da0b6-25b6-11e5-8cf6-ac72891c3257')
812sh['__cols__'] = ['group','var','table','freq','', 'shape', '', '', '','mip','mip?','uuid','rowIndex','new','gpid','vkey','vid']
813for k in ee0_p1.keys():
814    kkk = '%s.%s' % (ee0_p1[k][10],ee0_p1[k][0])
815    ##if not sx2e.ngmap.has_key(kkk):
816    if lookup1['new'].d.has_key(kkk):
817       id = lookup1['new'].d[kkk][0] 
818    elif lookup1['newOrp'].d.has_key(kkk):
819       id = lookup1['newOrp'].d[kkk][0] 
820    else:
821       id = None
822       err001[kkk] += 1
823    r = ee0_p1[k][:]
824    t = ee0_xref[k][0]
825    ##if t[0] == 1:
826      ##r[-2] = 0
827      ##r[-1] = '__see_vid__'
828    if id != None:
829      r[-2] = 1
830      r[-1] = id
831    else:
832      r[-2] = -1
833      r[-1] = '__none__'
834
835    r += [t[0],t[1][0]]
836    if r[1] == 'mrro':
837      print 'INFO.mrro.0001:', r
838    if r[1] == 'sisnconc':
839      print 'INFO.sisnconc.0001:', r
840    sh[k] = r[:]
841sh.close()
842
843## link to group items is now via mip + group id, using stuff from kmapk2 ....
844
845dorest = True
846doexpt = False
847
848class psort(object):
849
850   def __init__(self):
851     pass
852
853   def p(self,z):
854     return tabpri.get(z,9)
855
856   def cmp(self,x,y):
857     return cmp( self.p(x), self.p(y) )
858
859if dorest:
860 tabpri = { 'SPECS':2, 'CMIP5':0, 'CORDEX':3, 'PMIP3':4 }
861
862 gg = {}
863 for k in sx.eeold.keys():
864  if sx.eeold[k][7][:6] == 'mv.005':
865    gg[sx.eeold[k][1]] = k
866###
867### BUT need to get full OMIP records in here ......
868 cmip5GroupCol = collections.defaultdict( list )
869 sh = shelve.open( '%s/refTableItems' % odir, 'n' )
870 sh['__info__'] =  {'label':'refTableItems', 'title':'List of items in reference tables', 'prov':'sx.ee_mip' }
871 sh['__cols__'] = ['uuid', 'comment', 'deflate_level', 'shuffle', 'ok_max_mean_abs', 'flag_meanings', \
872                          'type', 'ok_min_mean_abs', 'standard_name', 'deflate', 'long_name', 'valid_min',\
873                           'cell_methods', 'flag_values', 'cell_measures', 'out_name', 'modeling_realm', 'units',\
874                           '#cell_methods', 'valid_max', 'positive', 'var', 'mipTable','dimensions','vid','gpid','ssect','priority'] 
875
876## added gpid for link to variable group .... not clear at this point how OMIP to be dealt with here.
877## for sections, perhaps need new section linking sections to groups ....
878
879 vdefex = {}
880 rwixkkk = 0
881 for k in sx.ee_mip.keys():
882  gpid = '__group_unknown__'
883  rwix = 0
884  mipt = sx.ee_mip[k][22]
885  if shbx.tabuuid.has_key( mipt ):
886    gpid = shbx.tabuuid[mipt]
887  p = 0
888  ssect = ''
889  if mipt[:4] in { "CMIP", "CCMI", "SPEC", "CORD"}:
890    m,t = string.split( mipt, '_' )
891# output name
892    v0 = sx.ee_mip[k][15]
893# variable name
894    v1 = sx.ee_mip[k][21]
895    if type(v0) == type( 'y' ) and v0 not in ['', ' ']:
896      v1 = v0
897
898    if v1 == 'rtmt':
899      print 'xxyyyy',v1,sx.ee_mip[k]
900    if v1 == 'clisccp':
901      print 'INFO.clisccp.0001:', sx.ee_mip[k]
902
903    trc = []
904    if m == "CMIP5":
905      assert cmip5gplk.has_key(t), 'ERROR.009.0010: CMIP5 table link not found for %s' % mipt
906      gpid = cmip5gplk[t]
907      assert sx.cmip5so.so.has_key(t), 'Key %s not found in cmip5.so keys' % t
908      if not sx.cmip5so.so[t].a.has_key(v1):
909        if t in sx.cmip5so.sx and v1 in sx.cmip5so.sx[t].a:
910          print 'ERROR.030.0001xx: Variable %s not found in cmip5so %s' % (v1,t)
911        else:
912          print 'ERROR.030.0001: Variable %s not found in cmip5so %s' % (v1,t)
913        p = 0
914        trc.append( 'p0' )
915      else:
916        p = sx.cmip5so.so[t].a[v1][0]
917        trc.append( 'pp' )
918        rwix = sx.cmip5so.so[t].a[v1][23]
919        si = sx.cmip5so.so[t].a[v1][24]
920        try:
921          if rwix == '':
922            rwix = 200*si
923          else:
924            rwix = rwix + 200*si
925        except:
926          print sx.cmip5so.so[t].a[v1], len(sx.cmip5so.so[t].a[v1])
927          print sx.cmip5so.so[t].a[v1][24], type( sx.cmip5so.so[t].a[v1][24] )
928          raise
929
930## the "Oyr" group is for import, not needed in request
931      if t in cmip5GroupsIx and t not in ['Oyr','Amon']:
932        trc.append( 'ix' )
933      ##assert cmip5GroupsIVAR[t].has_key(v1) or cmip5GroupsIVAR[t].has_key(v0), '%s not found in table %s' % (v1,t)
934        if not (cmip5GroupsIVAR[t].has_key(v1) or cmip5GroupsIVAR[t].has_key(v0) ):
935           print 'ERROR.080.0020: %s not found in table %s' % (v1,t)
936        else:
937          if cmip5GroupsIVAR[t].has_key(v1):
938            trc.append( '1' )
939            gp = cmip5GroupsIVAR[t][v1]
940          else:
941            gp = cmip5GroupsIVAR[t][v0]
942            trc.append( '0' )
943##
944## collect variables in each group, along with key and priority, to create "revTabItems"
945##
946          cmip5GroupCol[ gp ].append( (v1,k,p) )
947    else:
948       thisk = '%s.%s' % (m,t)
949       if thisk in shbx.tabuuid:
950         gpid = shbx.tabuuid[thisk]
951       else:
952         gpid = uidgen[thisk].uid
953       
954  elif mipt[:5] == "OMIP.":
955####
956#### this would be the place to create "OMIP.Omon_3d" and "OMIP.Omon_oth"
957####
958#### also need to generate "OMIP.Oyr_3dtr" ....
959####
960#### some information added to tabsectbyvar in dreq_utils
961####
962#### might be cleaner in framework/scanDreq ...
963####
964####
965    m,t = string.split( mipt, '.' )
966# output name
967    v0 = sx.ee_mip[k][15]
968# variable name
969    v1 = sx.ee_mip[k][21]
970    if v0[:3] == "dms" or v1[:3] == "dms":
971      print 'INFO.dms.0001: ',sx.ee_mip[k]
972    if type(v0) == type( 'y' ) and v0 not in ['', ' ']:
973      v1 = v0
974
975## check to see if sections are defined.
976    if shbx.tabsectbyvar.has_key(m):
977      tv = '%s.%s' % (t,v1)
978      if shbx.tabsectbyvar[m].has_key(tv):
979        gpid = shbx.tabsectuuid[m][ '%s.%s' % (t,shbx.tabsectbyvar[m][tv][2]) ]
980        rwix = shbx.tabsectbyvar[m][tv][3]
981        ssect = shbx.tabsectbyvar[m][tv][2]
982        p = shbx.tabsectbyvar[m][tv][1]
983        rwixkkk += 1
984
985    if gpid == '__group_unknown__':
986      print 'ERROR.040.0010: OMIP group not found %s, %s, %s' % (mipt,v0,) 
987  elif gpid == '__group_unknown__':
988    print 'ERROR:040.0011: failed to set gpid: ',sx.ee_mip[k]
989  omit = False
990  if not sx.ee_xref_bck.has_key( k ):
991    r1 = sx.ee_mip[k][1]
992    if r1 in ['','29'] or r1[:23] == 'Reference to literature' or r1[:15] == '(copied from 3D':
993       print 'WARN.002.0003: dud record',sx.ee_mip[k], sx.ee_mip[k][-2][:4] 
994       omit = True
995    elif sx.ee_mip[k][-2][:4] == 'OMIP':
996       print 'ERROR.002.0004: no back references %s' % str(sx.ee_mip[k])
997    else:
998      print 'ERROR.002.0003: no back references %s' % str(sx.ee_mip[k])
999    kl = ['__none__',]
1000    vnam0 = ''
1001  else:
1002    kl = sx.ee_xref_bck[ k ]
1003    if len(kl) != 1:
1004      print 'ERROR.002.0001: multiple back references %s' % str(kl)
1005      #print sx.ee_mip[k]
1006    kv = kl[0]
1007    r = sx.eeold[kv]
1008    vnam0 = r[1]
1009    if vnam0[-4:] == "Clim":
1010      print 'error in xref back .... ',r
1011    kit = 0
1012    itl = []
1013    while r[8] not in [ '','null','Depricated'] and r[8][0] != '*':
1014      itl.append(r)
1015      if ee_mv0.has_key(r[8]):
1016        kv = ee_mv0[ r[8] ]
1017        r0 = r[:]
1018        r = sx.eeold[kv]
1019        if r[1] != vnam0:
1020          print 'WARN: CHANGE ',vnam0,kv,r,r0
1021      else:
1022        print 'ERROR.002.0002: ambiguous back reference: %s' % str(r)
1023      kit += 1
1024      assert kit < 5, 'Too many iterations: %s,\n%s' % (str(r),str(itl))
1025      if kit > 1:
1026        print 'WARNING.002.0001: chained reference: %s' % str(r)
1027    kl = [kv,]
1028  ##print 'INFO.999.00005: ',omit, rec
1029
1030  if not omit:
1031## count refs, for use in determining where to create group records ....
1032    tabuuidrefs[gpid] += 1
1033    if r[1] != vnam0:
1034      print 'INFO.0001.001: name change:',r,vnam0
1035    vdefex[k] = list(r) + [vnam0,] 
1036    if len( sx.ee_mip[k][:] ) != 24:
1037      print 'ERROR.015.0002: Bad record length %s: %s' % (k,sx.ee_mip[k])
1038
1039    rec = sx.ee_mip[k][:]  + [kl[0],gpid,rwix,p]
1040    if rec[21] == u'bsi' or rec[15] == u'bsi':
1041      print 'INFO.999.00001: ',[rec[i] for i in [15,21,22,25]]
1042    if v1 == 'clisccp':
1043      print 'INFO.clisccp.0002:', rec
1044    sh[k] = sx.ee_mip[k][:]  + [kl[0],gpid,rwix,ssect,p] 
1045    if kl[0] in sx.eeold and sx.eeold[kl[0]][1] == 'ch4Clim':
1046      print 'INFO.ch4Clim.0001: ',sh[k]
1047    if gpid not in rvguids:
1048        print 'ERROR.080.06006: Request variable group link broken:', sh[k]
1049 sh.close()
1050
1051 sha = shelve.open( 'dreq_consol_tables_reviewed_a_v%s' % vdate )
1052 shb = shelve.open( 'dreq_consol_tables_reviewed_b_v%s' % vdate )
1053 keys = shb.keys()
1054 keys.sort()
1055 k0 = []
1056 for k in shbx.revisedTabKeysff:
1057   bb = string.split(k, '.' )
1058   if len(bb) == 2:
1059     k0.append( tuple(bb) )
1060
1061 sh = shelve.open( '%s/revTabItems' % odir, 'n' )
1062 sh['__info__'] =  {'label':'revTabItems', 'title':'List of items in revised tables', 'description':"uuid (col 3) references an item in 'refTableItems'", 'prov':'from dreq_consol_tables_reviewed_b_v%s, cross-referenced with sx.ee_miptables_old' % vdate }
1063 sh['__cols__'] = ['var','table','mip','uuid','priority']
1064####
1065 dop = dopen('check3')
1066 kr = 0
1067 krn = 0
1068
1069 for m,t in k0:
1070  vars = shb[ '%s.%s' % (m,t) ]
1071  print 'INFO.003.0001: ',m,t, sorted( vars.keys() )[:3]
1072  ee = {}
1073  ff = {}
1074
1075## inclusion of CFMIP here was an error ....
1076  if m in ["OMIP",'CFMIPx']:
1077    rk = '%s.%s' % (m,t)
1078  else:
1079    rk = 'CMIP5_%s' % t
1080
1081  if not sx.ee_miptables_old.has_key(rk):
1082     print 'ERROR.003.0002: key %s not found ' % rk
1083  else:
1084    for u in sx.ee_miptables_old[rk]:
1085      ee[ sx.ee_mip[u][21] ] = u
1086      if vdefex.has_key(u):
1087        if vdefex[u][1] != sx.ee_mip[u][21]:
1088          ff[vdefex[u][1]] = u
1089
1090    for v0 in vars.keys():
1091      v = string.strip( v0 )
1092      r = sha['records'][vars[v0][0]]
1093      if not ee.has_key(v):
1094        if ff.has_key(v):
1095          print 'INFO ... rename found',v
1096          thisu = ff[v]
1097        elif v[:7] == 'include':
1098          thisu = '__inc__'
1099        else:
1100          thisu = None
1101          if sx.ee_byvar.has_key( v ):
1102             tabs = map( lambda x: sx.ee_mip[x][-2], sx.ee_byvar[v] )
1103             tbs = map( lambda x: string.split(x, '_' )[-1], tabs )
1104             cls = map( lambda x: string.split(x, '_' )[0], tabs )
1105             if t in tbs:
1106               cl0 = []
1107               for k in range(len(tbs)):
1108                 if tbs[k] == t:
1109                    cl0.append( cls[k] )
1110
1111               cl0.sort( psort().cmp )
1112               ix = tabs.index( '%s_%s' % (cl0[0],t) )
1113               print 'WARN.003.0001 var not found -- alternative table used [%s]: %s (%s, %s)' % (cl0[0],v,m,t)
1114               thisu = sx.ee_byvar[v][ix]
1115               
1116             ##print map( lambda x: sx.ee_mip[x][-2], sx.ee_byvar[v] )
1117          elif m in ['OMIP','CFMIP'] and gg.has_key(v):
1118            print 'INFO.003.00010: new %s var found: %s' % (m,v)
1119            thisu = '__new.%s__' % m
1120            krn += 1
1121            id =  str( uuid.uuid1() )
1122            dop.a[ '%s3' % string.lower( m ) ].write( string.join( [id,] + map(lambda x: r[x],[4,0,5,2,7]) + ['%s_%s' % (m,t),'mv.006.%4.4i' % krn], '\t' ) + '\n' )
1123         
1124          if thisu == None:
1125            print 'ERROR.003.0001 var not found: %s (%s, %s)' % (v,m,t)
1126            thisu = "__var_not_found__"
1127
1128          if m == 'OMIP':
1129            kr += 1
1130            sr =  map(str,r)
1131            dop.a['omip'].write( string.join( map(str,r), '\t' ) + '\n' )
1132            dop.a['omip2'].write( string.join( map(lambda x: str(r[x]),[4,0,5,2,7]) + ['%s_%s' % (m,t),'mv.005.%4.4i' % kr], '\t' ) + '\n' )
1133         
1134      else:
1135        thisu = ee[v]
1136      kv = str( uuid.uuid1() )
1137      if t == 'day_oth':
1138        print 'xxxxxx', v,t,m,r
1139      if v == 'clic':
1140        print 'INFO.clic.00002: ',v,t,m,thisu,v0,vars[v0]
1141      if v == 'tdps':
1142        print 'INFO.tdps.00002: ',v,t,m,thisu,v0,vars[v0]
1143      sh[kv] = [v,t,m,thisu,vars[v0][1]]
1144
1145        ### cmip5GroupCol[ gp ].append( (v1,k,p) )
1146 gpextra = []
1147 for gp in cmip5GroupCol.keys():
1148   for v,k,p in cmip5GroupCol[gp]:
1149     kv = str( uuid.uuid1() )
1150     rec = [v,gp,'CMIP5',k,int(p)]
1151     if gp == 'day_oth':
1152        print 'xxxxyy', rec, gp
1153     gpextra.append(rec)
1154     sh[kv] = rec[:]
1155 dop.close('omip',rename='omip.csv')
1156 dop.close('omip2',rename='omip2.csv')
1157 dop.close('omip3',rename='omip3.csv')
1158 sh.close()
1159
1160 sh = shelve.open( '%s/requestVarGroup' % odir )
1161## add OMIP (+ ....?)
1162 nomip = 0
1163 donomip = False
1164 if donomip:
1165  for k in shbx.tabuuid.keys():
1166   if k[0] != '_':
1167  ####cmip5tbs.append( [u,"CMIP6",k,"CMIP6 CMOR Table: %s" % k, "CMIP5", "CMIP5 MIP Table: %s" % k] )
1168     if tabuuidrefs[shbx.tabuuid[k]]  > 0:
1169        mip,tab = string.split( k, '.' )
1170        u = shbx.tabuuid[k]
1171        if mip in {u'OMIP', 'OMIP'}:
1172          lab = '%s-%s' % (mip,tab)
1173        else:
1174          lab = tab
1175        sh[u] = [u,mip,lab,"CMOR Table variant: %s" % k, "CMIP5Rev", k ]
1176####'OMIP', u'OMIP-fx', u'OMIP: OMIP-fx', 'CMIP5Rev', u'OMIP.fx'
1177        print 'INFO: ADDING GROUP: %s' % str(sh[u])
1178        nomip += 1
1179 sh.close()
1180 print nomip
1181
1182
1183if doexpt:
1184
1185 ##wb = utils_wb.workbook( 'CMIP6DataRequest_ConsolidatedExperiments_20151028.xls' )
1186 cvdir = '/data/work/tmp/git/CMIP6_CVs'
1187 efn = 'CMIP6DataRequest_ConsolidatedExperiments_20160714.xls'
1188 efn = 'CMIP6DataRequest_ConsolidatedExperiments_20161111.xls'
1189 efn = 'CMIP6DataRequest_ConsolidatedExperiments_20170117.xls'
1190 wb = utils_wb.workbook( efn )
1191 sht = wb.book.sheet_by_name( 'Experiments' )
1192 ee = json.load( open( '%s/CMIP6_experiment_id.json' % cvdir ))
1193 p = dreq_utils.prconsolexpt()
1194 p.parse(sht, extra=ee['experiment_id'])
1195
1196## info about the deck to fill in.
1197 wb2 = utils_wb.workbook( 'CMIP6DataRequest_deckInfo.xls' )
1198 sht2 = wb2.book.sheet_by_name( 'Experiments' )
1199
1200## appends records to "p.records"
1201 p.parse(sht2)
1202
1203 sh = shelve.open( '%s/experiments' % odir, 'n' )
1204 sh['__info__'] = { 'label':'experiments', 'title':'Experiments', 'prov':'sx202.py, using %s' % efn }
1205 sh['__cols__'] = ['uuid','egid','label','description','mip','mcfg','tier','nstart','starty','endy','yps','ensz','ntot','comment']
1206 ##['label','group','mip','description','modelClass','tier','nstart','starty','endy','yps','ensz','ntot','comment']
1207 eegg = {}
1208 eetm = collections.defaultdict( set )
1209 eent = collections.defaultdict( int )
1210 elabs = {}
1211 for r in p.records:
1212   u = str( uuid.uuid1() )
1213   gp = r[1]
1214   if not eegg.has_key(gp):
1215     eegg[gp] = str( uuid.uuid1() )
1216 
1217   if type( r[5] ) == type( 1 ):
1218     eetm[gp].add( r[5] )
1219   else:
1220     eetm[gp].add( r[5][-1] )
1221   try:
1222     eent[gp] += r[11]
1223   except:
1224     print 'SEVERE: failed to increment eent[%s]' % gp
1225     print r
1226     raise
1227     print 'SEVERE: failed to increment eent[%s]: % .... %:: %' % (gp,eent[gp],r[11],str(r))
1228   label = labcoerce( r[0], nodash=False )
1229   assert label not in elabs, 'Duplicate experiment label: %s\n%s\n%s' % (label,str(r),str(sh[elabs[label]]))
1230   elabs[label] = u
1231   oo = [u,eegg[gp],label]
1232   for j in [3,2,4,5,6,7,8,9,10,11,12]:
1233     oo.append( r[j] )
1234   sh[u] = oo[:]
1235 sh.close()
1236
1237 sh = shelve.open( '%s/exptGroups' % odir, 'n' )
1238 sh['__info__'] = { 'label':'exptGroups', 'title':'Experiment groups', 'prov':'ConsolidatedExperiments' }
1239 sh['__cols__'] = ['uuid','label','tiermin','ntot']
1240 for k in eegg.keys():
1241   if not eegg.has_key(gp):
1242     eegg[gp] = str( uuid.uuid1() )
1243 
1244   lab = labcoerce(k,nodash=True)
1245   oo = [eegg[k],lab,min(eetm[k]),eent[k]]
1246   sh[oo[0]] = oo[:]
1247 sh.close()
1248
1249print uidgen.keys()
Note: See TracBrowser for help on using the repository browser.