コード例 #1
0
class SatelliteMisfitResult(gf.Result, MisfitResult):
    """Carries the observations for a target and corresponding synthetics."""
    statics_syn = Dict.T(
        String.T(),
        Array.T(dtype=num.float, shape=(None,), serialize_as='base64'),
        optional=True,
        help='Predicted static displacements for a target (synthetics).')
    statics_obs = Dict.T(
        String.T(),
        Array.T(dtype=num.float, shape=(None,), serialize_as='base64'),
        optional=True,
        help='Observed static displacement for a target.')
コード例 #2
0
class CovarianceConfig(guts.Object):
    noise_coord = Array.T(
        shape=(None, ),
        dtype=num.float,
        serialize_as="list",
        optional=True,
        help="Noise patch coordinates and size,",
    )
    model_coefficients = guts.Tuple.T(
        optional=True,
        help="Covariance model coefficients. Either two (exponential) "
        "or three (exponential and cosine term) coefficients."
        "See also :func:`~kite.covariance.modelCovariance`.",
    )
    model_function = guts.StringChoice.T(
        choices=["exponential", "exponential_cosine"],
        default="exponential",
        help="Covariance approximation function.",
    )
    sampling_method = guts.StringChoice.T(
        choices=["spectral", "spatial"],
        default="spatial",
        help="Method for estimating the covariance and structure function.",
    )
    spatial_bins = guts.Int.T(
        default=75,
        help="Number of distance bins for spatial covariance sampling.")
    spatial_pairs = guts.Int.T(
        default=200000,
        help="Number of random pairs for spatial covariance sampling.")
    variance = guts.Float.T(optional=True, help="Variance of the model.")
    adaptive_subsampling = guts.Bool.T(
        default=True,
        help="Adaptive subsampling flag for full covariance calculation.")
    covariance_matrix = Array.T(
        dtype=num.float,
        optional=True,
        serialize_as="base64",
        help="Cached covariance matrix, "
        "see :attr:`~kite.Covariance.covariance_matrix`.",
    )

    def __init__(self, *args, **kwargs):
        if len(kwargs) != 0:
            if "a" in kwargs and "b" in kwargs:
                kwargs["model_coefficients"] = (kwargs.pop("a"),
                                                kwargs.pop("b"))
        guts.Object.__init__(self, *args, **kwargs)
コード例 #3
0
 class A(Object):
     xmltagname = 'aroot'
     arr = Array.T(
         shape=shape,
         dtype=num.int,
         serialize_as=serialize_as,
         serialize_dtype='>i8')
コード例 #4
0
class InjectionSamplerPhase(SamplerPhase):
    xs_inject = Array.T(dtype=num.float,
                        shape=(None, None),
                        help='Array with the reference model.')

    def get_raw_sample(self, problem, iiter, chains):
        return Sample(model=self.xs_inject[iiter, :])
コード例 #5
0
ファイル: automap.py プロジェクト: d-chambers/pyrocko
class FloatTile(Object):
    xmin = Float.T()
    ymin = Float.T()
    dx = Float.T()
    dy = Float.T()
    data = Array.T(shape=(None, None), dtype=num.float, serialize_as='table')

    def __init__(self, xmin, ymin, dx, dy, data):
        Object.__init__(self, init_props=False)
        self.xmin = float(xmin)
        self.ymin = float(ymin)
        self.dx = float(dx)
        self.dy = float(dy)
        self.data = data
        self._set_maxes()

    def _set_maxes(self):
        self.ny, self.nx = self.data.shape
        self.xmax = self.xmin + (self.nx-1) * self.dx
        self.ymax = self.ymin + (self.ny-1) * self.dy

    def x(self):
        return self.xmin + num.arange(self.nx) * self.dx

    def y(self):
        return self.ymin + num.arange(self.ny) * self.dy

    def get(self, x, y):
        ix = int(round((x - self.xmin) / self.dx))
        iy = int(round((y - self.ymin) / self.dy))
        if 0 <= ix < self.nx and 0 <= iy < self.ny:
            return self.data[iy, ix]
        else:
            raise OutOfBounds()
コード例 #6
0
class PoelSourceFunction(Object):
    data = Array.T(shape=(None, 2), dtype=num.float)

    def string_for_config(self):
        return '\n'.join([
            '%i %s' % (i+1, str_float_vals(row))
            for (i, row) in enumerate(self.data)])
