Warning, /tools/darwin/preprocessptracers is written in an unsupported language. File is not indexed.
view on githubraw file Latest commit ba8c5276 on 2019-04-02 21:20:59 UTC
8fbfd1f382 Oliv*0001 #!/usr/bin/env python
0002 '''preprocessptracers [-mods <codedir>] [-d <digits>] [-u] data.ptracers.in
0003
0004 Call this in the directory where DARWIN_OPTIONS.h, DARWIN_SIZE.h and optionally
0005 DARWIN_INDICES.h of current setup are located to replace ptracer names in
0006 a data.ptracers template with indices. Header files will also be searched
0007 for in an MITgcm directory up to five levels up.
0008
0009 Options:
0010
0011 -u include "PTRACERS_units" lines
0012 -mods <codedir> look here for header files instead of current directory
0013 -d <digits> number of digits
0014
0015 Example:
0016
0017 preprocessptracers -mods ../code -u data.ptracers.in > data.ptracers
0018 '''
0019 from __future__ import print_function
0020 import sys
0021 import os
0022 import re
0023 from math import log10
0024 from fortran import OrderedDict
0025 from subprocess import Popen, PIPE
0026 from fortran import readparameters
0027
0028 units = {
ba8c527662 Oliv*0029 'DIC': 'uM C',
0030 'NH4': 'uM N',
0031 'NO2': 'uM N',
0032 'NO3': 'uM N',
0033 'PO4': 'uM P',
0034 'SiO2': 'uM Si',
0035 'FeT': 'uM Fe',
0036 'DOC': 'uM C',
0037 'DON': 'uM N',
0038 'DOP': 'uM P',
0039 'DOFe': 'uM Fe',
0040 'POC': 'uM C',
0041 'PON': 'uM N',
0042 'POP': 'uM P',
0043 'POSi': 'uM Si',
0044 'POFe': 'uM Fe',
0045 'PIC': 'uM C',
0046 'ALK': 'meq/m^3',
0047 'O2': 'uM O',
0048 'CDOM': 'uM C',
8fbfd1f382 Oliv*0049 }
0050 unitsre = {
ba8c527662 Oliv*0051 '^c[0-9]': 'uM C',
0052 '^n[0-9]': 'uM N',
0053 '^p[0-9]': 'uM P',
0054 '^si[0-9]': 'uM Si',
0055 '^fe[0-9]': 'uM Fe',
0056 '^Chl[0-9]': 'mg/m^3',
8fbfd1f382 Oliv*0057 }
0058 def getunit(name):
0059 try:
0060 return units[name]
0061 except KeyError:
0062 for k,v in unitsre.items():
0063 if re.match(k, name):
0064 return v
0065 else:
0066 return None
0067
0068 def findfile(fname):
0069 origfname = fname
0070 fname = os.path.join(dir, fname)
0071 if os.path.exists(fname): return fname
0072 fname = os.path.join('..', 'pkg', 'darwin', origfname)
0073 if os.path.exists(fname): return fname
0074 fname = os.path.join('..', fname)
0075 if os.path.exists(fname): return fname
0076 fname = os.path.join('..', fname)
0077 if os.path.exists(fname): return fname
0078 fname = os.path.join('..', fname)
0079 if os.path.exists(fname): return fname
0080 fname = os.path.join('..', fname)
0081 if os.path.exists(fname): return fname
0082 sys.stderr.write('Tried: ' + fname + '\n')
0083 raise RuntimeError('File not found: {}\n'.format(origfname))
0084
0085
0086 args = sys.argv[1:]
0087 if '-h' in args or '--help' in args:
0088 sys.exit(__doc__)
0089 printunits = '-u' in args
0090 if '-mods' in args:
0091 i = args.index('-mods')
0092 dir = args[i+1]
0093 args[i:i+2] = []
0094 else:
0095 dir = '.'
0096 if '-d' in args:
0097 i = args.index('-d')
0098 digits = int(args[i+1])
0099 args[i:i+2] = []
0100 else:
0101 digits = None
0102 template = None
0103 for arg in args:
0104 if arg not in ['-u']:
0105 if template is None:
0106 template = arg
0107 else:
0108 sys.exit(__doc__)
0109
0110 if template is None:
0111 sys.exit(__doc__)
0112
0113 files = []
0114 for fname in ['DARWIN_OPTIONS.h', 'DARWIN_SIZE.h', 'DARWIN_INDICES.h']:
0115 files.append(findfile(fname))
0116 sys.stderr.write(' '.join(['Using']+files) + '\n')
0117 pipe1 = Popen(['cat'] + files, stdout=PIPE, universal_newlines=True)
0118 pipe2 = Popen(['grep', '-v', 'PACKAGES_CONFIG'],
0119 stdin=pipe1.stdout, stdout=PIPE, universal_newlines=True)
0120 pipe1.stdout.close()
0121 pipe3 = Popen(['grep', '-v', 'CPP_OPTIONS'],
0122 stdin=pipe2.stdout, stdout=PIPE, universal_newlines=True)
0123 pipe2.stdout.close()
0124 pipe4 = Popen(['cpp', '-DALLOW_DARWIN', '-traditional', '-P'],
0125 stdin=pipe3.stdout, stdout=PIPE, universal_newlines=True)
0126 pipe3.stdout.close()
0127 p = readparameters(pipe4.stdout)
0128 pipe4.stdout.close()
0129 pl = dict((k.lower(), v) for k, v in p.items())
0130
0131 if digits is None:
0132 digits = int(log10(int(pl['nplank']))) + 1
0133 digitsChl = int(log10(int(pl['nphoto']))) + 1
0134 else:
0135 digitsChl = digits
0136
0137 ends = OrderedDict((k[1:], v) for k,v in p.items() if k.startswith('e'))
0138 starts = OrderedDict((k[1:], v) for k,v in p.items() if k.startswith('i') and k[1:4] not in ['Min', 'Max'])
0139 if 'CDOM' in ends and 'CDOM' not in starts or ends['CDOM'] == starts['CDOM']:
0140 del ends['CDOM']
96f6b36015 Oliv*0141 cellnames = list(ends)
8fbfd1f382 Oliv*0142 for k in starts:
0143 if k not in ends:
0144 ends[k] = starts[k]
0145
0146 nptr = max(ends.values())
0147
0148 digits_ptr = int(log10(nptr)) + 1
0149
0150 names = nptr*['']
0151 indices = {}
0152 for k,s in sorted(starts.items(), key=lambda x:x[1]):
0153 e = ends[k]
0154 for i in range(s,e+1):
0155 if k in cellnames:
0156 name = '{0}{1:0{d}d}'.format(k, i-s+1, d=digitsChl if k == 'Chl' else digits)
0157 else:
0158 name = k
0159 names[i-1] = name
0160 indices[name] = '{0:{d}d}'.format(i, d=digits_ptr)
0161
0162 if template is not None:
0163 with open(template) as f:
0164 for line in f:
0165 if line.strip() in '&/':
0166 print('#')
0167 for i in range(nptr):
0168 name = names[i]
0169 idx = indices[name]
0170 print(" PTRACERS_names({0})= '{1}',".format(idx, name))
0171
0172 if printunits:
0173 print('#')
0174 for i in range(nptr):
0175 name = names[i]
0176 idx = indices[name]
0177 unit = getunit(name)
0178 if unit is not None:
0179 print(" PTRACERS_units({0})= '{1}'".format(idx, unit))
0180
0181 try:
0182 lhs,rhs = line.rstrip().split('=')
0183 except ValueError:
0184 sys.stdout.write(line)
0185 continue
0186
0187 name = lhs.rstrip()
0188 nwslhs = len(lhs) - len(name)
0189 if name[-1:] == ')':
0190 name,arg = name[:-1].split('(')
0191 if arg.strip() == ':' and '*' not in rhs:
0192 print(lhs + '= ' + str(nptr) + '*' + rhs.strip(' ,') + ',')
0193 continue
0194
0195 args = arg.split(',')
0196 for iarg in range(len(args)):
0197 arg = args[iarg]
0198 if ':' in arg:
0199 i1,i2 = arg.split(':')
0200 i1 = indices.get(i1.strip(), i1)
0201 i2 = indices.get(i2.strip(), i2)
0202 arg = i1 + ':' + i2
0203 else:
0204 argname = arg.strip()
0205 pre = (len(arg) - len(argname))*' '
0206 arg = indices.get(argname, pre + argname)
0207 args[iarg] = arg
0208 print(name + '(' + ','.join(args) + ')' + nwslhs*' ' + '=' + rhs)
0209 continue
0210
0211 if name.strip().lower() == 'ptracers_numinuse':
0212 print(lhs + '= ' + str(nptr) + ',')
0213 continue
0214
0215 sys.stdout.write(line)
0216