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

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

release candidate

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