コード例 #7
0
ファイル: targets.py プロジェクト: li8182/pyrocko
class SatelliteTarget(StaticTarget):
    '''
    A computation request for a spatial multi-location target of
    static/geodetic quantities measured from a satellite instrument.
    The line of sight angles are provided and projecting
    post-processing is applied.
    '''
    theta = Array.T(
        shape=(None,),
        dtype=num.float,
        serialize_as='base64-compat',
        help='Horizontal angle towards satellite\'s line of sight in radians.'
             '\n\n        .. important::\n\n'
             '            :math:`0` is **east** and'
             ' :math:`\\frac{\\pi}{2}` is **north**.\n\n')

    phi = Array.T(
        shape=(None,),
        dtype=num.float,
        serialize_as='base64-compat',
        help='Theta is look vector elevation angle towards satellite from'
             ' horizon in radians. Matrix of theta towards satellite\'s'
             ' line of sight.'
             '\n\n        .. important::\n\n'
             '            :math:`-\\frac{\\pi}{2}` is **down** and'
             ' :math:`\\frac{\\pi}{2}` is **up**.\n\n')

    def __init__(self, *args, **kwargs):
        super(SatelliteTarget, self).__init__(*args, **kwargs)
        self._los_factors = None

    def get_los_factors(self):
        if (self.theta.size != self.phi.size != self.lats.size):
            raise AttributeError('LOS angles inconsistent with provided'
                                 ' coordinate shape.')
        if self._los_factors is None:
            self._los_factors = num.empty((self.theta.shape[0], 3))
            self._los_factors[:, 0] = num.sin(self.theta)
            self._los_factors[:, 1] = num.cos(self.theta) * num.cos(self.phi)
            self._los_factors[:, 2] = num.cos(self.theta) * num.sin(self.phi)
        return self._los_factors

    def post_process(self, engine, source, statics):
        return meta.SatelliteResult(
            result=statics,
            theta=self.theta, phi=self.phi)
コード例 #8
0
class Boundary(Object):

    name1 = String.T()
    name2 = String.T()
    kind = String.T()
    points = Array.T(dtype=num.float, shape=(None, 2))
    cpoints = Array.T(dtype=num.float, shape=(None, 2))
    itypes = Array.T(dtype=num.int, shape=(None))

    def split_types(self, groups=None):
        xyz = od.latlon_to_xyz(self.points)
        xyzmid = (xyz[1:] + xyz[:-1, :]) * 0.5
        cxyz = od.latlon_to_xyz(self.cpoints)
        d = od.distances3d(xyzmid[num.newaxis, :, :], cxyz[:, num.newaxis, :])
        idmin = num.argmin(d, axis=0)
        itypes = self.itypes[idmin]

        if groups is None:
            groupmap = num.arange(len(self._index_to_type))
        else:
            d = {}
            for igroup, group in enumerate(groups):
                for name in group:
                    d[name] = igroup

            groupmap = num.array([d[name] for name in self._index_to_type],
                                 dtype=num.int)

        iswitch = num.concatenate(
            ([0],
             num.where(groupmap[itypes[1:]] != groupmap[itypes[:-1]])[0] + 1,
             [itypes.size]))

        results = []
        for ii in range(iswitch.size - 1):
            if groups is not None:
                tt = [
                    self._index_to_type[ityp]
                    for ityp in num.unique(itypes[iswitch[ii]:iswitch[ii + 1]])
                ]
            else:
                tt = self._index_to_type[itypes[iswitch[ii]]]

            results.append((tt, self.points[iswitch[ii]:iswitch[ii + 1] + 1]))

        return results
コード例 #9
0
ファイル: covariance.py プロジェクト: sheecegardezi/kite
class CovarianceConfig(guts.Object):
    noise_coord = Array.T(
        shape=(None,), dtype=num.float,
        serialize_as='list',
        optional=True,
        help='Noise patch coordinates and size,')
    model_coefficients = guts.Tuple.T(
        optional=True,
        help='Covariance model coefficients. Either two (exponential) '
             'or three (exponential and cosine term) coefficients.'
             'See also :func:`~kite.covariance.modelCovariance`.')
    model_function = guts.StringChoice.T(
        choices=['exponential', 'exponential_cosine'],
        default='exponential',
        help='Covariance approximation function.')
    sampling_method = guts.StringChoice.T(
        choices=['spectral', 'spatial'],
        default='spatial',
        help='Method for estimating the covariance and structure function.')
    spatial_bins = guts.Int.T(
        default=75,
        help='Number of distance bins for spatial covariance sampling.')
    spatial_pairs = guts.Int.T(
        default=200000,
        help='Number of random pairs for spatial covariance sampling.')
    variance = guts.Float.T(
        optional=True,
        help='Variance of the model.')
    adaptive_subsampling = guts.Bool.T(
        default=True,
        help='Adaptive subsampling flag for full covariance calculation.')
    covariance_matrix = Array.T(
        dtype=num.float,
        optional=True,
        serialize_as='base64',
        help='Cached covariance matrix, '
             'see :attr:`~kite.Covariance.covariance_matrix`.')

    def __init__(self, *args, **kwargs):
        if len(kwargs) != 0:
            if 'a' in kwargs and 'b' in kwargs:
                kwargs['model_coefficients'] = (
                    kwargs.pop('a'), kwargs.pop('b'))
        guts.Object.__init__(self, *args, **kwargs)
コード例 #10
0
class PoelModel(Object):
    data = Array.T(shape=(None, 6), dtype=num.float)

    def string_for_config(self):
        srows = []
        for i, row in enumerate(self.data):
            srows.append('%i %s' % (i+1, str_float_vals(row)))

        return '\n'.join(srows)

    def get_nlines(self):
        return self.data.shape[0]
