Beispiel #1
0
    def test_material(self):
        mat = cake.Material(poisson=0.20, rho=3000., qp=100.)
        mat1 = cake.Material(vp=mat.vp,
                             poisson=mat.poisson(),
                             rho=mat.rho,
                             qp=mat.qp)
        mat2 = cake.Material(vp=mat.vp, vs=mat1.vs, rho=mat1.rho, qs=mat1.qs)
        mat3 = cake.Material(lame=mat2.lame(),
                             rho=mat2.rho,
                             qp=mat2.qp,
                             qs=mat2.qs)
        mat4 = cake.Material(vs=mat3.vs,
                             poisson=mat3.poisson(),
                             rho=mat3.rho,
                             qk=mat3.qk(),
                             qmu=mat3.qmu())

        mat5 = eval('cake.' + repr(mat))

        for matx in (mat1, mat2, mat3, mat4, mat5):
            self.assertEqual(mat.vp, matx.vp)
            self.assertEqual(mat.vs, matx.vs)
            self.assertEqual(mat.rho, matx.rho)
            self.assertEqual(mat.qp, matx.qp)
            self.assertEqual(mat.qs, matx.qs)
            self.assertEqual(mat.describe(), matx.describe())
Beispiel #2
0
    def test_copy(self):
        m1 = cake.Material(vp=1., vs=1.)
        m2 = cake.Material(vp=4., vs=4.)

        s = cake.Surface(0., m1)
        self.assertEqual(s.__dict__, s.copy().__dict__)

        i = cake.Interface(1., m1, m2, name='a')
        self.assertEqual(i.__dict__, i.copy().__dict__)
Beispiel #3
0
    def test_layer_resize(self):
        depth_min_init = 0.
        depth_max_init = 3.
        m1 = cake.Material(vp=1., vs=1.)
        m2 = cake.Material(vp=4., vs=4.)

        tests = [
            (cake.HomogeneousLayer, 1., None, 2., m1, m1),
            (cake.HomogeneousLayer, None, 2., 1., m1, m1),
            (cake.HomogeneousLayer, 1., 2., 1.5, m1, m1),
            (cake.GradientLayer, 1., None, 2., cake.Material(2., 2.), m2),
            (cake.GradientLayer, None, 2., 1., m1, cake.Material(3., 3.)),
            (cake.GradientLayer, 1., 2., 1.5,
                cake.Material(2., 2.,), cake.Material(3., 3.)),
            (cake.GradientLayer, None, 4., 2., m1, cake.Material(5., 5.)),
        ]

        for t in tests:
            cls, depth_min, depth_max, depth_mid, nmtop, nmbot = t
            if cls == cake.HomogeneousLayer:
                layer = cls(ztop=depth_min_init, zbot=depth_max_init, m=m1)
            if cls == cake.GradientLayer:
                layer = cls(ztop=depth_min_init, zbot=depth_max_init,
                            mtop=m1, mbot=m2)
            depth_min = depth_min or depth_min_init
            depth_max = depth_max or depth_max_init

            layer.resize(depth_min=depth_min, depth_max=depth_max)
            self.assertEqual(layer.ztop, depth_min)
            self.assertEqual(layer.zbot, depth_max)
            self.assertEqual(layer.zmid, num.mean((depth_min, depth_max)))

            self.assertEqual(layer.mtop, nmtop)
            self.assertEqual(layer.mbot, nmbot)
Beispiel #4
0
def example_model():
    material = cake.Material(vp=3000., vs=1000., rho=3000., qp=200., qs=100.)
    layer = cake.HomogeneousLayer(ztop=0.,
                                  zbot=30 * km,
                                  m=material,
                                  name='fullspace')
    mod = cake.LayeredModel()
    mod.append(layer)
    return mod
