def write_field(self, filename, field,griddescfile=None,fieldname=None): """Write a field to an unformatted fortran file using a method from scipy Arguments: filename: string; full path of the file to write to field: A Field (or Field subclass object); field to write griddescfile is ignored by this function but included to match the abstract function it is overriding fieldname is not used by this method and included only in order to match the abstract of method of IOFileHelper """ with scipyio.FortranFile(filename,mode='w') as f: #@UndefinedVariable print("Writing output to {0}".format(filename)) f.write_record(field.get_data())
def __call__(self, data, fid=slice(None), ftype='utout'): ofreqs = self.freqs[fid] ofreqs = [(2 * np.pi * freq) + self.dampCoeff for freq in ofreqs] outfile = '%s.%s' % (self.projnm, ftype) nfreq = len(ofreqs) if data.ndim != 3: raise Exception('Data must be of shape (nrec, nsrc, nfreq)') assert data.shape[2] == nfreq nrec = data.shape[0] nsrc = data.shape[1] with io.FortranFile(outfile, 'w') as ff: for i, freq in enumerate(ofreqs): panel = np.empty((nsrc, nrec + 1), dtype=np.complex64) panel[:, :1] = freq panel[:, 1:] = data[:, :, i].T ff.write_record(panel.ravel())
def load__fortranBinary(inpFile=None, shape=(-1, ), datatype="float"): # ------------------------------------------------- # # --- [1] Arguments --- # # ------------------------------------------------- # if (inpFile is None): sys.exit("[load__fortranBinary.py] inpFile == ??? ") # ------------------------------------------------- # # --- [2] load fortran Binary file --- # # ------------------------------------------------- # import scipy.io as io with io.FortranFile(inpFile, mode="r") as f: if (datatype.lower() in ["float", "double", "real"]): data = f.read_reals(float) elif (datatype.lower() in ["int", "integer", "long"]): data = f.read_ints(np.int32) # ------------------------------------------------- # # --- [3] reshape data --- # # ------------------------------------------------- # dshape = data.shape if (shape == (-1, )): ret = data elif (np.abs(np.prod(np.array(shape))) == data.shape[0]): ret = data.reshape(shape) else: print( "[load__fortranBinary.py] shape is incompatible with Data.shape !!! ERROR !!! " ) print("[load__fortranBinary.py] shape == {0} ".format(shape)) print("[load__fortranBinary.py] data.shape == {0} ".format(data.shape)) print() sys.exit() # ------------------------------------------------- # # --- [4] return --- # # ------------------------------------------------- # return (ret)
def read_lblrtm_spectral_output_files(readfrom = 'TAPE13', max_lines = 1000): ''' Returns a list of records from an unformatted Fortran file output by LBLRTM. This is based on the IDL script read_lbl_file.pro which Karen provided. INPUT: readfrom --- path to the file to read max_lines --- maximum number of lines to read from file ''' records = collections.deque([]) f = spio.FortranFile(readfrom, mode = 'r') for k in range(max_lines): try: r = f.read_reals() records.append(r) except TypeError: print('Encountered TypeError on read_real(). \ Stop reading and exit.') break f.close() return records
def load_field(self,filename,unmask=True,timeslice=None, fieldname=None,check_for_grid_info=False, grid_info=None,grid_type='HD',**grid_kwargs): """Load a field from a unformatted fortran file using a method from scipy Arguments: filename: string; full path of the file to load grid_type: string; keyword specifying what type of grid to use **grid_kwargs: keyword dictionary; keyword arguments giving parameters of the grid fieldname, timeslice, unmask, check_for_grid_info and grid_info are not used by this method and included only in order to match the abstract of method of IOFileHelper Returns: A numpy array containing the field This scipy method cannot read all Fortran file correctly; success or failure depends on the endianness and compiler used by the Fortran used to write the data. It will succeed in reading data written using FortranFile.write_record. """ grid = gd.makeGrid(grid_type,**grid_kwargs) with scipyio.FortranFile(filename,mode='r') as f: #@UndefinedVariable: print("Reading input from {0}".format(filename)) return f.read_record(self.data_type).reshape(grid.get_grid_dimensions())
import sys import numpy as np from scipy import io import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patches as patches from mpl_toolkits.axes_grid1 import make_axes_locatable # g file fp = io.FortranFile(sys.argv[1], "r") fp.read_ints(np.int32) index = fp.read_record(np.dtype(('<i4', (1, ))), np.dtype(('<i4', (1, )))) imax, jmax = index[0], index[1] xx = fp.read_record(np.dtype(('<f4', imax * jmax)), np.dtype(('<f4', imax * jmax)), np.dtype(('<i4', imax * jmax))) fp.close() imx = int(imax) jmx = int(jmax) x = xx[0].reshape([imx, jmx], order='F') y = xx[1].reshape([imx, jmx], order='F') ib = xx[2].reshape([imx, jmx], order='F') # q file fp = io.FortranFile(sys.argv[2], "r") fp.read_ints(np.int32) index = fp.read_record(np.dtype(('<i4', (1, ))), np.dtype(('<i4', (1, )))) imax, jmax = index[0], index[1] param = fp.read_record(np.dtype(('<f4', (4))))
def listing2opt(in_listing, out_opt): try: with spio.FortranFile(in_listing, 'r') as f: res = f.read_reals(float) while True: res = np.vstack((res, f.read_reals(float))) except TypeError: pass listePdt = np.unique(res[:, 0]) nombrePdT = len(listePdt) nombreSection = sum(res[:, 0] == listePdt[0]) nombreCouche = sum(res[:, 1] == 1999) // (nombrePdT - 1) Uno = np.array([1 for i in range(nombreSection)]) PdT = res[0:nombreSection, 0] NumeroSection = res[0:nombreSection, 1] variables = res[0:nombreSection, 2:17] Q = res[0:nombreSection, 5] * res[0:nombreSection, 6] print("%i frames, %i sections, %i couches" % (nombrePdT, nombreSection, nombreCouche)) Resultats = np.insert(variables, 0, PdT, axis=1) Resultats = np.insert(Resultats, 1, Uno, axis=1) Resultats = np.insert(Resultats, 17, Q, axis=1) Resultats = np.insert(Resultats, 2, NumeroSection, axis=1) OPT = Resultats for i in range(1, nombrePdT): rangeIndex_1 = i * nombreSection + (i - 1) * (nombreCouche + 3) rangeIndex_2 = rangeIndex_1 + nombreSection PdT = res[rangeIndex_1:rangeIndex_2, 0] NumeroSection = res[rangeIndex_1:rangeIndex_2, 1] variables = res[rangeIndex_1:rangeIndex_2, 2:17] Q = res[rangeIndex_1:rangeIndex_2, 5] * res[rangeIndex_1:rangeIndex_2, 6] Resultats = np.insert(variables, 0, PdT, axis=1) Resultats = np.insert(Resultats, 1, Uno, axis=1) Resultats = np.insert(Resultats, 17, Q, axis=1) Resultats = np.insert(Resultats, 2, NumeroSection, axis=1) OPT = np.vstack((OPT, Resultats)) with open(out_opt, 'w') as w: w.write('[variables]\n') w.write('\"Cote de l eau\";\"Z\";\"m\";3\n') w.write('\"Cote du fond\";\"ZREF\";\"m\";4\n') w.write('\"Vitesse mineure\";\"VMIN\";\"m/s\";4\n') w.write('\"Section mouillee mineure\";\"E1\";\"m2\";2\n') w.write('\"Concentration en vase\";\"CVas\";\"g/l\";4\n') w.write('\"Concentration en sable\";\"CSbl\";\"g/l\";4\n') w.write('\"Depot cumule\";\"DepT\";\"T\";3\n') w.write('\"Variation de surface cumulee\";\"Vsur\";\"m2\";3\n') w.write('\"Flux massique de vase\";\"FlVs\";\"kg/m/s\";3\n') w.write('\"Flux massique de sable\";\"FlSb\";\"kg/m/s\";3\n') w.write('\"Contrainte au fond maximale\";\"THMx\";\"N/m2\";3\n') w.write('\"Contrainte moyenne\";\"THMy\";\"N/m2\";3\n') w.write('\"Contrainte effective moyenne\";\"TEMy\";\"N/m2\";3\n') w.write('\"Concentration d' 'equilibre moy\";\"CeqM\";\"g/l\";3\n') w.write('\"Debit\";\"Q\";\"m3/s\";1\n') w.write('[resultats]\n') for i in range(np.size(OPT, 0)): j = 0 w.write("{:16.8f}".format(OPT[i, j])) for j in range(1, np.size(OPT, 1)): w.write(";{:16.8f}".format(OPT[i, j])) w.write("\n")