コード例 #11
0
ファイル: covariance.py プロジェクト: mohseniaref/kite
class CovarianceConfig(guts.Object):
    noise_coord = Array.T(shape=(None, ),
                          dtype=num.float,
                          serialize_as='list',
                          optional=True,
                          help='Noise patch coordinates and size,')
    a = guts.Float.T(optional=True,
                     help='Exponential covariance model; scaling factor. '
                     'See :func:`~kite.covariance.modelCovariance`')
    b = guts.Float.T(optional=True,
                     help='Exponential covariance model; exponential decay. '
                     'See :func:`~kite.covariance.modelCovariance`')
    variance = guts.Float.T(optional=True, help='Variance of the model')
    adaptive_subsampling = guts.Bool.T(
        default=True,
        help='Adaptive subsampling flag for full covariance calculation.')
    covariance_matrix = Array.T(
        optional=True,
        serialize_as='base64',
        help='Cached covariance matrix, '
        'see :attr:`~kite.Covariance.covariance_matrix`',
    )
コード例 #12
0
class TraceSpectrum(Object):
    network = String.T()
    station = String.T()
    location = String.T()
    channel = String.T()
    deltaf = Float.T(default=1.0)
    fmin = Float.T(default=0.0)
    ydata = Array.T(shape=(None, ), dtype=num.complex, serialize_as='list')

    def get_ydata(self):
        return self.ydata

    def get_xdata(self):
        return self.fmin + num.arange(self.ydata.size) * self.deltaf
コード例 #13
0
class Plate(Object):

    name = String.T()
    points = Array.T(dtype=num.float, shape=(None, 2))

    def max_interpoint_distance(self):
        p = od.latlon_to_xyz(self.points)
        return math.sqrt(
            num.max(
                num.sum((p[num.newaxis, :, :] - p[:, num.newaxis, :])**2,
                        axis=2)))

    def contains_point(self, point):
        return od.contains_point(self.points, point)

    def contains_points(self, points):
        return od.contains_points(self.points, points)
コード例 #14
0
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
コード例 #15
0
class MisfitTarget(Object):

    manual_weight = Float.T(
        default=1.0,
        help='Relative weight of this target')
    analyser_results = Dict.T(
        gf.StringID.T(),
        AnalyserResult.T(),
        help='Dictionary of analyser results')
    normalisation_family = gf.StringID.T(
        optional=True,
        help='Normalisation family of this misfit target')
    path = gf.StringID.T(
        help='A path identifier used for plotting')
    misfit_config = MisfitConfig.T(
        default=MisfitConfig.D(),
        help='Misfit configuration')
    bootstrap_weights = Array.T(
        dtype=num.float,
        serialize_as='base64',
        optional=True)
    bootstrap_residuals = Array.T(
        dtype=num.float,
        serialize_as='base64',
        optional=True)

    can_bootstrap_weights = False
    can_bootstrap_residuals = False

    def __init__(self, **kwargs):
        Object.__init__(self, **kwargs)
        self.parameters = []

        self._ds = None
        self._result_mode = 'sparse'

        self._combined_weight = None
        self._target_parameters = None
        self._target_ranges = None

        self._combined_weight = None

    @classmethod
    def get_plot_classes(cls):
        return []

    def set_dataset(self, ds):
        self._ds = ds

    def get_dataset(self):
        return self._ds

    @property
    def nmisfits(self):
        return 1

    @property
    def nparameters(self):
        if self._target_parameters is None:
            return 0
        return len(self._target_parameters)

    @property
    def target_parameters(self):
        if self._target_parameters is None:
            self._target_parameters = copy.deepcopy(self.parameters)
            for p in self._target_parameters:
                p.set_groups([self.string_id()])
        return self._target_parameters

    @property
    def target_ranges(self):
        return {}

    def set_parameter_values(self, model):
        for i, p in enumerate(self.parameters):
            self.parameter_values[p.name_nogroups] = model[i]

    def set_result_mode(self, result_mode):
        self._result_mode = result_mode

    def post_process(self, engine, source, statics):
        raise NotImplementedError()

    def get_combined_weight(self):
        if self._combined_weight is None:
            self._combined_weight = num.ones(1, dtype=num.float)
        return self._combined_weight

    def set_bootstrap_weights(self, weights):
        self.bootstrap_weights = weights

    def get_bootstrap_weights(self):
        if self.bootstrap_weights is None:
            raise Exception('Bootstrap weights have not been set!')
        nbootstraps = self.bootstrap_weights.size // self.nmisfits
        return self.bootstrap_weights.reshape(nbootstraps, self.nmisfits)

    def init_bootstrap_residuals(self, nbootstrap, rstate=None):
        raise NotImplementedError

    def set_bootstrap_residuals(self, residuals):
        self.bootstrap_residuals = residuals

    def get_bootstrap_residuals(self):
        if self.bootstrap_residuals is None:
            raise Exception('Bootstrap residuals have not been set!')
        nbootstraps = self.bootstrap_residuals.size // self.nmisfits
        return self.bootstrap_residuals.reshape(nbootstraps, self.nmisfits)

    def prepare_modelling(self, engine, source, targets):
        return []

    def finalize_modelling(
            self, engine, source, modelling_targets, modelling_results):

        raise NotImplemented('must be overloaded in subclass')
