class QSeisConfig(Object): qseis_version = String.T(default='2006') time_region = Tuple.T(2, Timing.T(), default=(Timing('-10'), Timing('+890'))) cut = Tuple.T(2, Timing.T(), optional=True) fade = Tuple.T(4, Timing.T(), optional=True) relevel_with_fade_in = Bool.T(default=False) sw_algorithm = Int.T(default=0) slowness_window = Tuple.T(4, Float.T(default=0.0)) wavenumber_sampling = Float.T(default=2.5) aliasing_suppression_factor = Float.T(default=0.1) filter_surface_effects = Int.T(default=0) filter_shallow_paths = Int.T(default=0) filter_shallow_paths_depth = Float.T(default=0.0) propagation_filters = List.T(QSeisPropagationFilter.T()) receiver_filter = QSeisPoleZeroFilter.T(optional=True) sw_flat_earth_transform = Int.T(default=0) gradient_resolution_vp = Float.T(default=0.0) gradient_resolution_vs = Float.T(default=0.0) gradient_resolution_density = Float.T(default=0.0) wavelet_duration_samples = Float.T(default=0.0) wavelet_type = Int.T(default=2) user_wavelet_samples = List.T(Float.T()) def items(self): return dict(self.T.inamevals(self))
class SandboxSceneConfig(Object): frame = FrameConfig.T(default=FrameConfig(), help='Frame/reference configuration') extent_north = Int.T(default=800, help='Model size towards north in [px]') extent_east = Int.T(default=800, help='Model size towards east in [px]') sources = List.T(help='List of sources') reference_scene = String.T(optional=True, help='Reference kite.Scene container')
class Decimation(Object): '''Corresponds to SEED blockette 57.''' input_sample_rate = Frequency.T(xmltagname='InputSampleRate') factor = Int.T(xmltagname='Factor') offset = Int.T(xmltagname='Offset') delay = FloatWithUnit.T(xmltagname='Delay') correction = FloatWithUnit.T(xmltagname='Correction')
class Similarity(Object): '''CC result of one event pair at one target.''' ievent = Int.T(help='Event identifier') jevent = Int.T(help='Event identifier') itarget = Int.T(help='Target identifier') cross_correlation = Float.T() cross_correlation_trace = SeismosizerTrace.T(optional=True) relative_amplitude = Float.T( help='Relative amplitude with reference to ievent.') time_lag = Float.T(help='Time lag at maximum of cross correlation')
class OriginQuality(Object): associated_phase_count = Int.T(optional=True) used_phase_count = Int.T(optional=True) associated_station_count = Int.T(optional=True) used_station_count = Int.T(optional=True) depth_phase_count = Int.T(optional=True) standard_error = Float.T(optional=True) azimuthal_gap = Float.T(optional=True) secondary_azimuthal_gap = Float.T(optional=True) ground_truth_level = GroundTruthLevel.T(optional=True) maximum_distance = Float.T(optional=True) minimum_distance = Float.T(optional=True) median_distance = Float.T(optional=True)
class PoelConfig(Object): s_radius = Float.T(default=0.0) s_type = Int.T(default=0) source_function_p = Float.T(default=1.0) source_function_i = PoelSourceFunction.T(default=PoelSourceFunction.D( data=num.array([[0., 0.], [10., 1.]], dtype=num.float))) t_window = Float.T(default=500.) accuracy = Float.T(default=0.025) isurfcon = Int.T(default=1) model = PoelModel.T(default=PoelModel(data=num.array( [[0.00, 0.4E+09, 0.2, 0.4, 0.75, 5.00]], dtype=num.float))) def items(self): return dict(self.T.inamevals(self))
class MetropolisConfig(SamplerParameters): """ Config for optimization parameters of the Adaptive Metropolis algorithm. """ n_steps = Int.T(default=25000, help='Number of steps for the MC chain.') n_chains = Int.T(default=20, help='Number of Metropolis chains for sampling.') thin = Int.T( default=2, help='Thinning parameter of the sampled trace. Every "thin"th sample' ' is taken.') burn = Float.T( default=0.5, help='Burn-in parameter between 0. and 1. to discard fraction of' ' samples from the beginning of the chain.')
class PNG(PlotFormat): name = 'png' dpi = Int.T( optional=True, help='DPI of the figure') size_pixels = Int.T( optional=True, help='Size in pixels') width_pixels = Int.T( optional=True, help='Width in pixels') height_pixels = Int.T( optional=True, help='Height in pixels') @property def extension(self): if self.dpi is not None: return 'd%i.png' % self.dpi elif self.size_pixels is not None: return 's%i.png' % self.size_pixels elif self.width_pixels is not None: return 'w%i.png' % self.width_pixels elif self.height_pixels is not None: return 'h%i.png' % self.height_pixels else: return 'd100.png' def get_dpi(self, size_cm): w_cm, h_cm = size_cm w_inch, h_inch = w_cm/inch, h_cm/inch if self.dpi: return self.dpi elif self.size_pixels is not None: return min(self.size_pixels/w_inch, self.size_pixels/h_inch) elif self.width_pixels is not None: return self.width_pixels/w_inch elif self.height_pixels is not None: return self.height_pixels/h_inch else: return 100.0 def render_mpl(self, fig, path, **kwargs): return fig.savefig(path, format=self.name, **kwargs) def render_automap(self, automap, path, **kwargs): return automap.save(path, **kwargs)
class Generator(Object): seed = Int.T(optional=True, help='Random seed for a reproducible scenario.') def __init__(self, **kwargs): Object.__init__(self, **kwargs) self._seed = None self._parent = None self.update_hierarchy() self._retry_offset = 0 def retry(self): self.clear() self._retry_offset += 1 for val in self.T.ivals(self): if isinstance(val, Generator): val.retry() def clear(self): self._seed = None def hash(self): return hashlib.sha1( (self.dump() + '\n\n%i' % self._retry_offset).encode('utf8'))\ .hexdigest() def get_seed_offset(self): return int(self.hash(), base=16) % N def update_hierarchy(self, parent=None): self._parent = parent for val in self.T.ivals(self): if isinstance(val, Generator): val.update_hierarchy(parent=self) def get_seed(self): if self._seed is None: if self.seed is None: if self._parent is not None: self._seed = self._parent.get_seed() else: self._seed = num.random.randint(N) elif self.seed == 0: self._seed = num.random.randint(N) else: self._seed = self.seed return self._seed + self.get_seed_offset() def get_rstate(self, i): return num.random.RandomState(self.get_seed() + i) def get_center_latlon(self): return self._parent.get_center_latlon() def get_radius(self): return self._parent.get_radius() def get_stations(self): return []
class PalantiriXcorrConfig(Object): '''Configuration of data IO and data preprocessing''' xcorr = Bool.T(default=True, optional=True, help='') xcorrtreshold = Float.T(default=0.6, optional=True, help='') autoxcorrcorrectur = Bool.T(default=False, optional=True, help='') refstationfreqmin = Float.T(default=0.03, optional=True, help='Length in seconds. Not needed \ when using TFRecordData') refstationfreqmax = Float.T(default=1, optional=True, help='Length in seconds. Not needed \ when using TFRecordData') refstationcorners = Int.T(default=2, optional=True, help='Length in seconds. Not needed \ when using TFRecordData') refstationzph = Bool.T(default=False, optional=True, help='') refsta = Float.T(default=0.5, optional=True, help='Length in seconds. Not needed \ when using TFRecordData') reflta = Float.T(default=2, optional=True, help='Length in seconds. Not needed \ when using TFRecordData')
class PyrockoRectangularSource(SandboxSourceRectangular, PyrockoSource): """Classical Haskell source model modified for bilateral rupture. See :class:`pyrocko.gf.seismosizer.RectangularSource`. """ __implements__ = "pyrocko" decimation_factor = Int.T(optional=True, default=10, help="Sub-source decimation factor.") store_dir = String.T(help="Pyrocko GF Store path") parametersUpdated = PyrockoSource.parametersUpdated def __init__(self, *args, **kwargs): SandboxSourceRectangular.__init__(self, *args, **kwargs) self.pyrocko_source = gf.RectangularSource(**self._src_args) @property def _src_args(self): return { "lat": 0.0, "lon": 0.0, "north_shift": self.northing, "east_shift": self.easting, "depth": self.depth, "length": self.length, "width": self.width, "strike": self.strike, "dip": self.dip, "rake": self.rake, "slip": self.slip, "decimation_factor": self.decimation_factor, "anchor": "top", }
class CMTProblemConfig(ProblemConfig): ranges = Dict.T(String.T(), gf.Range.T()) distance_min = Float.T(default=0.0) mt_type = MTType.T(default='full') stf_type = STFType.T(default='HalfSinusoidSTF') nthreads = Int.T(default=1) def get_problem(self, event, target_groups, targets): if event.depth is None: event.depth = 0. base_source = gf.MTSource.from_pyrocko_event(event) stf = STFType.base_stf(self.stf_type) stf.duration = event.duration or 0.0 base_source.stf = stf subs = dict(event_name=event.name, event_time=util.time_to_str(event.time)) problem = CMTProblem(name=expand_template(self.name_template, subs), base_source=base_source, target_groups=target_groups, targets=targets, ranges=self.ranges, distance_min=self.distance_min, mt_type=self.mt_type, stf_type=self.stf_type, norm_exponent=self.norm_exponent, nthreads=self.nthreads) return problem
class VolumePointProblemConfig(ProblemConfig): ranges = Dict.T(String.T(), gf.Range.T()) distance_min = Float.T(default=0.0) nthreads = Int.T(default=1) def get_problem(self, event, target_groups, targets): if event.depth is None: event.depth = 0. base_source = gf.ExplosionSource.from_pyrocko_event(event) base_source.stf = gf.HalfSinusoidSTF(duration=event.duration or 0.0) subs = dict(event_name=event.name, event_time=util.time_to_str(event.time)) problem = VolumePointProblem(name=expand_template( self.name_template, subs), base_source=base_source, target_groups=target_groups, targets=targets, ranges=self.ranges, distance_min=self.distance_min, norm_exponent=self.norm_exponent, nthreads=self.nthreads) return problem
class PyrockoRectangularSource(SandboxSourceRectangular, PyrockoSource): '''Classical Haskell source model modified for bilateral rupture. See :class:`pyrocko.gf.seismosizer.RectangularSource`. ''' __implements__ = 'pyrocko' decimation_factor = Int.T(optional=True, default=10, help='Sub-source decimation factor.') store_dir = String.T(help='Pyrocko GF Store path') parametersUpdated = PyrockoSource.parametersUpdated def __init__(self, *args, **kwargs): SandboxSourceRectangular.__init__(self, *args, **kwargs) self.pyrocko_source = gf.RectangularSource(**self._src_args) @property def _src_args(self): return { 'lat': 0., 'lon': 0., 'north_shift': self.northing, 'east_shift': self.easting, 'depth': self.depth, 'length': self.length, 'width': self.width, 'strike': self.strike, 'dip': self.dip, 'rake': self.rake, 'slip': self.slip, 'decimation_factor': self.decimation_factor, 'anchor': 'top', }
class City(Object): def __init__(self, name, lat, lon, population=None, asciiname=None): name = unicode(name) lat = float(lat) lon = float(lon) if asciiname is None: asciiname = name.encode('ascii', errors='replace') if population is None: population = 0 else: population = int(population) Object.__init__(self, name=name, lat=lat, lon=lon, population=population, asciiname=asciiname) name = Unicode.T() lat = Float.T() lon = Float.T() population = Int.T() asciiname = String.T()
class CatalogConfig(Object): search_events = Bool.T() use_local_catalog = Bool.T() subset_of_local_catalog = Bool.T() use_local_subsets = Bool.T() subset_fns = Dict.T() # catalog catalog_fn = String.T( optional=True, help='Name of local catalog to save to or to read from') dist = Float.T(default=165.0, help='Max. distance to show on catalog plot (map) [deg]') min_mag = Float.T() max_mag = Float.T() tmin_str = String.T() tmax_str = String.T() wedges_width = Int.T( help='Find one event in backazimuthal wedge of this width') mid_point = List.T( optional=True, help='Enter some estimation on centre point of array, needed for\ subset based on distances and plotting only.') median_ev_in_bin = Bool.T(default=True) # weighted_magn_baz_ev = Bool.T() min_dist_km = Float.T() max_dist_km = Float.T() depth_options = Dict.T() plot_catalog_all = Bool.T(default=False) plot_hist_wedges = Bool.T(default=False) plot_wedges_vs_dist = Bool.T(default=False) plot_wedges_vs_magn = Bool.T(default=False) plot_dist_vs_magn = Bool.T(default=False) plot_catalog_subset = Bool.T(default=False)
class QSeisRBandpassFilter(Object): order = Int.T(default=-1) lower_cutoff = Float.T(default=0.1) # [Hz] upper_cutoff = Float.T(default=10.0) def string_for_config(self): return '%(order) %(lower_cutoff)5e %(upper_cutoff)5e' % self.__dict__
class StationGenerator(TargetGenerator): nstations = Int.T(default=10, help='Number of randomly distributed stations.') network_name = String.T(default='CO', help='Network name') with_channels = Bool.T(default=True, help='Generate seismic channels: BHN, BHE, BHZ')
class GFLibaryConfig(Object): """ Baseconfig for GF Libraries """ component = String.T(default='uparr') event = model.Event.T(default=model.Event.D()) datatype = String.T(default='undefined') crust_ind = Int.T(default=0)
class QSeisPropagationFilter(Object): min_depth = Float.T(default=0.0) max_depth = Float.T(default=0.0) filtered_phase = Int.T(default=0) def string_for_config(self): return '%(min_depth)15e %(max_depth)15e ' \ '%(filtered_phase)i' % self.__dict__
class TargetBalancingAnalyserConfig(AnalyserConfig): """Configuration parameters of the target balancing.""" niterations = Int.T(default=1000, help='Number of random forward models for mean \ phase amplitude estimation') def get_analyser(self): return TargetBalancingAnalyser(niter=self.niterations)
class ProblemConfig(Object): ''' Base class for config section defining the objective function setup. Factory for :py:class:`Problem` objects. ''' name_template = String.T() norm_exponent = Int.T(default=2) nthreads = Int.T(default=1) def get_problem(self, event, target_groups, targets): ''' Instantiate the problem with a given event and targets. :returns: :py:class:`Problem` object ''' raise NotImplementedError
class PsGrnSpatialSampling(Object): n_steps = Int.T(default=10) start_distance = Float.T(default=0.) # start sampling [km] from source end_distance = Float.T(default=100.) # end def string_for_config(self): return '%i %15e %15e' \ % (self.n_steps, self.start_distance, self.end_distance)
class PoleZero(Object): '''Complex numbers used as poles or zeros in channel response.''' number = Int.T(optional=True, xmlstyle='attribute') real = FloatNoUnit.T(xmltagname='Real') imaginary = FloatNoUnit.T(xmltagname='Imaginary') def value(self): return self.real.value + 1J * self.imaginary.value
class Sample(Object): '''Sample model with context about how it was generated.''' model = Array.T(shape=(None, ), dtype=num.float, serialize_as='list') iphase = Int.T(optional=True) ichain_base = Int.T(optional=True) ilink_base = Int.T(optional=True) imodel_base = Int.T(optional=True) def preconstrain(self, problem): self.model = problem.preconstrain(self.model) def pack_context(self): i = num.zeros(4, dtype=num.int) i[:] = (fnone(self.iphase), fnone(self.ichain_base), fnone(self.ilink_base), fnone(self.imodel_base)) return i
class GRLawSTF(STF): '''Poisson distributed random impulses based on the Gutenberg-Richter law.''' duration = Float.T(default=0.0, help='baseline of the ramp') anchor = Float.T( default=0.0, help='anchor point with respect to source-time: (' '-1.0: left -> source duration [0, T] ~ hypocenter time, ' ' 0.0: center -> source duration [-T/2, T/2] ~ centroid time, ' '+1.0: right -> source duration [-T, 0] ~ rupture end time)') mag = Float.T(default=5.0, help='magnitude used for Gutenberg-Richter law') b = Float.T(default=1.2, help='b parameter for Gutenberg-Richter law') poisson_envelope = Int.T( default=0, help= 'Whether to apply a Poisson distribution envelope to the magnitudes of the asperities.' ) mu = Float.T(default=10, help='Mu parameter for Poisson envelope') loc = Float.T(optional=True, help="'loc' parameter for Poisson distribution function") def discretize_t(self, deltat, tref): # Gutenberg-Ricther law M = np.linspace(0, self.mag, 1000) pdf = self.b * np.log(10) * 10**(-self.b * M) self.cdf = 1 - 10**(-self.b * M) # method returns discrete times and the respective amplitudes tmin_stf = tref - self.duration * (self.anchor + 1.) * 0.5 tmax_stf = tref + self.duration * (1. - self.anchor) * 0.5 tmin = round(tmin_stf / deltat) * deltat tmax = round(tmax_stf / deltat) * deltat nt = int(round((tmax - tmin) / deltat)) + 1 times = np.linspace(tmin, tmax, nt) if nt > 1: self._amplitudes = np.random.uniform(min(self.cdf), max(self.cdf), nt) if self.poisson_envelope: x = np.linspace(0, nt - 1, nt) self.envelope = poisson.pmf(x, mu=self.mu, loc=self.loc) self.amplitudes = self.mag * (self._amplitudes * self.envelope) else: self.amplitudes = self._amplitudes else: self.amplitudes = np.ones(1) return times, self.amplitudes def base_key(self): # method returns STF name and the values return (self.__class__.__name__, self.duration, self.anchor)
class NormalizeNthRoot(Normalization): '''Normalize traces by their Nth root. Note: polarities get lost.''' nth_root = Int.T(default=4) def __call__(self, chunk): chunk -= num.nanmean(chunk) chunk[:] = num.power(num.abs(chunk), 1./self.nth_root) chunk += num.nanmean(chunk)
class MapParameters(Object): width = Float.T(help="width of map", optional=True, default=16) height = Float.T(help="heigth of map", optional=True, default=16) lat = Float.T(help="center latitude") lon = Float.T(help="center longitude") radius = Float.T(help="radius of map") outfn = String.T(help="output filename", optional=True, default="map.png") stations = List.T(model.Station.T(), optional=True) station_label_mapping = List.T(String.T(), optional=True) station_colors = Dict.T(String.T(), String.T(), optional=True) events = List.T(model.Event.T(), optional=True) show_topo = Bool.T(optional=True, default=True) show_grid = Bool.T(optional=True, default=True) color_wet = Tuple.T(3, Int.T(), default=(200, 200, 200)) color_dry = Tuple.T(3, Int.T(), default=(253, 253, 253)) @classmethod def process_args(cls, *args, **kwargs): return cls(**kwargs)
class SeismicGFLibraryConfig(GFLibaryConfig): """ Config for the linear Seismic GF Library for dumping and loading. """ wave_config = WaveformFitConfig.T(default=WaveformFitConfig.D()) starttime_sampling = Float.T(default=0.5) duration_sampling = Float.T(default=0.5) starttime_min = Float.T(default=0.) duration_min = Float.T(default=0.1) dimensions = Tuple.T(5, Int.T(), default=(0, 0, 0, 0, 0))
class SamplerParameters(Object): n_jobs = Int.T( default=1, help='Number of processors to use, i.e. chains to sample in parallel.') tune_interval = Int.T( default=50, help='Tune interval for adaptive tuning of Metropolis step size.') proposal_dist = String.T( default='Normal', help='Normal Proposal distribution, for Metropolis steps;' 'Alternatives: Cauchy, Laplace, Poisson, MultivariateNormal') check_bnd = Bool.T( default=True, help='Flag for checking whether proposed step lies within' ' variable bounds.') rm_flag = Bool.T(default=False, help='Remove existing results prior to sampling.')