def main(): args = sys.argv[1:] if len(args) == 0: print '\n\tError - no station name given\n' return lo_stations = args[0] try: lo_stations = lo_stations.split(',') lo_stations = [i.upper() for i in lo_stations] except: print 'Error - station name list could not be read!' print '(Must be comma-separated list...no whitespaces)\n' outfile = op.abspath(op.join(os.curdir, 'dummy_survey.cfg')) outfile = MTfh.make_unique_filename(outfile) survey_dict = {} for st in lo_stations: tmp_dict = {} for idx_r, req in enumerate(MTcf.list_of_required_keywords): tmp_dict[req] = MTcf.list_of_keyword_defaults_general[idx_r] for idx_e, efield in enumerate(MTcf.list_of_efield_keywords): tmp_dict[efield] = MTcf.list_of_keyword_defaults_efield[idx_e] for idx_b, bfield in enumerate(MTcf.list_of_bfield_keywords): tmp_dict[bfield] = MTcf.list_of_keyword_defaults_bfield[idx_b] survey_dict[st] = tmp_dict MTcf.write_dict_to_configfile(survey_dict, outfile)
def main(): args = sys.argv[1:] if len(args) == 0 : print '\n\tError - no station name given\n' return lo_stations = args[0] try: lo_stations = lo_stations.split(',') lo_stations = [i.upper() for i in lo_stations] except: print 'Error - station name list could not be read!' print '(Must be comma-separated list...no whitespaces)\n' outfile = op.abspath(op.join(os.curdir,'dummy_survey.cfg')) outfile = MTfh.make_unique_filename(outfile) survey_dict = {} for st in lo_stations: tmp_dict = {} for idx_r, req in enumerate(MTcf.list_of_required_keywords): tmp_dict[req] = MTcf.list_of_keyword_defaults_general[idx_r] for idx_e, efield in enumerate(MTcf.list_of_efield_keywords): tmp_dict[efield] = MTcf.list_of_keyword_defaults_efield[idx_e] for idx_b,bfield in enumerate(MTcf.list_of_bfield_keywords): tmp_dict[bfield] = MTcf.list_of_keyword_defaults_bfield[idx_b] survey_dict[st] = tmp_dict MTcf.write_dict_to_configfile(survey_dict, outfile)
def convert_edi_coordinates_to_kml_file(edi_filelist, outfilename = None): kml_string = '' kml_string += '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n' kml_string += '<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n' kml_string += '<Document>\n' for edi_idx, edi in enumerate(edi_filelist): e = EDI.Edi() e.readfile(edi) lat = e.lat lon = e.lon ele = e.elev station = e.head['dataid'] kml = [] description = 'File: {0}'.format(e.filename) kml.append(' <Placemark>') kml.append(' <name>%s</name>' % station) kml.append(' <description>') kml.append(' <p>%s</p>' % description) kml.append(' </description>') kml.append(' <Point>') kml.append(' <coordinates>%f,%f,%f</coordinates>' % (lon, lat,ele)) kml.append(' </Point>') kml.append(' </Placemark>') kml_string += '\n'.join(kml) kml_string += '\n</Document>\n' kml_string += '</kml>\n' if outfilename is None: outfilename = op.abspath('edi_coordinates.kml') else: try: outfilename = op.abspath(op.join('.',outfilename)) except: outfilename = op.abspath('edi_coordinates.kml') outfilename = MTfh.make_unique_filename(outfilename) fileObj = open(outfilename, 'w' ) fileObj.write(kml_string) fileObj.close() return outfilename
def write_config_file(self, save_fn): """ write a config file for birrp parameters """ cfg_fn = mtfh.make_unique_filename( '{0}_birrp_params.cfg'.format(save_fn)) birrp_dict = self._get_parameters() mtcfg.write_dict_to_configfile(birrp_dict, cfg_fn) print('Wrote BIRRP config file for edi file to {0}'.format(cfg_fn))
def write_config_file(self, save_fn): """ write a config file for birrp parameters """ cfg_fn = mtfh.make_unique_filename( '{0}_birrp_params.cfg'.format(save_fn)) station = os.path.basename(save_fn) birrp_dict = self.to_dict() mtcfg.write_dict_to_configfile({station: birrp_dict}, cfg_fn) print( 'INFO: Wrote BIRRP config file for edi file to {0}'.format(cfg_fn))
def convert_edi_coordinates_to_kml_file(edi_filelist, outfilename=None): kml_string = '' kml_string += '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n' kml_string += '<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n' kml_string += '<Document>\n' for edi_idx, edi in enumerate(edi_filelist): e = EDI.Edi() e.readfile(edi) lat = e.lat lon = e.lon ele = e.elev station = e.head['dataid'] kml = [] description = 'File: {0}'.format(e.filename) kml.append(' <Placemark>') kml.append(' <name>%s</name>' % station) kml.append(' <description>') kml.append(' <p>%s</p>' % description) kml.append(' </description>') kml.append(' <Point>') kml.append(' <coordinates>%f,%f,%f</coordinates>' % (lon, lat, ele)) kml.append(' </Point>') kml.append(' </Placemark>') kml_string += '\n'.join(kml) kml_string += '\n</Document>\n' kml_string += '</kml>\n' if outfilename is None: outfilename = op.abspath('edi_coordinates.kml') else: try: outfilename = op.abspath(op.join('.', outfilename)) except: outfilename = op.abspath('edi_coordinates.kml') outfilename = MTfh.make_unique_filename(outfilename) fileObj = open(outfilename, 'w') fileObj.write(kml_string) fileObj.close() return outfilename
def writefile_obspy_singletrace(outfilename,station,channel,network,location, delta_t, t0, data): # Fill header attributes stats = {'network': network.upper(), 'station': station.upper(), 'location': location.upper(), 'channel': channel.upper(), 'npts': len(data), 'sampling_rate': 1./delta_t, 'starttime' : t0} #define stream st = Stream([Trace(data=data, header=stats)]) if not outfilename.lower().endswith('.mseed'): outfilename += '.mseed' #save to file outfilename = MTfh.make_unique_filename(outfilename) st.write(outfilename, 'MSEED') return outfilename
def writefile_obspy_singletrace(outfilename, station, channel, network, location, delta_t, t0, data): # Fill header attributes stats = { 'network': network.upper(), 'station': station.upper(), 'location': location.upper(), 'channel': channel.upper(), 'npts': len(data), 'sampling_rate': 1. / delta_t, 'starttime': t0 } #define stream st = Stream([Trace(data=data, header=stats)]) if not outfilename.lower().endswith('.mseed'): outfilename += '.mseed' #save to file outfilename = MTfh.make_unique_filename(outfilename) st.write(outfilename, 'MSEED') return outfilename
def makemap(edilist, mapstretchfactor, symbolsize, labelsize, showlabel): #import of modules here due to warnings from Matplotlib packages #these warnings distract the 'usage' information from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import matplotlib as mpl import mtpy.utils.filehandling as MTfh import mtpy.core.edi as EDI import mtpy.utils.filehandling as MTfh lats = [] lons = [] names = [] for i in edilist: e = EDI.Edi() e.readfile(i) lats.append(e.lat) lons.append(e.lon) names.append(e.head['dataid'].lower()) coords = zeros((len(edilist), 2)) coords[:, 0] = lats coords[:, 1] = lons latrange = max(lats) - min(lats) lonrange = max(lons) - min(lons) #center point for projection: c = [mean(lats), mean(lons)] #----------------------- #Matplotlib options mpl.rcParams['font.size'] = 10. mpl.rcParams['axes.labelsize'] = 8. mpl.rcParams['xtick.labelsize'] = 6. mpl.rcParams['ytick.labelsize'] = 6. plt.close('all') fig = plt.figure() #figsize=(5.7,4.3)) plt.subplots_adjust(left=0.2, right=0.9, top=0.90, bottom=0.1, wspace=0.15, hspace=0.05) ax = plt.subplot(111) stretch = float(mapstretchfactor) total_latmin = max((min(lats) - stretch * latrange), -90) total_lonmin = max((min(lons) - stretch * lonrange), -180) total_latmax = min((max(lats) + stretch * latrange), 90) total_lonmax = min((max(lons) + stretch * lonrange), 180) total_latrange = total_latmax - total_latmin total_lonrange = total_lonmax - total_lonmin #determine number of axes labels: maximumlabels = 5 latnum = maximumlabels lonnum = maximumlabels lonlat_stretch = total_lonrange / total_latrange if int(lonlat_stretch) > 2: #significantly more long than lat factor = int(int(lonlat_stretch) / 2.) latnum = int(maximumlabels / factor) + 1 lonnum = maximumlabels elif int(lonlat_stretch) < 0.5: #significantly more long than lat factor = int(int(1. / lonlat_stretch) / 2.) lonnum = int(maximumlabels / factor) + 1 latnum = maximumlabels m = Basemap(projection='merc', lon_0=c[1], lat_0=c[0], lat_ts=c[0], llcrnrlat=total_latmin, urcrnrlat=total_latmax, llcrnrlon=total_lonmin, urcrnrlon=total_lonmax, rsphere=6371200., resolution='h') #,ax=ax) lons.append(total_lonmin) lons.append(total_lonmax) lats.append(total_latmin) lats.append(total_latmax) xgrid, ygrid = m(*meshgrid(lons, lats)) xdiff = xgrid.max() - xgrid.min() ydiff = ygrid.max() - ygrid.min() largest_extent = max(ydiff, xdiff) m.drawcoastlines(linewidth=0.25, ax=ax) m.drawcountries(linewidth=0.25, ax=ax) m.fillcontinents(color='coral', lake_color='aqua', ax=ax) m.drawmapboundary(fill_color='aqua', ax=ax) m.drawparallels([ round(i, 3) for i in linspace(total_latmin, total_latmax, latnum + 1, False) ][1:], labels=[1, 0, 0, 0], fmt='%.1f') m.drawmeridians([ round(i, 3) for i in linspace(total_lonmin, total_lonmax, lonnum + 1, False) ][1:], labels=[0, 0, 0, 1], fmt='%.1f') m.drawrivers() m.etopo() m.drawmapscale( total_lonmax - 0.15 * total_lonrange, total_latmax - 0.2 * total_latrange, c[1], c[0], 2 * 10**(int(log10(largest_extent / 1000.)) - 1), barstyle='simple', labelstyle='simple', fontsize=12, fontcolor='k', fillcolor1='r', fillcolor2='g', ax=None, format='%d', ) for x, y, name in zip(xgrid[0, :], ygrid[:, 0], names): plt.plot(x, y, 'v', ms=symbolsize, color='k', label=name) if showlabel is True: plt.text(x, y, name, fontsize=labelsize, ha='center', va='bottom', color='k', backgroundcolor='r') #, labelfontsize=5) plt.title('locations of {0} MT stations'.format(len(names))) f1 = 'station_locations_map.png' f2 = 'station_locations_map.svg' f1 = MTfh.make_unique_filename(f1) f2 = MTfh.make_unique_filename(f2) plt.savefig(f1, format='png', dpi=200) plt.savefig(f2, format='svg', transparent=True) return op.abspath(f1), op.abspath(f2)
def makemap(edilist,mapstretchfactor,symbolsize,labelsize,showlabel): #import of modules here due to warnings from Matplotlib packages #these warnings distract the 'usage' information from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import matplotlib as mpl import mtpy.utils.filehandling as MTfh import mtpy.core.edi as EDI import mtpy.utils.filehandling as MTfh lats = [] lons =[] names=[] for i in edilist: e = EDI.Edi() e.readfile(i) lats.append(e.lat) lons.append(e.lon) names.append(e.head['dataid'].lower()) coords = zeros((len(edilist),2)) coords[:,0] = lats coords[:,1] = lons latrange = max(lats) - min(lats) lonrange = max(lons) - min(lons) #center point for projection: c = [mean(lats),mean(lons)] #----------------------- #Matplotlib options mpl.rcParams['font.size'] = 10. mpl.rcParams['axes.labelsize'] = 8. mpl.rcParams['xtick.labelsize'] = 6. mpl.rcParams['ytick.labelsize'] = 6. plt.close('all') fig = plt.figure()#figsize=(5.7,4.3)) plt.subplots_adjust(left=0.2,right=0.9,top=0.90,bottom=0.1,wspace=0.15,hspace=0.05) ax = plt.subplot(111) stretch = float(mapstretchfactor) total_latmin = min(lats)-stretch*latrange total_lonmin = min(lons)-stretch*lonrange total_latmax = max(lats)+stretch*latrange total_lonmax = max(lons)+stretch*lonrange total_latrange = total_latmax - total_latmin total_lonrange = total_lonmax - total_lonmin #determine number of axes labels: maximumlabels = 5 latnum=maximumlabels lonnum=maximumlabels lonlat_stretch = total_lonrange/total_latrange if int(lonlat_stretch) > 2: #significantly more long than lat factor = int(int(lonlat_stretch)/2.) latnum = int(maximumlabels/factor) + 1 lonnum = maximumlabels elif int(lonlat_stretch) <0.5 : #significantly more long than lat factor = int(int(1./lonlat_stretch)/2.) lonnum = int(maximumlabels/factor) + 1 latnum = maximumlabels m = Basemap( projection='merc', lon_0=c[1],lat_0=c[0],lat_ts=c[0], llcrnrlat=total_latmin, urcrnrlat=total_latmax, llcrnrlon=total_lonmin, urcrnrlon=total_lonmax, rsphere=6371200.,resolution='h',ax=ax) lons.append(total_lonmin) lons.append(total_lonmax) lats.append(total_latmin) lats.append(total_latmax) xgrid, ygrid = m(*meshgrid(lons,lats)) xdiff = xgrid.max()-xgrid.min() ydiff = ygrid.max()-ygrid.min() largest_extent = max(ydiff,xdiff) m.drawcoastlines(linewidth=0.25,ax=ax) m.drawcountries(linewidth=0.25,ax=ax) m.fillcontinents(color='coral',lake_color='aqua',ax=ax) m.drawmapboundary(fill_color='aqua',ax=ax) m.drawparallels( [round(i,3) for i in linspace(total_latmin,total_latmax,latnum+1,False)][1:], labels=[1,0,0,0], fmt='%.1f' ) m.drawmeridians( [round(i,3) for i in linspace(total_lonmin,total_lonmax,lonnum+1,False)][1:], labels=[0,0,0,1], fmt='%.1f' ) m.drawrivers() m.etopo() m.drawmapscale( total_lonmax-0.15*total_lonrange, total_latmax-0.2*total_latrange, c[1],c[0], 2*10**(int(log10(largest_extent/1000.))-1), barstyle='simple', labelstyle='simple',fontsize=12, fontcolor='k', fillcolor1='r', fillcolor2='g', ax=None, format='%d', ) for x,y,name in zip(xgrid[0,:], ygrid[:,0],names): plt.plot(x,y,'v',ms=symbolsize,color='k',label=name) if showlabel is True: plt.text(x,y,name,fontsize=labelsize,ha='center',va='bottom',color='k',backgroundcolor='r')#, labelfontsize=5) plt.title('locations of {0} MT stations'.format(len(names))) f1 = 'station_locations_map.png' f2 = 'station_locations_map.svg' f1 = MTfh.make_unique_filename(f1) f2 = MTfh.make_unique_filename(f2) plt.savefig(f1,format='png',dpi=200) plt.savefig(f2,format='svg',transparent=True) return op.abspath(f1),op.abspath(f2)
def generate_input_file(edifilename, outputdir=None): eo = EDI.Edi() eo.readfile(edifilename) filebase = op.splitext(op.split(edifilename)[-1])[0] outfilename1 = "{0}_bayesian1d_z.in".format(filebase) outfilename2 = "{0}_bayesian1d_zvar.in".format(filebase) outdir = op.split(edifilename)[0] if outputdir is not None: try: if not op.isdir(outputdir): os.makedirs(outputdir) outdir = outputdir except: pass outfn1 = op.join(outdir, outfilename1) outfn2 = op.join(outdir, outfilename2) outfn1 = MTfh.make_unique_filename(outfn1) outfn2 = MTfh.make_unique_filename(outfn2) freqs = eo.freq z_array = eo.Z.z z_err_array = eo.Z.z_err if len(freqs) != len(z_array): raise MTex.MTpyError_edi_file( "ERROR in Edi file {0} - number of " "freqs different from length of Z array".format(eo.filename) ) sorting = np.argsort(freqs) outstring1 = "" outstring2 = "" for idx in sorting: z = z_array[idx] z_err = z_err_array[idx] f = freqs[idx] outstring1 += "{0}\t".format(f) outstring2 += "{0}\t".format(f) for i in np.arange(2): for j in np.arange(2): if np.imag(z[i % 2, (j + 1) / 2]) < 0: z_string = "{0}-{1}i".format(np.real(z[i % 2, (j + 1) / 2]), np.abs(np.imag(z[i % 2, (j + 1) / 2]))) else: z_string = "{0}+{1}i".format(np.real(z[i % 2, (j + 1) / 2]), np.imag(z[i % 2, (j + 1) / 2])) z_err_string = "{0}".format(z_err[i % 2, (j + 1) / 2]) outstring1 += "{0}\t".format(z_string) outstring2 += "{0}\t".format(z_err_string) outstring1 = outstring1.rstrip() + "\n" outstring2 = outstring2.rstrip() + "\n" Fout1 = open(outfn1, "w") Fout2 = open(outfn2, "w") Fout1.write(outstring1.expandtabs(4)) Fout2.write(outstring2.expandtabs(4)) Fout1.close() Fout2.close() return outfn1, outfn2
def generate_input_file(edifilename, outputdir=None): eo = EDI.Edi() eo.readfile(edifilename) filebase = op.splitext(op.split(edifilename)[-1])[0] outfilename1 = '{0}_bayesian1d_z.in'.format(filebase) outfilename2 = '{0}_bayesian1d_zvar.in'.format(filebase) outdir = op.split(edifilename)[0] if outputdir is not None: try: if not op.isdir(outputdir): os.makedirs(outputdir) outdir = outputdir except: pass outfn1 = op.join(outdir, outfilename1) outfn2 = op.join(outdir, outfilename2) outfn1 = MTfh.make_unique_filename(outfn1) outfn2 = MTfh.make_unique_filename(outfn2) freqs = eo.freq z_array = eo.Z.z z_err_array = eo.Z.z_err if len(freqs) != len(z_array): raise MTex.MTpyError_edi_file('ERROR in Edi file {0} - number of ' 'freqs different from length of Z array'.format(eo.filename)) sorting = np.argsort(freqs) outstring1 = '' outstring2 = '' for idx in sorting: z = z_array[idx] z_err = z_err_array[idx] f = freqs[idx] outstring1 += '{0}\t'.format(f) outstring2 += '{0}\t'.format(f) for i in np.arange(2): for j in np.arange(2): if np.imag(z[i % 2, (j + 1) / 2]) < 0: z_string = '{0}-{1}i'.format(np.real(z[i % 2, (j + 1) / 2]), np.abs(np.imag(z[i % 2, (j + 1) / 2]))) else: z_string = '{0}+{1}i'.format(np.real(z[i % 2, (j + 1) / 2]), np.imag(z[i % 2, (j + 1) / 2])) z_err_string = '{0}'.format(z_err[i % 2, (j + 1) / 2]) outstring1 += '{0}\t'.format(z_string) outstring2 += '{0}\t'.format(z_err_string) outstring1 = outstring1.rstrip() + '\n' outstring2 = outstring2.rstrip() + '\n' Fout1 = open(outfn1, 'w') Fout2 = open(outfn2, 'w') Fout1.write(outstring1.expandtabs(4)) Fout2.write(outstring2.expandtabs(4)) Fout1.close() Fout2.close() return outfn1, outfn2
def write_edi_file(self, station=None, birrp_dir=None, survey_config_fn=None, birrp_config_fn=None, copy_path=None): """ Read in BIRRP out puts, in this case the .j file and convert that into an .edi file using the survey_config_fn parameters. Arguments ------------- **station** : string name of station **birrp_dir** : string full path to output directory for BIRRP **survey_config_fn** : string full path to survey configuration file **birrp_config_fn** : string full path to birrp configuration file *default* is none and is looked for in the birrp_dir **copy_path** : string full path to directory to copy the edi file to Outputs ------------- **edi_fn** : string full path to edi file .. note:: The survey_config_fn is a file that has the structure: [station] b_instrument_amplification = 1 b_instrument_type = coil b_logger_gain = 1 b_logger_type = zen b_xaxis_azimuth = 0 b_yaxis_azimuth = 90 box = 26 date = 2015/06/09 e_instrument_amplification = 1 e_instrument_type = Ag-Agcl electrodes e_logger_gain = 1 e_logger_type = zen e_xaxis_azimuth = 0 e_xaxis_length = 100 e_yaxis_azimuth = 90 e_yaxis_length = 100 elevation = 2113.2 hx = 2274 hy = 2284 hz = 2254 lat = 37.7074236995 location = Earth lon = -118.999542099 network = USGS notes = Generic config file rr_box = 25 rr_date = 2015/06/09 rr_hx = 2334 rr_hy = 2324 rr_lat = 37.6909139779 rr_lon = -119.028707542 rr_station = 302 sampling_interval = all save_path = \home\mtdata\survey_01\mt_01 station = 300 station_type = mt This file can be written using mtpy.utils.configfile:: >>> import mtpy.utils.configfile as mtcfg >>> station_dict = {} >>> station_dict['lat'] = 21.346 >>> station_dict['lon'] = 122.45654 >>> station_dict['elev'] = 123.43 >>> cfg_fn = r"\home\mtdata\survey_01" >>> mtcfg.write_dict_to_configfile({station: station_dict}, cfg_fn) """ # check to make sure all the files exist if station is not None: self.station = station if self.station is None: raise mtex.MTpyError_inputarguments( 'Need to input the station name') # birrp directory if birrp_dir is not None: self.birrp_dir = birrp_dir if not os.path.isdir(self.birrp_dir): raise mtex.MTpyError_inputarguments( 'Could not find {0}, check path'.format(birrp_dir)) # survey configuratrion if survey_config_fn is not None: self.survey_config_fn = survey_config_fn self.read_survey_config_fn() # birrp configuration file if birrp_config_fn is not None: self.birrp_config_fn = birrp_config_fn self.read_birrp_config_fn() # get .j file first\ self.get_j_file() # read in .j file self.mt_obj = mt.MT() self.mt_obj.read_mt_file(self.j_fn) # get birrp parameters from .j file if birrp dictionary is None if self.birrp_dict is None: self.birrp_dict = self.j_obj.header_dict for b_key in list(self.birrp_dict.keys()): if 'filnam' in b_key: self.birrp_dict.pop(b_key) # fill in different blocks of the edi file self._fill_site() self._fill_info() self._fill_field_notes() # write edi file edi_fn = mtfh.make_unique_filename( os.path.join(self.birrp_dir, '{0}.edi'.format(self.station))) edi_fn = self.mt_obj._write_edi_file(new_edi_fn=edi_fn) return edi_fn
def rewrite_cache_file(self): """ rewrite a cache file if parameters changed assuming data that was read in is in counts. """ self.save_fn_rw = mtfh.make_unique_filename(self.save_fn) cfid = file(self.save_fn_rw, 'wb+') n_fn = self.ts.shape[1] #--> write navigation records first cfid.write(struct.pack('<i', self._nav_len)) cfid.write(struct.pack('<i', self._flag)) cfid.write(struct.pack('<h', self._type_dict['nav'])) for nd in range(self._nav_len - 2): cfid.write(struct.pack('<b', 0)) cfid.write(struct.pack('<i', self._nav_len)) #--> write meta data meta_str = ''.join([ key + ',' + ','.join(self.meta_data[key]) + '\n' for key in np.sort(list(self.meta_data.keys())) if key != '' ]) meta_len = len(meta_str) cfid.write(struct.pack('<i', meta_len + 2)) cfid.write(struct.pack('<i', self._flag)) cfid.write(struct.pack('<h', self._type_dict['meta'])) cfid.write(meta_str) cfid.write(struct.pack('<i', meta_len + 2)) #--> write calibrations cal_data1 = 'HEADER.TYPE,Calibrate\nCAL.VER,019\nCAL.SYS,0000,'+\ ''.join([' 0.000000: '+'0.000000 0.000000,'*3]*1) cal_data2 = '\nCAL.SYS,0000,'+\ ''.join([' 0.000000: '+'0.000000 0.000000,'*3]*1) cal_data = cal_data1 + (cal_data2 * (self.ts.shape[1] - 1)) cal_len = len(cal_data) cfid.write(struct.pack('<i', cal_len + 2)) cfid.write(struct.pack('<i', self._flag)) cfid.write(struct.pack('<h', self._type_dict['cal'])) cfid.write(cal_data[:-1] + '\n') cfid.write(struct.pack('<i', cal_len + 2)) #--> write data ts_block_len = self.ts.shape[0] * n_fn * 4 + 2 #--> make sure none of the data is above the allowed level self.ts[np.where(self.ts > 2.14e9)] = 2.14e9 self.ts[np.where(self.ts < -2.14e9)] = -2.14e9 #--> write time series block cfid.write(struct.pack('<i', ts_block_len)) cfid.write(struct.pack('<i', self._flag)) cfid.write(struct.pack('<h', self._type_dict['ts'])) for zz in range(self.ts.shape[0]): cfid.write(struct.pack('<' + 'i' * n_fn, *self.ts[zz])) cfid.write(struct.pack('<i', ts_block_len)) cfid.close() print('Rewrote {0}\n to {1}'.format(self.save_fn, self.save_fn_rw))