コード例 #16
0
 class A(Object):
     arr = Array.T(serialize_as='base64+meta')
コード例 #17
0
 class A(Object):
     xmltagname = 'aroot'
     arr = Array.T(
         shape=(s0, s1),
         dtype=num.int)
コード例 #18
0
class MisfitResult(Object):
    misfits = Array.T(shape=(None, 2), dtype=num.float)
コード例 #19
0
    def testOptionalDefault(self):

        from pyrocko.guts_array import Array, array_equal
        import numpy as num
        assert_ae = num.testing.assert_almost_equal

        def array_equal_noneaware(a, b):
            if a is None:
                return b is None
            elif b is None:
                return a is None
            else:
                return array_equal(a, b)

        data = [
            ('a', Int.T(),
                [None, 0, 1, 2],
                ['aerr', 0, 1, 2]),
            ('b', Int.T(optional=True),
                [None, 0, 1, 2],
                [None, 0, 1, 2]),
            ('c', Int.T(default=1),
                [None, 0, 1, 2],
                [1, 0, 1, 2]),
            ('d', Int.T(default=1, optional=True),
                [None, 0, 1, 2],
                [1, 0, 1, 2]),
            ('e', List.T(Int.T()),
                [None, [], [1], [2]],
                [[], [], [1], [2]]),
            ('f', List.T(Int.T(), optional=True),
                [None, [], [1], [2]],
                [None, [], [1], [2]]),
            ('g', List.T(Int.T(), default=[1]), [
                None, [], [1], [2]],
                [[1], [], [1], [2]]),
            ('h', List.T(Int.T(), default=[1], optional=True),
                [None, [], [1], [2]],
                [[1], [], [1], [2]]),
            ('i', Tuple.T(2, Int.T()),
                [None, (1, 2)],
                ['err', (1, 2)]),
            ('j', Tuple.T(2, Int.T(), optional=True),
                [None, (1, 2)],
                [None, (1, 2)]),
            ('k', Tuple.T(2, Int.T(), default=(1, 2)),
                [None, (1, 2), (3, 4)],
                [(1, 2), (1, 2), (3, 4)]),
            ('l', Tuple.T(2, Int.T(), default=(1, 2), optional=True),
                [None, (1, 2), (3, 4)],
                [(1, 2), (1, 2), (3, 4)]),
            ('i2', Tuple.T(None, Int.T()),
                [None, (1, 2)],
                [(), (1, 2)]),
            ('j2', Tuple.T(None, Int.T(), optional=True),
                [None, (), (3, 4)],
                [None, (), (3, 4)]),
            ('k2', Tuple.T(None, Int.T(), default=(1,)),
                [None, (), (3, 4)],
                [(1,), (), (3, 4)]),
            ('l2', Tuple.T(None, Int.T(), default=(1,), optional=True),
                [None, (), (3, 4)],
                [(1,), (), (3, 4)]),
            ('m', Array.T(shape=(None,), dtype=num.int, serialize_as='list'),
                [num.arange(0), num.arange(2)],
                [num.arange(0), num.arange(2)]),
            ('n', Array.T(shape=(None,), dtype=num.int, serialize_as='list',
                          optional=True),
                [None, num.arange(0), num.arange(2)],
                [None, num.arange(0), num.arange(2)]),
            ('o', Array.T(shape=(None,), dtype=num.int, serialize_as='list',
                          default=num.arange(2)),
                [None, num.arange(0), num.arange(2), num.arange(3)],
                [num.arange(2), num.arange(0), num.arange(2), num.arange(3)]),
            ('p', Array.T(shape=(None,), dtype=num.int, serialize_as='list',
                          default=num.arange(2), optional=True),
                [None, num.arange(0), num.arange(2), num.arange(3)],
                [num.arange(2), num.arange(0), num.arange(2), num.arange(3)]),
            ('q', Dict.T(String.T(), Int.T()),
                [None, {}, {'a': 1}],
                [{}, {}, {'a': 1}]),
            ('r', Dict.T(String.T(), Int.T(), optional=True),
                [None, {}, {'a': 1}],
                [None, {}, {'a': 1}]),
            ('s', Dict.T(String.T(), Int.T(), default={'a': 1}),
                [None, {}, {'a': 1}],
                [{'a': 1}, {}, {'a': 1}]),
            ('t', Dict.T(String.T(), Int.T(), default={'a': 1}, optional=True),
                [None, {}, {'a': 1}],
                [{'a': 1}, {}, {'a': 1}]),
        ]

        for k, t, vals, exp, in data:
            last = [None]

            class A(Object):
                def __init__(self, **kwargs):
                    last[0] = len(kwargs)
                    Object.__init__(self, **kwargs)

                v = t

            A.T.class_signature()

            for v, e in zip(vals, exp):
                if isinstance(e, str) and e == 'aerr':
                    with self.assertRaises(ArgumentError):
                        if v is not None:
                            a1 = A(v=v)
                        else:
                            a1 = A()

                    continue
                else:
                    if v is not None:
                        a1 = A(v=v)
                    else:
                        a1 = A()

                if isinstance(e, str) and e == 'err':
                    with self.assertRaises(ValidationError):
                        a1.validate()
                else:
                    a1.validate()
                    a2 = load_string(dump(a1))
                    if isinstance(e, num.ndarray):
                        assert last[0] == int(
                            not (array_equal_noneaware(t.default(), a1.v)
                                 and t.optional))
                        assert_ae(a1.v, e)
                        assert_ae(a1.v, e)
                    else:
                        assert last[0] == int(
                            not(t.default() == a1.v and t.optional))
                        self.assertEqual(a1.v, e)
                        self.assertEqual(a2.v, e)