Beispiel #5
0
def optparse(required=(),
             optional=(),
             args=sys.argv,
             usage='%prog [options]',
             descr=None):

    want = required + optional

    parser = OptionParser(prog='cake',
                          usage=usage,
                          description=descr.capitalize() + '.',
                          add_help_option=False,
                          formatter=util.BetterHelpFormatter())

    parser.add_option('-h',
                      '--help',
                      action='help',
                      help='Show help message and exit.')

    if 'phases' in want:
        group = OptionGroup(
            parser, 'Phases', '''

Seismic phase arrivals may be either specified as traditional phase names (e.g.
P, S, PP, PcP, ...) or in Cake's own syntax which is more powerful.  Use the
--classic option, for traditional phase names. Use the --phase option if you
want to define phases in Cake's syntax.

''')
        group.add_option(
            '--phase',
            '--phases',
            dest='phases',
            action="append",
            default=[],
            metavar='PHASE1,PHASE2,...',
            help='''Comma separated list of seismic phases in Cake\'s syntax.

The definition of a seismic propagation path in Cake's phase syntax is a string
consisting of an alternating sequence of "legs" and "knees".

A "leg" represents seismic wave propagation without any conversions,
encountering only super-critical reflections. Legs are denoted by "P", "p",
"S", or "s". The capital letters are used when the take-off of the "leg" is
in downward direction, while the lower case letters indicate a take-off in
upward direction.

A "knee" is an interaction with an interface. It can be a mode conversion, a
reflection, or propagation as a headwave or diffracted wave.

   * conversion is simply denoted as: "(INTERFACE)" or "DEPTH"
   * upperside reflection: "v(INTERFACE)" or "vDEPTH"
   * underside reflection: "^(INTERFACE)" or "^DEPTH"
   * normal kind headwave or diffracted wave: "v_(INTERFACE)" or "v_DEPTH"

The interface may be given by name or by depth: INTERFACE is the name of an
interface defined in the model, DEPTH is the depth of an interface in [km] (the
interface closest to that depth is chosen).  If two legs appear consecutively
without an explicit "knee", surface interaction is assumed.

The preferred standard interface names in cake are "conrad", "moho", "cmb"
(core-mantle boundary), and "cb" (inner core boundary).

The phase definition may end with a backslash "\\", to indicate that the ray
should arrive at the receiver from above instead of from below. It is possible
to restrict the maximum and minimum depth of a "leg" by appending
"<(INTERFACE)" or "<DEPTH" or ">(INTERFACE)" or ">DEPTH" after the leg
character, respectively.

When plotting rays or travel-time curves, the color can be set by appending
"{COLOR}" to the phase definition, where COLOR is the name of a color or an RGB
or RGBA color tuple in the format "R/G/B" or "R/G/B/A", respectively. The
values can be normalized to the range [0, 1] or to [0, 255]. The latter is only
assumed when any of the values given exceeds 1.0.
''')

        group.add_option(
            '--classic',
            dest='classic_phases',
            action='append',
            default=[],
            metavar='PHASE1,PHASE2,...',
            help='''Comma separated list of seismic phases in classic
nomenclature. Run "cake list-phase-map" for a list of available
phase names. When plotting, color can be specified in the same way
as in --phases.''')

        parser.add_option_group(group)

    if 'model' in want:
        group = OptionGroup(parser, 'Model')
        group.add_option(
            '--model',
            dest='model_filename',
            metavar='(NAME or FILENAME)',
            help='Use builtin model named NAME or user model from file '
            'FILENAME. By default, the "ak135-f-continental.m" model is '
            'used. Run "cake list-models" for a list of builtin models.')

        group.add_option(
            '--format',
            dest='model_format',
            metavar='FORMAT',
            choices=['nd', 'hyposat'],
            default='nd',
            help='Set model file format (available: nd, hyposat; default: '
            'nd).')
        group.add_option(
            '--crust2loc',
            dest='crust2loc',
            metavar='LAT,LON',
            help='Set model from CRUST2.0 profile at location (LAT,LON).')
        group.add_option(
            '--crust2profile',
            dest='crust2profile',
            metavar='KEY',
            help='Set model from CRUST2.0 profile with given KEY.')

        parser.add_option_group(group)

    if any(x in want
           for x in ('zstart', 'zstop', 'distances', 'sloc', 'rloc')):

        group = OptionGroup(parser, 'Source-receiver geometry')
        if 'zstart' in want:
            group.add_option('--sdepth',
                             dest='sdepth',
                             type='float',
                             default=0.0,
                             metavar='FLOAT',
                             help='Source depth [km] (default: 0)')
        if 'zstop' in want:
            group.add_option('--rdepth',
                             dest='rdepth',
                             type='float',
                             default=0.0,
                             metavar='FLOAT',
                             help='Receiver depth [km] (default: 0)')
        if 'distances' in want:
            group.add_option('--distances',
                             dest='sdist',
                             metavar='DISTANCES',
                             help='Surface distances as "start:stop:n" or '
                             '"dist1,dist2,..." [km]')
            group.add_option('--sloc',
                             dest='sloc',
                             metavar='LAT,LON',
                             help='Source location (LAT,LON).')
            group.add_option('--rloc',
                             dest='rloc',
                             metavar='LAT,LON',
                             help='Receiver location (LAT,LON).')
        parser.add_option_group(group)

    if 'material' in want:
        group = OptionGroup(
            parser, 'Material',
            'An isotropic elastic material may be specified by giving '
            'a combination of some of the following options. ')
        group.add_option('--vp',
                         dest='vp',
                         default=None,
                         type='float',
                         metavar='FLOAT',
                         help='P-wave velocity [km/s]')
        group.add_option('--vs',
                         dest='vs',
                         default=None,
                         type='float',
                         metavar='FLOAT',
                         help='S-wave velocity [km/s]')
        group.add_option('--rho',
                         dest='rho',
                         default=None,
                         type='float',
                         metavar='FLOAT',
                         help='density [g/cm**3]')
        group.add_option('--qp',
                         dest='qp',
                         default=None,
                         type='float',
                         metavar='FLOAT',
                         help='P-wave attenuation Qp (default: 1456)')
        group.add_option('--qs',
                         dest='qs',
                         default=None,
                         type='float',
                         metavar='FLOAT',
                         help='S-wave attenuation Qs (default: 600)')
        group.add_option('--poisson',
                         dest='poisson',
                         default=None,
                         type='float',
                         metavar='FLOAT',
                         help='Poisson ratio')
        group.add_option('--lambda',
                         dest='lame_lambda',
                         default=None,
                         type='float',
                         metavar='FLOAT',
                         help='Lame parameter lambda [GPa]')
        group.add_option('--mu',
                         dest='lame_mu',
                         default=None,
                         type='float',
                         metavar='FLOAT',
                         help='Shear modulus [GPa]')
        group.add_option('--qk',
                         dest='qk',
                         default=None,
                         type='float',
                         metavar='FLOAT',
                         help='Bulk attenuation Qk')
        group.add_option('--qmu',
                         dest='qmu',
                         default=None,
                         type='float',
                         metavar='FLOAT',
                         help='Shear attenuation Qmu')
        parser.add_option_group(group)

    if any(x in want for x in ('vred', 'as_degrees', 'accuracy', 'slowness',
                               'interface', 'aspect', 'shade_model')):

        group = OptionGroup(parser, 'General')
        if 'vred' in want:
            group.add_option('--vred',
                             dest='vred',
                             type='float',
                             metavar='FLOAT',
                             help='Velocity for time reduction in plot [km/s]')

        if 'as_degrees' in want:
            group.add_option(
                '--degrees',
                dest='as_degrees',
                action='store_true',
                default=False,
                help='Distances are in [deg] instead of [km], velocities in '
                '[deg/s] instead of [km/s], slownesses in [s/deg] '
                'instead of [s/km].')

        if 'accuracy' in want:
            group.add_option('--accuracy',
                             dest='accuracy',
                             type='float',
                             metavar='MAXIMUM_RELATIVE_RMS',
                             default=0.002,
                             help='Set accuracy for model simplification.')

        if 'slowness' in want:
            group.add_option(
                '--slowness',
                dest='slowness',
                type='float',
                metavar='FLOAT',
                default=0.0,
                help='Select surface slowness [s/km] (default: 0)')

        if 'interface' in want:
            group.add_option('--interface',
                             dest='interface',
                             metavar='(NAME or DEPTH)',
                             help='Name or depth [km] of interface to select')

        if 'aspect' in want:
            group.add_option('--aspect',
                             dest='aspect',
                             type='float',
                             metavar='FLOAT',
                             help='Aspect ratio for plot')

        if 'shade_model' in want:
            group.add_option('--no-shade-model',
                             dest='shade_model',
                             action='store_false',
                             default=True,
                             help='Suppress shading of earth model layers')

        parser.add_option_group(group)

    if any(x in want for x in ('output_format', )):
        group = OptionGroup(parser, 'Output')
        if 'output_format' in want:
            group.add_option(
                '--output-format',
                dest='output_format',
                metavar='FORMAT',
                default='textual',
                choices=('textual', 'nd'),
                help='Set model output format (available: textual, nd, '
                'default: textual)')

        parser.add_option_group(group)

    if usage == 'cake help-options':
        parser.print_help()

    (options, args) = parser.parse_args(args)

    if len(args) != 2:
        parser.error(
            'Cake arguments should look like "--option" or "--option=...".')

    d = {}
    as_degrees = False
    if 'as_degrees' in want:
        as_degrees = options.as_degrees
        d['as_degrees'] = as_degrees

    if 'accuracy' in want:
        d['accuracy'] = options.accuracy

    if 'output_format' in want:
        d['output_format'] = options.output_format

    if 'aspect' in want:
        d['aspect'] = options.aspect

    if 'shade_model' in want:
        d['shade_model'] = options.shade_model

    if 'phases' in want:
        phases = []
        phase_colors = {}
        try:
            for ss in options.phases:
                for s in ss.split(','):
                    s = process_color(s, phase_colors)
                    phases.append(cake.PhaseDef(s))

            for pp in options.classic_phases:
                for p in pp.split(','):
                    p = process_color(p, phase_colors)
                    phases.extend(cake.PhaseDef.classic(p))

        except (cake.PhaseDefParseError, cake.UnknownClassicPhase) as e:
            parser.error(e)

        if not phases and 'phases' in required:
            s = process_color('P', phase_colors)
            phases.append(cake.PhaseDef(s))

        if phases:
            d['phase_colors'] = phase_colors
            d['phases'] = phases

    if 'model' in want:
        if options.model_filename:
            d['model'] = cake.load_model(options.model_filename,
                                         options.model_format)

        if options.crust2loc or options.crust2profile:
            if options.crust2loc:
                try:
                    args = tuple(
                        [float(x) for x in options.crust2loc.split(',')])
                except Exception:
                    parser.error('format for --crust2loc option is '
                                 '"LATITUDE,LONGITUDE"')
            elif options.crust2profile:
                args = (options.crust2profile.upper(), )
            else:
                assert False

            if 'model' in d:
                d['model'] = d['model'].replaced_crust(args)
            else:
                from pyrocko import crust2x2
                profile = crust2x2.get_profile(*args)
                d['model'] = cake.LayeredModel.from_scanlines(
                    cake.from_crust2x2_profile(profile))

    if 'vred' in want:
        d['vred'] = options.vred
        if d['vred'] is not None:
            if not as_degrees:
                d['vred'] *= r2d * cake.km / cake.earthradius

    if 'distances' in want:
        distances = None
        if options.sdist:
            if options.sdist.find(':') != -1:
                ssn = options.sdist.split(':')
                if len(ssn) != 3:
                    parser.error('format for distances is '
                                 '"min_distance:max_distance:n_distances"')

                distances = num.linspace(*map(float, ssn))
            else:
                distances = num.array(list(map(float,
                                               options.sdist.split(','))),
                                      dtype=num.float)

            if not as_degrees:
                distances *= r2d * cake.km / cake.earthradius

        if options.sloc and options.rloc:
            try:
                slat, slon = tuple([float(x) for x in options.sloc.split(',')])
                rlat, rlon = tuple([float(x) for x in options.rloc.split(',')])
            except Exception:
                parser.error('format for --sloc and --rloc options is '
                             '"LATITUDE,LONGITUDE"')

            distance_sr = orthodrome.distance_accurate50m_numpy(
                slat, slon, rlat, rlon)

            distance_sr *= r2d / cake.earthradius
            if distances is not None:
                distances = num.concatenate((distances, [distance_sr]))
            else:
                distances = num.array([distance_sr], dtype=num.float)

        if distances is not None:
            d['distances'] = distances
        else:
            if 'distances' not in required:
                d['distances'] = None

    if 'slowness' in want:
        d['slowness'] = options.slowness / cake.d2r
        if not as_degrees:
            d['slowness'] /= cake.km * cake.m2d

    if 'interface' in want:
        if options.interface:
            try:
                d['interface'] = float(options.interface) * cake.km
            except ValueError:
                d['interface'] = options.interface

        else:
            d['interface'] = None

    if 'zstart' in want:
        d['zstart'] = options.sdepth * cake.km

    if 'zstop' in want:
        d['zstop'] = options.rdepth * cake.km

    if 'material' in want:
        md = {}
        userfactor = dict(vp=1000.,
                          vs=1000.,
                          rho=1000.,
                          qp=1.,
                          qs=1.,
                          qmu=1.,
                          qk=1.,
                          lame_lambda=1.0e9,
                          lame_mu=1.0e9,
                          poisson=1.)

        for k in userfactor.keys():
            if getattr(options, k) is not None:
                md[k] = getattr(options, k) * userfactor[k]

        if not (bool('lame_lambda' in md) == bool('lame_mu' in md)):
            parser.error('lambda and mu must be specified both.')
        if 'lame_lambda' in md and 'lame_mu' in md:
            md['lame'] = md.pop('lame_lambda'), md.pop('lame_mu')

        if md:
            try:
                d['material'] = cake.Material(**md)
            except cake.InvalidArguments as e:
                parser.error(str(e))

    for k in list(d.keys()):
        if k not in want:
            del d[k]

    for k in required:
        if k not in d:
            if k == 'model':
                d['model'] = cake.load_model('ak135-f-continental.m')

            elif k == 'distances':
                d['distances'] = num.linspace(10*cake.km, 100*cake.km, 10) \
                    / cake.earthradius * r2d

            elif k == 'phases':
                d['phases'] = list(map(cake.PhaseDef, 'Pp'))

            else:
                parser.error('missing %s' % k)

    return Anon(d)