def _atmos_ (atmFiles, outFile=None, commentChar='#', extract='*', where=None, zToA=None, pRatio=None, zGrid=None, format=None, saveVMR=False, pT=False, verbose=False): if isinstance(where, str): # replace acronyms with names used in namelist file where = atmos_short2long_name(where) profileList = get_profile_list (atmFiles, commentChar, extract, where, verbose) if zToA or pRatio or zGrid: profileList = reGridProfiles (profileList, zToA, zGrid, pRatio) if verbose: for prof in profileList: print prof atmos1d = Atmos1D(profileList) out = open_outFile (outFile, commentChar) if format in ('namelist', 'nml'): write_atmos_namelist (out, atmos1d, saveVMR) elif format=='xy': write_atmos_xy (out, atmos1d, pT, saveVMR) else: from pprint import pprint pprint(atmos1d.__dict__, out) # close the output file (if its not stdout) if outFile: out.close()
def save_optDepth_xy (vGrid, optDepth, outFile=None, atmos=None, nanometer=False, yOnly=False, flipUpDown=False, commentChar='#'): """ Save optical depth (vs wavenumber or wavelength) in ascii tabular format. """ out = open_outFile (outFile, commentChar) nLevels = len(atmos.z) nGas = len(atmos.gases) if flipUpDown: if len(optDepth.shape)==2: optDepth = np.fliplr(optDepth) # swap columns comments = ['altitudes [km]: ' + nLevels*' %10.1f' % tuple(unitConversion(atmos.z[::-1],'length',new='km')), 'temperatures [K]:' + nLevels*' %10.2f' % tuple(atmos.T[::-1]), 'pressures [mb]: ' + nLevels*' %10.4g' % tuple(unitConversion(atmos.p[::-1],'p',new='mb'))] else: comments = ['altitudes [km]: ' + nLevels*' %10.1f' % tuple(unitConversion(atmos.z,'length',new='km')), 'temperatures [K]:' + nLevels*' %10.2f' % tuple(atmos.T), 'pressures [mb]: ' + nLevels*' %10.4g' % tuple(unitConversion(atmos.p,'p',new='mb'))] comments += ['gases: ' + nGas*' %10s' % tuple(atmos.gases), 'vcd [molec/cm^2]:' + nGas*' %10.2g' % tuple(atmos.vcd())] if nanometer: if yOnly: writeArray (np.flipud(optDepth), out, comments=comments, format= '%10g') else: comments += ['%10s %10s' % ('wavelength','optical depth'), '%10s' % 'nm'] writeArray (np.flipud(paste(1e7/vGrid,optDepth)), out, comments=comments, format= '%10f %10g') else: if yOnly: writeArray (optDepth, out, comments=comments, format= '%10g') else: comments += ['%10s %10s' % ('wavenumber','optical depth'), '%10s' % '1/cm'] writeArray (paste(vGrid,optDepth), out, comments=comments, format= '%10f %10g') out.close()
def write_crossSections_xyy (crossSections, outFile=None, linePositions=None, interpolate='3', commentChar='#'): """ Write cross section(s) to output (file) in tabular xy format. (All cross sections of a given molecule (i.e., data for all p,T levels) are interpolated to a common wavenumber grid and written to a single file) """ out = open_outFile (outFile, commentChar) if outFile: # print a summary molecules = tuple([xs.get('molecule') for xs in crossSections]) sameMolec = np.alltrue([molecules[0] == other for other in molecules[1:]]) if sameMolec: out.write ( '%1s %-16s %s\n' % (commentChar, 'molecule:', molecules[0])) lineShapes = tuple([xs.get('lineShape') for xs in crossSections]) sameShapes = np.alltrue([lineShapes[0] == other for other in lineShapes[1:]]) if sameShapes: out.write ( '%1s %-16s %s\n' % (commentChar, 'lineshape:', lineShapes[0])) if isinstance(linePositions,np.ndarray): out.write ( '%1s %i %s %f ... %f\n' % (commentChar, len(linePositions), 'lines in ', min(linePositions),max(linePositions)) ) # extract pressure and temperatures nXS = len(crossSections) pressures = tuple([unitConversion(xs.get('p',0.0),'p',new='mb') for xs in crossSections]) temperatures = tuple([xs.get('T',0.0) for xs in crossSections]) out.write ( commentChar+' pressure [mb]: ' + nXS*' %10g' % pressures + '\n') out.write ( commentChar+' temperature [K]:' + nXS*' %10.2f' % temperatures + '\n') out.write ( commentChar + '\n' ) # select an interpolation method if interpolate.lower() in 'sb': try: from scipy.interpolate import splrep, splev except ImportError, msg: raise SystemExit, msg else: intMethod = 'Spline interpolation (scipy splrep/splev)'
def write_voigtLines (positions, strengths, gammaL, gammaD, pressure, temperature, molecule, outFile=None, commentChar='#'): """ Write Voigt line parameters (strengths, Lorentz and Gaussian widths vs line positionsp. """ out = open_outFile (outFile, commentChar) out.write ('%s %s %s\n' % (commentChar, "molecule:", molecule)) out.write ('%s %s %-12g\n' % (commentChar, "pressure [mb]: " , unitConversion(pressure,'p', new='mb'))) out.write ('%s %s %8.2f\n' % (commentChar, "temperature [K]: ", temperature)) out.write ('%s %10s %11s %11s %11s\n' % (commentChar, "position", "strength", "gammaL", "gammaG")) format = '%12f %11.3e %11.3g %11.3g\n' for v,S, gL, gG in zip(positions, strengths, gammaL, gammaD): out.write ( format % (v,S,gL,gG) ) # close the output file (if its not stdout) if outFile: out.close()
def write_strengths (positions, strengths, strRef, temperature, tempRef, molecule, outFile=None, commentChar='#'): """ Write line strengths (for two temperatures) vs line positions. """ out = open_outFile (outFile, commentChar) out.write ('%s %s %s\n' % (commentChar, "molecule:", molecule)) out.write ('%s %s %8.2f %s\n' % (commentChar, "temperature T_ref:" , tempRef, "K")) out.write ('%s %s %8.2f %s\n' % (commentChar, "temperature T: ", temperature, "K")) out.write ('%s %10s %23s\n' % (commentChar, "position", " S(T_ref) |S(T)- S(T_ref)|")) format = '%12f %11.3e %10.2e 0\n' for v,S0,S in zip(positions, strRef, strengths): #out.write ( format % (v,S0,S) ) if S>S0: out.write ( format % (v,S0,S-S0) ) else: out.write ( format % (v,S0,S0-S) ) # close the output file (if its not stdout) if outFile: out.close()
def write_crossSections_xy (crossSections, outFile=None, linePositions=None, commentChar='#'): """ Write cross section(s) to output (file) in tabular xy format. (Cross sections of a given molecule (i.e., data for all p,T levels) are written to a individual files) """ # extract attributes like pressure and temperatures nXS = len(crossSections) molecules = tuple([xs.get('molecule') for xs in crossSections]) pressures = tuple([unitConversion(xs.get('p',0.0),'p',new='mb') for xs in crossSections]) temperatures = tuple([xs.get('T',0.0) for xs in crossSections]) lineShapes = tuple([xs.get('lineShape') for xs in crossSections]) if isinstance(linePositions,np.ndarray): lineInfo = '%i %s %f ... %f' % (len(linePositions), 'lines in ', min(linePositions),max(linePositions)) else: lineInfo = '' for l, xs in enumerate(crossSections): if isinstance(outFile,str) and '.' in outFile: outRoot, outExt = os.path.splitext(outFile) oFile = '%s_%2.2i_%gmb_%.1fK%s' % (outRoot, l+1, pressures[l], temperatures[l], outExt) else: oFile = '%s_%gmb_%.1fK.%s' % (molecules[l], pressures[l], temperatures[l], 'xs') out = open_outFile (oFile, commentChar) # print a summary out.write ( '%1s %-16s %s\n' % (commentChar, 'molecule:', molecules[l])) out.write ( '%1s %-16s %s\n' % (commentChar, 'lineshape:', lineShapes[l])) if lineInfo: out.write ( '%1s %s\n' % (commentChar, lineInfo)) out.write ( commentChar+' pressure [mb]: ' + ' %10g' % pressures[l] + '\n') out.write ( commentChar+' temperature [K]:' + ' %10.2f' % temperatures[l] + '\n') out.write ( commentChar + '\n' ) # extract cross section spectra and save in list yyy = xs['y'] nxy = len(yyy)-1 xLow, xHigh = crossSections[0]['x'].limits() xLo, xHi = float(xLow/nxy), float(xHigh/nxy) # and write cross section vs wavenumber out.write ( '%1s%12s %15s\n' % (commentChar, 'wavenumber', 'cross section') ) format = ' %12f %12.6g\n' for i,y in enumerate(yyy): x = i*xHi + (nxy-i)*xLo out.write (format % (x,y)) if outFile: out.close()
def print_lines(outFile, Lines, dataFile, molecule, format="", commentChar="#"): if "hit" in lower(dataFile): xUnit, TRef, pRef = "cm-1", 296.0, 1013.25 elif "sao" in lower(dataFile): xUnit, TRef, pRef = "cm-1", 296.0, 1013.25 elif "geisa" in lower(dataFile): xUnit, TRef, pRef = "cm-1", 296.0, 1013.25 elif "jpl" in lower(dataFile): xUnit, TRef, pRef = "MHz", 300.0, 1013.0 else: raise SystemExit, "unknown database type!" # check if output file extension indicates the format if outFile: outFileExt = os.path.splitext(outFile)[1] if not format and lower(outFileExt).startswith(".vs"): format = outFileExt[1:] print "format automatically determined from output file extension ", format if lower(format).startswith("vs"): if molecule: write_lines_xy(outFile, Lines, dataFile, format, TRef, pRef, molecule, commentChar) else: if outFile: print "\nWARNING: specified output filename will be ignored!\n (lines will be saved to files with names defined by molecule and format)\n" lineLists = split_molecules(Lines, dataFile) # actually this returns a dictionary! for molec, lines in lineLists.items(): outFile = molec + os.path.extsep + format write_lines_xy(outFile, lines, dataFile, format, TRef, pRef, molec, commentChar) else: # save line extract in original format commentChar = "00" if "hit" in dataFile: if lower(format).startswith("g"): raise SystemExit, "\nERROR --- extract: no format conversion hitran -> geisa" elif "geisa" in dataFile: commentChar = 5 * commentChar if lower(format).startswith("h"): raise SystemExit, "\nERROR --- extract: no format conversion geisa -> hitran" else: if lower(format).startswith("g") or lower(format).startswith("h"): raise SystemExit, "\nERROR --- extract: no format conversion ??? -> hitran" out = open_outFile(outFile, commentChar) if "hit" in dataFile.lower(): if len(Lines[0].rstrip()) == 100: # old hitran versions <=2000 out.write( "%3s%12s%10s%10s%5s%5s%10s%4s%8s%3s%3s%9s%9s%3s%6s\n" % ( "000", "wavenumber", "S", "A", "air", "self", "Energy", "n", "pShift", "uV", "lV", "uL", "lL", "er", "ref", ) ) else: # new hitran versions >=2004 out.write( "%3s%12s%10s%10s%5s%5s%10s%4s%8s%15s%15s%15s%15s%6s%12s %s7%7s\n" % ( "000", "wavenumber", "S", "A", "air", "self", "Energy", "n", "pShift", "upVib", "loVib", "upLocal", "loLocal", "err", "ref", "usw", "lsw", ) ) for line in Lines: out.write(line) if outFile: out.close() return
def write_lines_xy(outFile, lines, dataFile, job="vS", TRef=0, pRef=0, molecule="", commentChar="#"): """ Print 'core' line parameters, i.e., positions vs strengths, and optionally energies, airWidths, tempExponents. """ # open an output file if explicitely specified (otherwise use standard output) out = open_outFile(outFile, commentChar) if molecule: out.write("%s %s %s\n" % (commentChar, "molecule:", molecule)) # reference pressure and temperature of database if TRef: out.write("%s %s %8.2f %s\n" % (commentChar, "temperature:", TRef, "K")) if pRef: out.write("%s %s %8.2f %s\n" % (commentChar, "pressure: ", pRef, "mb")) # extract most important numeric line parameters positions, strengths, energies, airWidths, selfWidths, tempDep, isoNr = core_parameters(lines, dataFile) # some statistical information nLines = len(positions) out.write("%s %-30s %12i\n" % (commentChar, "number of lines: ", nLines)) out.write("%s %-30s %12.3g%13.3g\n" % (commentChar, "min, max line strength: ", min(strengths), max(strengths))) out.write("%s %s %s\n" % (commentChar, "format:", job)) if "a" in job: out.write( "%s %-30s %12.3f%13.3f\n" % (commentChar, "min, max airbroad. widths: ", min(airWidths), max(airWidths)) ) out.write( "%s %-30s %12.3f%13.3f\n" % (commentChar, "min, max selfbroad. widths: ", min(selfWidths), max(selfWidths)) ) out.write("%s %-30s %12.3f%13.3f\n" % (commentChar, "min, max temp. exponent: ", min(tempDep), max(tempDep))) if outFile: print "%-8s %8i %s %11.3g %s %-11.3g %s %s" % ( molecule, nLines, " lines with", min(strengths), "< S <", max(strengths), " writing to file", outFile, ) # if job == "vSEani": format = "%12f %11.3e %11.5f %8.5f %7.4f %3i\n" out.write( "%1s %10s %11s %11s %8s %7s %3s\n" % (commentChar, "position", "strength", "energy", "airWidth", "Tdep", "iso") ) out.write("%1s %10s %11s %11s %8s %7s\n" % (commentChar, "cm-1", "cm-1/cm-2", "cm-1", "cm-1", "")) for l in xrange(nLines): out.write(format % (positions[l], strengths[l], energies[l], airWidths[l], tempDep[l], isoNumber[l])) elif job == "vSEan": format = "%12f %11.3e %11.5f %8.5f %7.4f\n" out.write("%1s %10s %11s %11s %8s %7s\n" % (commentChar, "position", "strength", "energy", "airWidth", "Tdep")) out.write("%1s %10s %11s %11s %8s %7s\n" % (commentChar, "cm-1", "cm-1/cm-2", "cm-1", "cm-1", "")) for l in xrange(nLines): out.write(format % (positions[l], strengths[l], energies[l], airWidths[l], tempDep[l])) elif job == "vSEasni": format = "%12f %11.3e %11.5f %8.5f %8.5f %7.4f %4i\n" out.write( "%1s %10s %11s %11s %8s %8s %7s %4s\n" % (commentChar, "position", "strength", "energy", "airWidth", "selfWidth", "Tdep", "iso") ) out.write("%1s %10s %11s %11s %8s %8s %7s\n" % (commentChar, "cm-1", "cm-1/cm-2", "cm-1", "cm-1", "cm-1", "")) for l in xrange(nLines): out.write( format % (positions[l], strengths[l], energies[l], airWidths[l], selfWidths[l], tempDep[l], isoNr[l]) ) elif job == "vSEasn": format = "%12f %11.3e %11.5f %8.5f %8.5f %7.4f\n" out.write( "%1s %10s %11s %11s %8s %8s %7s\n" % (commentChar, "position", "strength", "energy", "airWidth", "selfWidth", "Tdep") ) out.write("%1s %10s %11s %11s %8s %8s %7s\n" % (commentChar, "cm-1", "cm-1/cm-2", "cm-1", "cm-1", "cm-1", "")) for l in xrange(nLines): out.write(format % (positions[l], strengths[l], energies[l], airWidths[l], selfWidths[l], tempDep[l])) elif job == "vSEa": format = "%12f %11.3e %11.5f %8.5f\n" for l in xrange(nLines): out.write(format % (positions[l], strengths[l], energies[l], airWidths[l])) elif job == "vSE": format = "%12f %11.3e %11.5f\n" for l in xrange(nLines): out.write(format % (positions[l], strengths[l], energies[l])) else: format = "%12f %11.3e\n" for l in xrange(nLines): out.write(format % (positions[l], strengths[l])) # close the output file (if its not stdout) if outFile: out.close() return
from command_parser import parse_command, standardOptions opts = standardOptions + [ # h=help, c=commentChar, o=outFile {'ID': 'i', 'name': 'isoNr', 'type': IntType, 'default': 0}, {'ID': 'm', 'name': 'molNr', 'type': IntType, 'default': 0}, {'ID': 'S', 'name': 'strMin', 'type': FloatType, 'default': 0.0, 'constraint': 'strMin>=0.0'}, {'ID': 'x', 'name': 'xLimits', 'type': Interval, 'default': Interval(0.0,99999.9), 'constraint': 'xLimits.lower>=0.0'} ] files, options, commentChar, outFile = parse_command (opts, 1) for opt in opts: if opt.has_key('name') and opt.has_key('type'): exec opt['name'] + ' = ' + repr(options.get(opt['name'])) if options.has_key('h'): print __doc__%globals(); raise SystemExit, " end of hitran help" elif molNr or xLimits.size()<50000.0: # Read lines from HITRAN line parameter file lines = extract_hitran (files[0], xLimits, molNr, isoNr, strMin) print len(lines), ' lines' else: # at least molecule or wavenumber range needed raise SystemExit, ' ERROR: neither molecule nor wavenumber range specified!' # open an output file if explicitely specified (otherwise use standard output) out = open_outFile (outFile, commentChar='00') # print extracted lines for line in lines: out.write (line) # close the output file (if its not stdout) if outFile: out.close()