コード例 #20
0
class MisfitTarget(Object):

    manual_weight = Float.T(default=1.0, help='Relative weight of this target')
    analyser_results = Dict.T(gf.StringID.T(),
                              AnalyserResult.T(),
                              help='Dictionary of analyser results')
    normalisation_family = gf.StringID.T(
        optional=True, help='Normalisation family of this misfit target')
    path = gf.StringID.T(help='A path identifier used for plotting')
    misfit_config = MisfitConfig.T(default=MisfitConfig.D(),
                                   help='Misfit configuration')
    bootstrap_weights = Array.T(dtype=num.float,
                                serialize_as='base64',
                                optional=True)
    bootstrap_residuals = Array.T(dtype=num.float,
                                  serialize_as='base64',
                                  optional=True)

    can_bootstrap_weights = False
    can_bootstrap_residuals = False

    plot_misfits_cumulative = True

    def __init__(self, **kwargs):
        Object.__init__(self, **kwargs)
        self.parameters = []

        self._ds = None
        self._result_mode = 'sparse'

        self._combined_weight = None
        self._target_parameters = None
        self._target_ranges = None

        self._combined_weight = None

    @classmethod
    def get_plot_classes(cls):
        return []

    def set_dataset(self, ds):
        self._ds = ds

    def get_dataset(self):
        return self._ds

    def string_id(self):
        return str(self.path)

    def misfits_string_ids(self):
        raise NotImplementedError('%s does not implement misfits_string_id' %
                                  self.__class__.__name__)

    @property
    def nmisfits(self):
        return 1

    def noise_weight_matrix(self):
        return num.array([[1]])

    @property
    def nparameters(self):
        if self._target_parameters is None:
            return 0
        return len(self._target_parameters)

    @property
    def target_parameters(self):
        if self._target_parameters is None:
            self._target_parameters = copy.deepcopy(self.parameters)
            for p in self._target_parameters:
                p.set_groups([self.string_id()])
        return self._target_parameters

    @property
    def target_ranges(self):
        return {}

    def set_parameter_values(self, model):
        for i, p in enumerate(self.parameters):
            self.parameter_values[p.name_nogroups] = model[i]

    def set_result_mode(self, result_mode):
        self._result_mode = result_mode

    def post_process(self, engine, source, statics):
        raise NotImplementedError()

    def get_combined_weight(self):
        if self._combined_weight is None:
            w = self.manual_weight
            for analyser in self.analyser_results.values():
                w *= analyser.weight
            self._combined_weight = num.array([w], dtype=num.float)

        return self._combined_weight

    def get_correlated_weights(self, nthreads=0):
        pass

    def set_bootstrap_weights(self, weights):
        self.bootstrap_weights = weights

    def get_bootstrap_weights(self):
        if self.bootstrap_weights is None:
            raise Exception('Bootstrap weights have not been set!')
        nbootstraps = self.bootstrap_weights.size // self.nmisfits
        return self.bootstrap_weights.reshape(nbootstraps, self.nmisfits)

    def init_bootstrap_residuals(self, nbootstrap, rstate=None, nthreads=0):
        raise NotImplementedError()

    def set_bootstrap_residuals(self, residuals):
        self.bootstrap_residuals = residuals

    def get_bootstrap_residuals(self):
        if self.bootstrap_residuals is None:
            raise Exception('Bootstrap residuals have not been set!')
        nbootstraps = self.bootstrap_residuals.size // self.nmisfits
        return self.bootstrap_residuals.reshape(nbootstraps, self.nmisfits)

    def prepare_modelling(self, engine, source, targets):
        ''' Prepare modelling target

        This function shall return a list of :class:`pyrocko.gf.Target`
        for forward modelling in the :class:`pyrocko.gf.LocalEngine`.
        '''
        return [self]

    def finalize_modelling(self, engine, source, modelling_targets,
                           modelling_results):
        ''' Manipulate modelling before misfit calculation

        This function can be overloaded interact with the modelling results.
        '''
        return modelling_results[0]
