# http://pyrocko.org - GPLv3 # # The Pyrocko Developers, 21st Century # ---|P------/S----------~Lg----------
block_end_string='}', variable_start_string='\\VAR{', variable_end_string='}', comment_start_string='\\%{', comment_end_string='}', line_statement_prefix='\\-', line_comment_prefix='%%', trim_blocks=True, loader=PackageLoader('pyrocko', 'data/fomosto_report'))
Exception.__init__(self) self.frequency = frequency
def __str__(self): return 'Cannot set {0} frequency to both an absolute and' \ ' revlative value.'.format(self.frequency)
Exception.__init__(self) self.type = typ
def __str__(self): return 'Source type not currently supported: {0}'.format(self.type)
'sensor_count', 'change_dists']
def validate_args(cls, kwargs): k in cls.__sensorarray_allowed): ks.append(k)
del kwargs[i]
def __validate_args_target(cls, kwargs):
self.sensor_count) Target(north_shift=float(np.cos(np.radians(self.strike)) * dist), east_shift=float(np.sin(np.radians(self.strike)) * dist), **kwargs) for dist in dists]
'lowpass_frequency', 'rel_lowpass_frequency', 'highpass_frequency', 'rel_highpass_frequency', 'filter_order', 'plot_velocity', 'plot_everything']
def __get_valid_arguments(cls, args): tdict = {} for k in args: if k in cls.__valid_properties: tdict[k] = args[k] return tdict
raise FilterFrequencyError('lowpass') raise FilterFrequencyError('highpass')
self.rel_lowpass_frequency
self.rel_highpass_frequency
for x in self.store.config.tabulated_phases]) self.phase_ratio_string = r'\color{red}' \ '{warning: store has no tabulated phases}' else: self.phase_ratio_string = 'first({0})'.format(self.phases)
self.src_ids = sorted(self.sources) self.sen_ids = sorted(self.sensors)
self.pdf_dir = os.path.expanduser('~') self.store_id, self.getFrequencyString(None))
if self.message is None: self.message = '\nmessage(s) for store {0}:\n'. \ format(self.store_id) self.message += msg + '\n'
if self.message is not None: print(self.message)
os.remove(path)
return '' .format(typ, src.strike, src.dip, src.rake) elif isinstance(src, gf.RectangularExplosionSource): typ = 'Explosion' sstr = 'Source Type: {0}, Strike: {1:g}, Dip: {2:g}'.format( typ, src.strike, src.dip) else: typ = '{0}'.format(type(src)).split('.')[-1].split("'")[0] sstr = 'Source Type: {0}, see config page'.format(typ)
return ''
format(sen_ar.strike, targ.azimuth, targ.dip)
elif lpf: return 'lowpass {0:.4g}Hz'.format(lpf) elif hpf: return 'highpass {0:.4g}Hz'.format(hpf) else: return 'unfiltered'
return ''
elif lpf and lpfa: return 'lowpass frequency: {0:.4g} [Hz]'.format(lpf) elif hpf and hpfa: return 'highpass frequency: {0:.4g} [Hz]'.format(hpf) else: return 'unfiltered'
self.store_id, self.getSourceString(src_id), self.getSensorString(sen_id)) format(fac * 1e-9 / 1e3)
north_shift=0., east_shift=0., change_dists=True, **kwargs): elif depth < stMin or depth > stMax: if not change_dists: raise OutOfBounds('Source depth.') diff = abs(stMin - depth) if diff < stMax - depth: depth = stMin else: depth = stMax if not self.changed_depth: self.changed_depth = True self.__addToMessage( 'Source depth out of bounds. Changed to: {0:g}m.'. format(depth))
src = gf.RectangularExplosionSource( lat=lat, lon=lon, north_shift=north_shift, east_shift=east_shift, depth=depth, strike=strike, dip=dip) lat=lat, lon=lon, north_shift=north_shift, east_shift=east_shift, depth=depth, strike=strike, dip=dip, rake=rake) else: raise SourceError(typ)
typ[0:2], depth, strike, dip) tint += 1 tstr = srcstr + chr(tint)
change_dists=True, **kwargs): elif distance_min < stMin or distance_min > stMax: if not change_dists: raise OutOfBounds('Minimum sensor distance.') distance_min = stMin if not self.changed_dist_min: self.changed_dist_min = True self.__addToMessage( 'Sensor minimum distance out of bounds. Changed to allowed' ' minimum {0:g}m.'.format(stMin))
elif (distance_max > stMax or distance_max < stMin): if not change_dists: raise OutOfBounds('Maximum sensor distance') distance_max = stMax if not self.changed_dist_max: self.changed_dist_max = True self.__addToMessage( 'Sensor maximum distance out of bounds. Changed to allowed' ' maximum {0:g}m.'.format(stMax))
distance_min = stMin distance_max = stMax self.__addToMessage( 'Sensor minimum and maximum distance equal. Changed to' ' allowed minimum {0:g}m and maximum {1:g}m.'.format(stMin, stMax))
distance_max=distance_max, **kwargs) tint += 1 tstr = senstr + chr(tint)
continue continue continue continue self.sources[sr_id], self.sensors[sn_id].sensors) self.__tracesMinMax(trcs, sr_id, sn_id) trc.spectrum() for trc in trcs] except IndexError: self.__addToMessage( 'warning: IndexError: no traces created for' ' source-sensor combination: {0} - {1}. Try increasing' ' the sensor minimum distance.'.format( sr_id, sn_id))
src_id, sen_id = ids else: ((src_id == 'all' or src_id in self.sources) and (sen_id == 'all' or sen_id in self.sensors))): continue continue transfer_function=trace.DifferentiationResponse()) for trc in tdict['displacement_traces']] self.__tracesMinMax(trcs, src_id, sen_id) trc.spectrum() for trc in trcs]
continue continue
self.lowpass_frequency, demean=False)
self.lowpass_frequency, demean=False)
self.highpass_frequency, demean=False)
self.highpass_frequency, demean=False)
self.__tracesMinMax(trcs, sr_id, sn_id) self.__tracesMinMax(trcs, sr_id, sn_id)
gft2=None, together=False):
file_type = 'tex' dir = self.temp_dir fstr_id = self.__formatLatexString(str_id) else:
tpath = self.__createVelocityProfile(gft2) if is_tex: img_ttl = r'{0} \& {1}'.format( fstr_id, gft2.__formatLatexString(gft2.store_id)) else: img_ttl = r'{0} & {1}'.format(str_id, gft2.store_id) else:
if is_tex: fstr_id = self.__formatLatexString(gft2.store_id) str_id = r'{0} \& {1}'.format(str_id, gft2.store_id) else: fstr_id = gft2.store_id str_id = r'{0} & {1}'.format(str_id, gft2.store_id)
config = gft2.store.config.dump() if together: tpath = '' else: tpath = gft2.__createVelocityProfile()
info += [(fstr_id, config, tpath, fstr_id)]
f.write(temp.render( rpt_id=self.__formatLatexString(str_id), str_info=info, artefacts=artefacts, chapters=chapters, config=config, headings='headings')) rpt_id=str_id, str_info=info, artefacts=artefacts, chapters=chapters, config=config, date=datetime.datetime.now().strftime('%B %d, %Y')))
pro_call = ['pdflatex', '-output-directory', self.pdf_dir, out, '-interaction', 'nonstop'] try: subprocess.call(pro_call) subprocess.call(pro_call) subprocess.call(pro_call) except OSError: raise FomostoReportError( 'Cannot run "pdflatex" executable. Is it installed?')
gft2.cleanup()
def __formatLatexString(string): rep = {'_': r'\_', r'\n': r'\\', '|': r'\textbar '} rep = {re.escape(k): v for k, v in rep.items()} pat = re.compile('|'.join(rep.keys())) return pat.sub(lambda m: rep[re.escape(m.group(0))], string)
continue self.getSourceString(src_id), self.getSensorString(sen_id)) trc_id=tid, str_id=self.store_id, type='d') self.__saveTempFigure(fig))]) for x in figs[1:]])
self.__saveTempFigure(fig)))
'displacement_spectra') self.__saveTempFigure(fig)))
trc_id=tid, str_id=self.store_id, type='v') self.__saveTempFigure(fig))]) for x in figs[1:]])
self.__saveTempFigure(fig)))
'velocity_spectra') self.__saveTempFigure(fig))) src_str = self.__formatLatexString( self.sources[src_id].dump()) sen_str = self.__formatLatexString( self.sensors[sen_id].dump()) else: self.__createOutputDoc( [[self.__formatLatexString(self.store_id), self.__formatLatexString(self.phase_ratio_string), artefacts]], chapters) [[self.store_id, self.phase_ratio_string, artefacts]], chapters)
def createComparisonOutputDoc(cls, gft1, gft2, *trc_ids, **kwargs): # only valid kwargs is 'together' if 'together' in kwargs: together = kwargs['together'] else: together = True
if len(trc_ids) == 0: trc_ids = gft1.traces.keys()
tname = '{0}-{1}{2}{3}'.format( gft1.store_id, gft2.store_id, '_together_' if together else '_', gft1.getFrequencyString(None)) gft1.pdf_name = tname gft2.pdf_name = tname
trcs1 = gft1.traces trcs2 = gft2.traces
art1 = gft1.__getArtefactPageInfo(trc_ids) art2 = gft2.__getArtefactPageInfo(trc_ids, gft1.store_id) chapters = [] if gft1.plot_everything: for tid in trc_ids: if tid not in trcs1 or tid not in trcs2: continue src_id, sen_id = tid.split('|') ttl = '{0}, {1}'.format( gft1.getSourceString(src_id), gft1.getSensorString(sen_id)) tdict1 = trcs1[tid] tdict2 = trcs2[tid] img_data = [] href = r'\hypertarget{${trc_id}|${str_id}|${type}}{}' trcname = 'displacement_traces' tstr = 'displacement_spectra' if trcname in tdict1 and trcname in tdict2: hstr = Template(href).substitute( trc_id=tid, str_id=gft1.store_id, type='d') figs = cls.__createComparisonTraceFigures( gft1, gft2, tid, trcname, together) fig = figs[0] img_data.extend([(gft1.__getFigureTitle(fig), hstr, gft1.__saveTempFigure(fig))]) img_data.extend([('', '', gft1.__saveTempFigure(x)) for x in figs[1:]])
if tstr in tdict1 and tstr in tdict2: fig = gft1.__createComparisonMaxAmpFigure( gft1, gft2, tid, trcname, together) img_data.append((gft1.__getFigureTitle(fig), '', gft1.__saveTempFigure(fig)))
trcname = tstr if not together: if trcname in tdict1 and trcname in tdict2: fig = cls.__createComparissonSpectraFigure( gft1, gft2, tid, trcname) img_data.append((gft1.__getFigureTitle(fig), '', gft1.__saveTempFigure(fig)))
trcname = 'velocity_traces' tstr = 'velocity_spectra' if gft1.plot_velocity and gft2.plot_velocity and \ trcname in tdict1 and trcname in tdict2:
hstr = Template(href).substitute( trc_id=tid, str_id=gft1.store_id, type='v') figs = cls.__createComparisonTraceFigures( gft1, gft2, tid, trcname, together) fig = figs[0] img_data.extend([(gft1.__getFigureTitle(fig), hstr, gft1.__saveTempFigure(fig))]) img_data.extend([('', '', gft1.__saveTempFigure(x)) for x in figs[1:]])
if tstr in tdict1 and tstr in tdict2: fig = gft1.__createComparisonMaxAmpFigure( gft1, gft2, tid, trcname, together) img_data.append((gft1.__getFigureTitle(fig), '', gft1.__saveTempFigure(fig)))
if not together: if tstr in tdict1 and tstr in tdict2: fig = cls.__createComparissonSpectraFigure( gft1, gft2, tid, tstr) img_data.append((gft1.__getFigureTitle(fig), '', gft1.__saveTempFigure(fig)))
if gft1.output_format == 'pdf': src_str = gft1.__formatLatexString( gft1.sources[src_id].dump()) sen_str = gft1.__formatLatexString( gft1.sensors[sen_id].dump()) else: src_str = gft1.sources[src_id].dump() sen_str = gft1.sensors[sen_id].dump()
chapters.append([ttl, src_str, sen_str, img_data])
if gft1.output_format == 'pdf': gft1.__createOutputDoc( [[gft1.__formatLatexString(gft1.store_id), gft1.__formatLatexString(gft1.phase_ratio_string), art1], [gft2.__formatLatexString(gft2.store_id), gft2.__formatLatexString(gft2.phase_ratio_string), art2]], chapters, gft2=gft2, together=together) elif gft1.output_format == 'html': gft1.__createOutputDoc( [[gft1.store_id, gft1.phase_ratio_string, art1], [gft2.store_id, gft2.phase_ratio_string, art2]], chapters, gft2=gft2, together=together)
sp = r'\ '*6 else:
# list of [<trace string>, <ratio text color>, <ratio string>] continue self.getSensorString(sen_id)) ttl_str = r'\textbr{%s}' % ttl_str
sp, 'Displacement', chCode) tex = r'\hyperlink{${tid}|${str_id}|${type}}{${title}}' ttl_str = Template(tex).substitute( tid=tid, str_id=str_id, type='d', title=ttl_str)
else 'black') tex = r'\hyperlink{${tid}|${str_id}|${type}}{${title}}' ttl_str = Template(tex).substitute( tid=tid, str_id=str_id, type='v', title=ttl_str)
(0.01, 0.01)) break
def __createComparisonTraceFigures( gfTest1, gfTest2, trc_id, trc_type, together):
tdict = gfTest1.traces[trc_id] sc1 = tdict['{0}_scale'.format(trc_type.split('_')[0])]
tdict = gfTest2.traces[trc_id] sc2 = tdict['{0}_scale'.format(trc_type.split('_')[0])]
absmax = (sc1 + sc2) / 2. figs = [] for i in gfTest1.__scalelist: if together: fig = gfTest1.__setupFigure(trc_type, 1) ax, ax2 = fig.axes zerotrc1 = gfTest1.__drawTraceData( trc_id, trc_type, ax, ax2, i, (0.01, 0.01), showphases=False, absmax=absmax) zerotrc2 = gfTest2.__drawTraceData( trc_id, trc_type, ax, ax2, i, (0.92, 0.01), color=plot.mpl_color('scarletred2'), hor_ali='right', showphases=False, absmax=absmax) gfTest1.__drawBeachball(trc_id, ax) else: fig = gfTest1.__setupFigure(trc_type, 2) ax, ax2, ax3, ax4 = fig.axes zerotrc1 = gfTest1.__drawTraceData( trc_id, trc_type, ax, ax2, i, (0.01, 0.01), absmax=absmax) gfTest1.__drawBeachball(trc_id, ax) zerotrc2 = gfTest2.__drawTraceData( trc_id, trc_type, ax3, ax4, i, (0.98, 0.01), hor_ali='right', absmax=absmax) gfTest2.__drawBeachball(trc_id, ax3)
figs.append(fig) if zerotrc1 and zerotrc2: break return figs
color='black', hor_ali='left', showphases=True, absmax=None): phdict = None
absmax = 1. zerotrc = True
(dist + trc.get_ydata() * ysc2) * cake.m2d, '-', color=color)
label='{0}-wave'.format(pid), marker='o', markersize=3, color=plot.to01(plot.graph_colors[i % 7]))
else: xlims = lfax.get_xlim() xlims = (min(xmin, xlims[0]), max(xmax, xlims[1])) lfax.set_xlim(xlims)
trc_type.split('_')[0].title(), chCode, self.getFrequencyString(trc_id)), y=1.015) xy=anno_pt, fontsize=(self.__notesize), xycoords='figure fraction', ha=hor_ali, color=color) lfax.annotate("Zero amplitudes!\nSpectra will not\nbe plotted.", xy=(0.001, 0.), fontsize=25, alpha=0.75, rotation=0., xycoords='axes fraction', color=plot.mpl_color('aluminium4'))
def __createComparissonSpectraFigure(gfTest1, gfTest2, trc_id, spc_id): fig = gfTest1.__setupFigure('spectra', 2) ax, ax2 = fig.axes gfTest1.__drawSpectraData(trc_id, ax, (0.01, 0.01), spc_id, show_cbar=False) gfTest2.__drawSpectraData(trc_id, ax2, (0.98, 0.01), spc_id, hor_ali='right') # evenly space the axes ax1, ax2, ax3 = fig.axes pos1 = ax1.get_position() pos2 = ax2.get_position() fac = (pos2.x0 - pos1.x1) / 2. mid = (pos2.x1 + pos1.x0) / 2. wid = mid - fac - pos1.x0 ax1.set_position([pos1.x0, pos1.y0, wid, pos1.height]) ax2.set_position([mid + fac, pos2.y0, wid, pos2.height]) return fig
hor_ali='left', show_cbar=True): marker='x')
'm' if spc_id.startswith('displacement') else 'm/s')) format(spc_id.split('_')[0].title(), chCode), y=1.015) xy=anno_pt, ha=hor_ali, fontsize=(self.__notesize), xycoords='figure fraction') cmap=cmap, norm=plt.Normalize(vmin=tmin, vmax=tmax)) self.sensors[sen_id].sensor_count))
def __createComparisonMaxAmpFigure(gfTest1, gfTest2, trc_id, trc_typ, together): if together: fig = gfTest1.__setupFigure('maxamp_{0}'.format(trc_typ), 1) ax, ax2 = fig.axes gfTest1.__drawMaxAmpData(trc_id, ax, ax2, (0.01, 0.01), trc_typ) gfTest2.__drawMaxAmpData(trc_id, ax, ax2, (0.92, 0.01), trc_typ, color=plot.mpl_color('scarletred2'), hor_ali='right') else: fig = gfTest1.__setupFigure('maxamp_{0}'.format(trc_typ), 2) ax, ax2, ax3, ax4 = fig.axes gfTest1.__drawMaxAmpData(trc_id, ax, ax2, (0.01, 0.01), trc_typ) gfTest2.__drawMaxAmpData(trc_id, ax3, ax4, (0.98, 0.01), trc_typ, hor_ali='right') return fig
color='black', hor_ali='left'):
topax.set_xlim(xlims) btmax.set_ylim(ylims) else: format(trc_typ.split('_')[0].title(), chCode), y=1.08) xy=anno_pt, ha=hor_ali, color=color, fontsize=(self.__notesize), xycoords='figure fraction')
else:
else: data, depths = self.__getModelProperty(opt) ax.plot(data, depths, linewidth=3, linestyle='--', alpha=0.8, label=self.store_id, color=plot.mpl_color('aluminium4')) data, depths = gft2.__getModelProperty(opt) ax.plot(data, depths, linewidth=1, color=plot.mpl_color('scarletred2'), label=gft2.store_id)
else: pos.height - (y - pos.y0)]) else:
else: ttl = 'Earth model plots: {0} & {1}'.format(self.store_id, gft2.store_id) ax.legend(bbox_to_anchor=(1.25, 1.), loc=2)
xycoords='figure fraction', ha='center', va='top')
wspace=7., nw=cols, nh=rows) else:
def __getFigureTitle(fig): continue return ''
szpt, -szpt, ax.figure.dpi_scale_trans) ax.transData.transform((bbx, bby)))) size=sz, position=(bbx, bby))
fname = NamedTemporaryFile( prefix='gft_', suffix='.pdf', dir=self.temp_dir, delete=False) fname.close() fig.savefig(fname.name, transparent=True) out = fname.name
# return the min/max amplitudes before and after the arrival of the # self.phase_ratio_string phase found in the traces, # plus the maximum ratio between the max absolute value
tbrk = None else: else: tminb = 0. tmaxb = 0. after.append((tminb, tmaxb)) else:
# return the min/max amplitudes before and after the arrival of the # self.phase_ratio_string phase found in the traces, # plus the maximum ratio between the max absolute value max(abs(b[0]), abs(b[1]))/max(abs(a[0]), abs(a[1])), before, after))
def __createStandardSetups(cls, store_dir, **kwargs): tdict = cls.__get_valid_arguments(kwargs)
gft = cls(store_dir, **tdict)
if 'source_depth' in kwargs: depth = kwargs['source_depth'] else: depth = None src1 = gft.createSource('DC', depth, 0., 90., 0., **kwargs) # src2 = gft.createSource('DC', depth, -90., 90., -90., **kwargs) src3 = gft.createSource('DC', depth, 45., 90., 180., **kwargs) # src4 = gft.createSource('Explosion', depth, 0., 90., **kwargs)
SensorArray.validate_args(kwargs) sen1 = gft.createSensors(strike=0., codes=('', 'STA', '', 'R'), azimuth=0., dip=0., **kwargs) sen2 = gft.createSensors(strike=0., codes=('', 'STA', '', 'T'), azimuth=90., dip=0., **kwargs) sen3 = gft.createSensors(strike=0., codes=('', 'STA', '', 'Z'), azimuth=0., dip=-90., **kwargs)
gft.trace_configs = [[src3, sen1], [src1, sen2], [src3, sen3]] # gft.trace_configs = [[src3, sen1]] # gft.trace_configs = [[src3, sen1], [src1, sen2], [src3, sen3], # [src4, 'all']] # gft.trace_configs = [[src4, 'all']] # gft.trace_configs = [['all', 'all']] gft.__applyTypicalProcedures() return gft
if self.trace_configs is None: self.createDisplacementTraces() else: for src, sen in self.trace_configs: self.createDisplacementTraces(src, sen) if self.plot_velocity: if self.trace_configs is None: self.createVelocityTraces() else: for src, sen in self.trace_configs: self.createVelocityTraces('{0}|{1}'.format(src, sen)) self.applyFrequencyFilters() self.getPhaseArrivals()
for k in kwargs: temp = kwargs[k] if temp is not None: setattr(self, k, temp)
cls, store_dir, source_depth=None, lowpass_frequency=None, highpass_frequency=None, rel_lowpass_frequency=(1. / 110), rel_highpass_frequency=(1. / 16), distance_min=None, distance_max=None, sensor_count=50, filter_order=4, pdf_dir=None, plot_velocity=False, plot_everything=True, output_format='pdf'):
args = locals() del args['cls'] gft = cls.__createStandardSetups(**args) gft.createOutputDoc() gft.__printMessage() return gft
cls, store_dir1, store_dir2, distance_min, distance_max, together=True, source_depth=None, output_format='pdf', lowpass_frequency=None, highpass_frequency=None, rel_lowpass_frequency=(1. / 110), rel_highpass_frequency=(1. / 16), filter_order=4, pdf_dir=None, plot_velocity=False, plot_everything=True, sensor_count=50):
args = locals() del args['cls'] args['change_dists'] = False gft1 = cls.__createStandardSetups(store_dir1, **args) if 'source_depth' not in args or args['source_depth'] is None: args['source_depth'] = gft1.sources[list(gft1.sources.keys())[0]]\ .depth
gft2 = cls.__createStandardSetups(store_dir2, **args)
cls.createComparisonOutputDoc(gft1, gft2, together=together) gft1.__printMessage() gft2.__printMessage() return gft1, gft2
with open(filename, 'r') as f: fstr = f.read() gfts = [] st = None end = -1 tstr = '--- !{0}.GreensFunctionTest'.format(guts_prefix) try: while True: st = fstr.index(tstr, end + 1) if st is None: break if st > 0 and fstr[st - 1:st] != '\n': end = st st = None continue end = fstr.index('\n{0}'.format(tstr), st) gfts.append(fstr[st:end]) except ValueError: if st is not None: gfts.append(fstr[st:])
cnt = len(gfts) if cnt == 0: raise TypeError('error: GreensFunctionTest: non-valid config' ' file passed: {0}'.format(filename)) elif cnt > allowed: raise TypeError('error: GreensFunctionTest: to many configs in' ' file passed: {0}'.format(filename)) elif cnt < allowed: raise TypeError('error: GreensFunctionTest: not enough configs in' ' file passed: {0}'.format(filename))
if cnt == allowed == 1: gft = load(stream=gfts[0]) gft.__update(**kwargs) gft.__applyTypicalProcedures() gft.createOutputDoc() gft.__printMessage() return gft
if cnt == allowed == 2: gft = load(stream=gfts[0]) gft.__update(**kwargs) gft.__applyTypicalProcedures()
gft2 = load(stream=gfts[1]) gft2.__update(**kwargs) gft2.__applyTypicalProcedures()
gft.createComparisonOutputDoc(gft, gft2, **kwargs) gft.__printMessage() gft2.__printMessage() return gft, gft2 |