コード例 #21
0
class PoelConfigFull(PoelConfig):
    s_start_depth = Float.T(default=25.0)
    s_end_depth = Float.T(default=25.0)

    sw_equidistant_z = Int.T(default=1)
    no_depths = Int.T(default=10)
    depths = Array.T(
        shape=(None,),
        dtype=num.float,
        default=num.array([10.0, 100.0], dtype=num.float))
    sw_equidistant_x = Int.T(default=1)
    no_distances = Int.T(default=10)
    distances = Array.T(
        shape=(None,),
        dtype=num.float,
        default=num.array([10., 100.]))

    no_t_samples = Int.T(default=51)
    t_files = List.T(String.T(), default=[x+'.t' for x in poel_components])
    sw_t_files = List.T(Int.T(), default=[1 for x in poel_components])

    def get_output_filenames(self, rundir):
        return [pjoin(rundir, fn) for fn in self.t_files]

    def string_for_config(self):

        d = self.__dict__.copy()

        if not self.sw_equidistant_x:
            d['no_distances'] = len(self.distances)
        d['str_distances'] = str_float_vals(self.distances)

        if not self.sw_equidistant_z:
            d['no_depths'] = len(self.depths)
        d['str_depths'] = str_float_vals(self.depths)

        d['sw_t_files_1_2'] = ' '.join(
            ['%i' % i for i in self.sw_t_files[0:2]])
        d['t_files_1_2'] = ' '.join(
            ["'%s'" % s for s in self.t_files[0:2]])
        d['sw_t_files_3_7'] = ' '.join(
            ['%i' % i for i in self.sw_t_files[2:7]])
        d['t_files_3_7'] = ' '.join(
            ["'%s'" % s for s in self.t_files[2:7]])
        d['sw_t_files_8_10'] = ' '.join(
            ['%i' % i for i in self.sw_t_files[7:10]])
        d['t_files_8_10'] = ' '.join(
            ["'%s'" % s for s in self.t_files[7:10]])

        d['no_model_lines'] = self.model.get_nlines()

        if self.s_type == 0:
            d['source_function'] = str(self.source_function_p)
        elif self.s_type == 1:
            d['source_function'] = self.source_function_i.string_for_config()

        d['model'] = self.model.string_for_config()

        template = '''
# This is the input file of FORTRAN77 program "poel06" for modeling
# coupled deformation-diffusion processes based on a multi-layered (half-
# or full-space) poroelastic media induced by an injection (pump) of
# from a borehole or by a (point) reservoir loading.
#
# by R. Wang,
# GeoForschungsZentrum Potsdam
# e-mail: [email protected]
# phone 0049 331 2881209
# fax 0049 331 2881204
#
# Last modified: Potsdam, July, 2012
#
##############################################################
##                                                          ##
## Cylindrical coordinates (Z positive downwards!) are used ##
## If not others specified, SI Unit System is used overall! ##
##                                                          ##
## Tilt is positive when the upper end of a borehole tilt-  ##
## meter body moves away from the pumping well.             ##
##                                                          ##
##############################################################
#
###############################################################################
#
#   SOURCE PARAMETERS A: SOURCE GEOMETRY
#   ====================================
# 1. source top and bottom depth [m]
#    Note: top depth < bottom depth for a vertical line source
#          top depth = bottom depth for a vertical point source
#
#        !  whole source screen should be within a homogeneous layer, and  !
#        !  both top and bottom should not coincide with any interface of  !
#        !  the model used (see below)                                     !
#
# 2. source radius (> 0) [m]
#    Note: source radius > 0 for a horizontal disk source
#          source radius = 0 for a horizontal point source
#------------------------------------------------------------------------------
  %(s_start_depth)g %(s_end_depth)g             |dble: s_top_depth, s_bottom_de
  %(s_radius)g                                  |dble: s_radius;
#------------------------------------------------------------------------------
#
#   SOURCE PARAMETERS B: SOURCE TYPE
#   ================================
# 1. selection of source type:
#    0 = initial excess pore pressure within the source volume
#        (initial value problem)
#    1 = injection within the source volume
#        (boundary value problem)
#------------------------------------------------------------------------------
   %(s_type)i                                   |int: sw_source_type;
#------------------------------------------------------------------------------
   %(source_function)s
###############################################################################
#
#   RECEIVER PARAMETERS A: RECEIVER DEPTH SAMPLING
#   ==============================================
# 1. switch for equidistant steping (1/0 = yes/no)
# 2. number of receiver depth samples (<= nzrmax defined in "peglobal.h")
# 3. if equidistant, start depth [m], end depth [m]; else list of depths
#    (all >= 0 and ordered from small to large!)
#------------------------------------------------------------------------------
   %(sw_equidistant_z)i                         |int: sw_receiver_depth_samplin
   %(no_depths)i                                |int: no_depths;
   %(str_depths)s                               |dble: zr_1,zr_n; or zr_1,zr_2,
#------------------------------------------------------------------------------
#
#   RECEIVER PARAMETERS B: RECEIVER DISTANCE SAMPLING
#   =================================================
# 1. switch for equidistant steping (1/0 = yes/no)
# 2. number of receiver distance samples (<= nrmax defined in "peglobal.h")
# 3. if equidistant, start distance [m], end distance [m]; else list of
#    distances (all >= 0 and ordered from small to large!)
#------------------------------------------------------------------------------
   %(sw_equidistant_x)i                         |int: sw_equidistant;
   %(no_distances)i                             |int: no_distances;
   %(str_distances)s                            |dble: d_1,d_n; or d_1,d_2, ...
#------------------------------------------------------------------------------
#
#   RECEIVER PARAMETERS C: Time SAMPLING
#   ====================================
# 1. time window [s]
# 2. number of time samples
#    Note: the caracteristic diffusion time =
#          max_receiver_distance^2 / diffusivity_of_source_layer
#------------------------------------------------------------------------------
   %(t_window)s                                 |dble: time_window;
   %(no_t_samples)i                             |int: no_time_samples;
#------------------------------------------------------------------------------
#
#   WAVENUMBER INTEGRATION PARAMETERS
#   =================================
# 1. relative accuracy (0.01 for 1%% error) for numerical wavenumber integratio
#------------------------------------------------------------------------------
   %(accuracy)s                                 |dble: accuracy;
#------------------------------------------------------------------------------
###############################################################################
#
#   OUTPUTS A: DISPLACEMENT TIME SERIES
#   ===================================
# 1. select the 2 displacement time series (1/0 = yes/no)
#    Note Ut = 0
# 2. file names of these 2 time series
#------------------------------------------------------------------------------
   %(sw_t_files_1_2)s                           |int: sw_t_files(1-2);
   %(t_files_1_2)s                              |char: t_files(1-2);
#------------------------------------------------------------------------------
#
#   OUTPUTS B: STRAIN TENSOR & TILT TIME SERIES
#   ===========================================
# 1. select strain time series (1/0 = yes/no): Ezz, Err, Ett, Ezr (4 tensor
#    components) and Tlt (= -dur/dz, the radial component of the vertical tilt)
#    Note Ezt, Ert and Tlt (tangential tilt) = 0
# 2. file names of these 5 time series
#------------------------------------------------------------------------------
   %(sw_t_files_3_7)s                           |int: sw_t_files(3-7);
   %(t_files_3_7)s                              |char: t_files(3-7);
#------------------------------------------------------------------------------
#
#   OUTPUTS C: PORE PRESSURE & DARCY VELOCITY TIME SERIES
#   =====================================================
# 1. select pore pressure and Darcy velocity time series (1/0 = yes/no):
#    Pp (excess pore pressure), Dvz, Dvr (2 Darcy velocity components)
#    Note Dvt = 0
# 2. file names of these 3 time series
#------------------------------------------------------------------------------
   %(sw_t_files_8_10)s                          |int: sw_t_files(8-10);
   %(t_files_8_10)s                             |char: t_files(8-10);
#------------------------------------------------------------------------------
#
#   OUTPUTS D: SNAPSHOTS OF ALL OBSERVABLES
#   =======================================
# 1. number of snapshots
# 2. time[s] (within the time window, see above) and output filename of
#    the 1. snapshot
# 3. ...
#------------------------------------------------------------------------------
 1                                              |int: no_sn;
   %(t_window)s    'snapshot.dat'               |dable: sn_time(i),sn_file(i)
###############################################################################
#
#   GLOBAL MODEL PARAMETERS
#   =======================
# 1. switch for surface conditions:
#    0 = without free surface (whole space),
#    1 = unconfined free surface (p = 0),
#    2 = confined free surface (dp/dz = 0).
# 2. number of data lines of the layered model (<= lmax as defined in
#    "peglobal.h") (see Note below)
#------------------------------------------------------------------------------
   %(isurfcon)i                                   |int: isurfcon
   %(no_model_lines)i                             |int: no_model_lines;
#------------------------------------------------------------------------------
#
#   MULTILAYERED MODEL PARAMETERS
#   =============================
#
#   Note: mu = shear modulus
#         nu = Poisson ratio under drained condition
#         nu_u = Poisson ratio under undrained condition (nu_u > nu)
#         B = Skempton parameter (the change in pore pressure per unit change
#             in confining pressure under undrained condition)
#         D = hydraulic diffusivity
#
# no depth[m] mu[Pa]    nu    nu_u   B     D[m^2/s]   Explanations
#------------------------------------------------------------------------------
   %(model)s
###########################end of all inputs###################################

Note for the model input format and the step-function approximation for model
parameters varying linearly with depth:

The surface and the upper boundary of the lowest half-space as well as the
interfaces at which the poroelastic parameters are continuous, are all defined
by a single data line; All other interfaces, at which the poroelastic
parameters are discontinuous, are all defined by two data lines (upper-side and
lower-side values). This input format would also be needed for a graphic plot
of the layered model. Layers which have different parameter values at top and
bottom, will be treated as layers with a constant gradient, and will be
discretised to a number of homogeneous sublayers. Errors due to the
discretisation are limited within about 5%% (changeable, see peglobal.h).
'''.lstrip()

        return template % d
コード例 #22
0
class VelocityProfile(Object):
    uid = Int.T(optional=True, help='Unique ID of measurement')

    lat = Float.T(help='Latitude [deg]')
    lon = Float.T(help='Longitude [deg]')
    elevation = Float.T(default=num.nan, help='Elevation [m]')
    vp = Array.T(shape=(None, 1), help='P Wave velocities [m/s]')
    vs = Array.T(shape=(None, 1), help='S Wave velocities [m/s]')
    d = Array.T(shape=(None, 1), help='Interface depth, top [m]')
    h = Array.T(shape=(None, 1), help='Interface thickness [m]')

    heatflow = Float.T(optional=True, help='Heatflow [W/m^2]')
    geographical_location = String.T(optional=True, help='Geographic Location')
    geological_province = String.T(optional=True, help='Geological Province')
    geological_age = String.T(optional=True, help='Geological Age')
    measurement_method = Int.T(optional=True, help='Measurement method')
    publication_reference = String.T(optional=True,
                                     help='Publication Reference')
    publication_year__ = Int.T(help='Publication Date')

    def __init__(self, *args, **kwargs):
        Object.__init__(self, *args, **kwargs)

        self.h = num.abs(self.d - num.roll(self.d, -1))
        self.h[-1] = 0
        self.nlayers = self.h.size

        self.geographical_location = '%s (%s)' % (provinceKey(
            self.geographical_location), self.geographical_location)

        self.vs[self.vs == 0] = num.nan
        self.vp[self.vp == 0] = num.nan

        self._step_vp = num.repeat(self.vp, 2)
        self._step_vs = num.repeat(self.vs, 2)
        self._step_d = num.roll(num.repeat(self.d, 2), -1)
        self._step_d[-1] = self._step_d[-2] + THICKNESS_HALFSPACE

    @property
    def publication_year__(self):
        return pubYear(self.publication_reference)

    def interpolateProfile(self, depths, phase='p', stepped=True):
        '''Get a continuous velocity function at arbitrary depth

        :param depth: Depths to interpolate
        :type depth: :class:`numpy.ndarray`
        :param phase: P or S wave velocity, **p** or **s**
        :type phase: str, optional
        :param stepped: Use a stepped velocity function or gradient
        :type stepped: bool
        :returns: velocities at requested depths
        :rtype: :class:`numpy.ndarray`
        '''

        if phase not in ['s', 'p']:
            raise AttributeError('Phase has to be either \'p\' or \'s\'.')

        if phase == 'p':
            vel = self._step_vp if stepped else self.vp
        elif phase == 's':
            vel = self._step_vs if stepped else self.vs
        d = self._step_d if stepped else self.d

        if vel.size == 0:
            raise ProfileEmpty('Phase %s does not contain velocities' % phase)

        try:
            res = num.interp(depths, d, vel, left=num.nan, right=num.nan)
        except ValueError:
            raise ValueError('Could not interpolate velocity profile.')

        return res

    def plot(self, axes=None):
        ''' Plot the velocity profile, see :class:`pyrocko.cake`.

        :param axes: Axes to plot into.
        :type axes: :class:`matplotlib.Axes`'''

        import matplotlib.pyplot as plt

        fig, ax = _getCanvas(axes)
        my_model_plot(self.getLayeredModel(), axes=axes)
        ax.set_title('Global Crustal Database\n'
                     'Velocity Structure at {p.lat:.4f}N, '
                     ' {p.lat:.4f}E (uid {p.uid})'.format(p=self))
        if axes is None:
            plt.show()

    def getLayeredModel(self):
        ''' Get a layered model, see :class:`pyrocko.cake.LayeredModel`. '''
        def iterLines():
            for il, m in enumerate(self.iterLayers()):
                yield self.d[il], m, ''

        return LayeredModel.from_scanlines(iterLines())

    def iterLayers(self):
        ''' Iterator returns a :class:`pyrocko.cake.Material` for each layer'''
        for il in range(self.nlayers):
            yield Material(vp=self.vp[il], vs=self.vs[il])

    @property
    def geog_loc_long(self):
        return provinceKey(self.geog_loc)

    @property
    def geol_age_long(self):
        return ageKey(self.geol_age)

    @property
    def has_s(self):
        return num.any(self.vp)

    @property
    def has_p(self):
        return num.any(self.vs)

    def get_weeded(self):
        ''' Get weeded representation of layers used in the profile.
        See :func:`pyrocko.cake.get_weeded` for details.
        '''
        weeded = num.zeros((self.nlayers, 4))
        weeded[:, 0] = self.d
        weeded[:, 1] = self.vp
        weeded[:, 2] = self.vs

    def _csv(self):
        output = ''
        for d in range(len(self.h)):
            output += (
                '{p.uid}, {p.lat}, {p.lon},'
                ' {vp}, {vs}, {h}, {d}, {p.publication_reference}\n').format(
                    p=self,
                    vp=self.vp[d],
                    vs=self.vs[d],
                    h=self.h[d],
                    d=self.d[d])
        return output