Exemple #1
0
            hps=self.hyperparams['h_any_P_T'],
            slog_pdets=slog_pdets, residuals=res)

        llk_normal = multivariate_normal(
            self.datasets, icov_weights,
            self.hyperparams, res)

        fnorm = function([res], llk_normal)
        f_bulk_ichol = function([res], ichol_bulk_llk)
        f_bulk_icov_chol = function([res], icov_chol_bulk_llk)

        t0 = time()
        a = f_bulk_ichol(self.residuals)
        t1 = time()
        b = f_bulk_icov_chol(self.residuals)
        t2 = time()
        c = fnorm(self.residuals)

        logger.info('Bulk Ichol %f [s]' % (t1 - t0))
        logger.info('Bulk Icov_chol %f [s]' % (t2 - t1))

        assert_allclose(a, c, rtol=0., atol=1e-6)
        assert_allclose(b, c, rtol=0., atol=1e-6)
        assert_allclose(a, b, rtol=0., atol=1e-6)


if __name__ == '__main__':

    util.setup_logging('test_models', 'info')
    unittest.main()
Exemple #2
0
    for level in dry.levels:
        if level.vmax > 0.0:
            if level.vmin < 0.0:
                level.vmin = 0.0

            levels.append(level)

    combi = CPT(color_below=wet.color_below, color_above=dry.color_above, color_nan=dry.color_nan, levels=levels)

    return combi


if __name__ == "__main__":
    from pyrocko import util

    util.setup_logging("pyrocko.automap", "info")

    m = Map(
        lat=rand(40, 70.0),
        lon=rand(0.0, 20.0),
        radius=math.exp(rand(math.log(10 * km), math.log(2000 * km))),
        width=rand(10, 20),
        height=rand(10, 20),
        show_grid=True,
        show_topo=True,
        illuminate=True,
    )

    m.draw_cities()
    print m
    m.save("map.pdf")
Exemple #3
0
    def testUSGS(self):

        def is_the_haiti_event(ev):
            assert near(ev.magnitude, 7.0, 0.1)
            assert near(ev.lat, 18.443, 0.01)
            assert near(ev.lon, -72.571, 0.01)
            assert near(ev.depth, 13000., 1.)

        cat = catalog.USGS()

        tmin = util.str_to_time('2010-01-12 21:50:00')
        tmax = util.str_to_time('2010-01-13 03:17:00')

        names = cat.get_event_names(time_range=(tmin, tmax), magmin=5.)
        assert len(names) == 13
        for name in names:
            ev = cat.get_event(name)
            if ev.magnitude >= 7.:
                is_the_haiti_event(ev)
                ident = ev.name

        assert ident is not None
        cat.flush()
        ev = cat.get_event(ident)
        is_the_haiti_event(ev)


if __name__ == "__main__":
    util.setup_logging('test_catalog', 'debug')
    unittest.main()
        to_check = [
            ('http://nappe.wustl.edu/antelope/css-formats/wfdisc.htm',
             'pyrocko.css'),
            ('http://www.ietf.org/timezones/data/leap-seconds.list',
             'pyrocko.config'),
            ('http://stackoverflow.com/questions/2417794/', 'cake_plot'),
            ('http://igppweb.ucsd.edu/~gabi/rem.html', 'crust2x2_data'),
            ('http://kinherd.org/pyrocko_data/gsc20130501.txt', 'crustdb'),
            ('http://download.geonames.org/export/dump/', 'geonames'),
            ('http://emolch.github.io/gmtpy/', 'gmtpy'),
            ('http://www.apache.org/licenses/LICENSE-2.0', 'kagan.py'),
            ('http://www.opengis.net/kml/2.2', 'model'),
            ('http://maps.google.com/mapfiles/kml/paddle/S.png', 'model'),
            ('http://de.wikipedia.org/wiki/Orthodrome', 'orthodrome'),
            ('http://peterbird.name/oldFTP/PB2002', 'tectonics'),
            ('http://gsrm.unavco.org/model', 'tectonics'),
            ('http://stackoverflow.com/questions/19332902/', 'util'),
        ]

        for url in to_check:
            try:
                fdsn._request(url[0])
            except urllib.error.HTTPError as e:
                logger.warn('%s - %s referenced in pyrocko.%s' %
                            (e, url[0], url[1]))


if __name__ == '__main__':
    util.setup_logging('test_fdsn', 'warning')
    unittest.main()
            widget = layout.get_widget()
            # widget['J'] =  ('-JT%g/%g'  % (lon, lat)) + '/%(width)gp'
            widget['J'] =  ('-JE%g/%g/%g'  % (lon, lat, min(lat_delta/2.,180.))) + '/%(width)gp'
            aspect = gmtpy.aspect_for_projection( *(widget.J() + scaler.R()) )
            widget.set_aspect(aspect)
            
            if lat > 0:
                axes_layout = 'WSen'
            else:
                axes_layout = 'WseN'
        
            gmt.psbasemap( #B=('%(xinc)gg%(xinc)g:%(xlabel)s:/%(yinc)gg%(yinc)g:%(ylabel)s:' % scaler.get_params())+axes_layout,
                           B='5g5',
                        L=('x%gp/%gp/%g/%g/%gk' % (widget.width()/2., widget.height()/7.,lon,lat,scale_km) ),
                        *(widget.JXY()+scaler.R()) )
            
            gmt.psxy( in_columns=(lon_grid,lat_grid), S='x10p', W='1p/200/0/0', *(widget.JXY()+scaler.R()) )
            gmt.psxy( in_columns=(lon_grid_alt,lat_grid_alt), S='c10p', W='1p/0/0/200', *(widget.JXY()+scaler.R()) )
            
            gmt.save('orthodrome.pdf')
            subprocess.call( [ 'xpdf', '-remote', 'ortho', '-reload' ] )
            time.sleep(2)
        else:
            print 'ok', gsize, lat, lon
            
if __name__ == "__main__":
    util.setup_logging('test_orthodrome', 'warning')
    unittest.main()

            
    def save_as(self):
        if self.fig:
            fn = self.output_filename()
            self.fig.savefig(fn,
                             pad_inches=0.05, 
                             bbox_inches='tight')

    def configure_cli_parser(self, parser):
        parser.add_option(
            '--events',
            dest='events_filename',
            default=None,
            metavar='FILENAME',
            help='Read events from FILENAME')
    
def __snufflings__():
    '''Returns a list of snufflings to be exported by this module.'''
    
    return [ TimeLine() ]

if __name__=='__main__':
    import matplotlib.pyplot as plt
    util.setup_logging('time_line.py', 'info')
    s = TimeLine()
    options, args, parser = s.setup_cli()

    s.cli_mode = True
    if options.events_filename:
        s.make_time_line(list(model.Event.load_catalog(options.events_filename)))

Exemple #7
0
def process_common_options(options):
    util.setup_logging(program_name, options.loglevel)
Exemple #8
0
                                        self.starttime_max,
                                        dimension=self.gfs.npatches)
        slips = num.random.random(self.gfs.npatches)

        outnum = reference_numpy(self.gfs, durations, starttimes, slips)
        outtheanobatch = theano_batched_dot(self.gfs, durations, starttimes,
                                            slips)

        self.gfs.set_stack_mode('numpy')
        durationidxs = self.gfs.durations2idxs(durations)
        starttimeidxs = self.gfs.starttimes2idxs(starttimes)

        outtheanofor = theano_for_loop(self.gfs, durationidxs, starttimeidxs,
                                       slips)

        num.testing.assert_allclose(outnum, outtheanobatch, rtol=0., atol=1e-6)
        num.testing.assert_allclose(outnum, outtheanofor, rtol=0., atol=1e-6)

    def test_snuffle(self):

        self.gfs.get_traces(targets=self.gfs.wavemap.targets[0:2],
                            patchidxs=[0],
                            durationidxs=list(range(self.ndurations)),
                            starttimeidxs=[0],
                            plot=True)


if __name__ == '__main__':
    util.setup_logging('test_ffi', 'debug')
    unittest.main()
Exemple #9
0
        x3, y3, z3 = gmtpy.tabledata(xf, yf, zf)

        assert_allclose(x3, x2, atol=1e-7)
        assert_allclose(y3, y2, atol=1e-7)
        assert_allclose(z3, z2, atol=1e-7)

        xf2, yf2, zf2 = gmtpy.doublegrid(xf, yf, zf)
        assert (xf2.size, yf2.size, zf2.size) == (199, 199, 199 * 199)

        fn = self.fpath('grid.nc')
        for naming in ['xy', 'lonlat']:
            gmtpy.savegrd(xf, yf, zf, fn, naming=naming, title='mygrid')
            xf3, yf3, zf3 = gmtpy.loadgrd(fn)
            assert_allclose(xf3, xf)
            assert_allclose(yf3, yf)
            assert_allclose(zf3, zf)

    def test_text_box(self):

        for version in gmtpy.all_installed_gmt_versions():
            s = gmtpy.text_box('Hello', gmtversion=version)
            assert_allclose(s, (25.8, 9.), rtol=0.1)
            s = gmtpy.text_box('Abc def ghi jkl mno pqr stu vwx yz',
                               gmtversion=version)
            assert_allclose(s, (179.9, 12.3), rtol=0.01)


if __name__ == "__main__":
    util.setup_logging('test_gmtpy', 'warning')
    unittest.main()
Exemple #10
0
        for tr in traces.values():
            yield tr


def detect(first512):
    # does not work properly, produces too many false positives
    # difficult to improve due to the very compact GCF header
    try:
        if len(first512) < 512:
            return False

        f = StringIO(first512)
        h = read_header(f)
        return True

    except:
        return False


if __name__ == '__main__':
    from pyrocko import util
    util.setup_logging('warn')

    all_traces = []
    for fn in sys.argv[1:]:
        if detect(open(fn).read(512)):
            print fn
            all_traces.extend(iload(fn))

    trace.snuffle(all_traces)
Exemple #11
0
from beat.info import project_root
from pyrocko import util

logger = logging.getLogger('test_distributed')


class TestDistributed(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)
        self.n_jobs = 4
        self.beatpath = project_root

    def test_mpi_runner(self):

        logger.info('testing')
        runner = MPIRunner()
        runner.run(self.beatpath + '/test/pt_toy_example.py',
                   n_jobs=self.n_jobs)
        logger.info('successful!')

    def test_arg_passing(self):
        nsamples = 100
        sampler_args = [nsamples]
        run_mpi_sampler('pt', sampler_args, keep_tmp=True, n_jobs=self.n_jobs)


if __name__ == '__main__':

    util.setup_logging('test_distributed', 'info')
    unittest.main()
Exemple #12
0
    Tries to use SRTMGL3, falls back to ETOPO01 if not available.
    '''

    for dem in ['SRTMGL3', 'ETOPO1']:
        r = get(dem, (lon, lat))
        if r is not None and r != 0:
            return r


def select_dem_names(kind, dmin, dmax, region):
    assert kind in ('land', 'ocean')
    ok = []
    if kind == 'land':
        for dem in srtmgl3_all:
            if dem.is_suitable(region, dmin, dmax):
                ok.append(dem.name)
                break

    for dem in etopo1_all:
        if dem.is_suitable(region, dmin, dmax):
            ok.append(dem.name)
            break

    return ok


if __name__ == '__main__':
    # comparison((-180., 180., -90, 90), dems=[etopo1_d8])
    util.setup_logging('topo', 'info')
    comparison((30, 31, 30, 31), dems=[srtmgl3, srtmgl3_d2])
Exemple #13
0
                    vmin=accvmin[i], vmax=accvmax[i], cmap='hot')
                axes1[rowi, coli].set_title('min %i, max%i' % (accvmin[i], accvmax[i]))
                axes1[rowi, coli].get_xaxis().set_ticklabels([])
                axes2[rowi, coli].matshow(
                    history.sample_counts[i], vmin=scvmin[i], vmax=scvmax[i], cmap='hot')
                axes2[rowi, coli].set_title('min %i, max%i' % (scvmin[i], scvmax[i]))
                axes2[rowi, coli].get_xaxis().set_ticklabels([])


        fig2.suptitle('Accepted number of samples')
        fig2.tight_layout()
        fig3.tight_layout()
        fig3.suptitle('Total number of samples')
        plt.show()

        #d = mtrace.get_values('X', combine=True, squeeze=True)
        #mu1d = num.abs(d).mean(axis=0)

        #num.testing.assert_allclose(mu1, mu1d, rtol=0., atol=0.03)

    def test_multicore(self):
        self._test_sample(self.n_chains, self.test_folder_multi)

    def tearDown(self):
        shutil.rmtree(self.test_folder_multi)


if __name__ == '__main__':
    util.setup_logging('test_pt', 'info')
    unittest.main()
Exemple #14
0
import random
import logging
import sys
from matplotlib import pyplot as plt
from pyrocko import beachball, moment_tensor as pmt
from pyrocko import util

logger = logging.getLogger(sys.argv[0])

util.setup_logging()

fig = plt.figure(figsize=(10., 4.))
fig.subplots_adjust(left=0., right=1., bottom=0., top=1.)
axes = fig.add_subplot(1, 1, 1)

for i in xrange(200):

    # create random moment tensor
    mt = pmt.MomentTensor.random_mt()

    try:
        # create beachball from moment tensor
        beachball.plot_beachball_mpl(
            mt,
            axes,
            # type of beachball: deviatoric, full or double couple (dc)
            beachball_type='full',
            size=random.random() * 120.,
            position=(random.random() * 10., random.random() * 10.),
            alpha=random.random(),
            linewidth=1.0)
import random
import logging
from matplotlib import pyplot as plt
from pyrocko import moment_tensor as pmt
from pyrocko import util
from pyrocko.plot import beachball

''' Beachball Copacabana '''

logger = logging.getLogger('pyrocko.examples.beachball_example01')

util.setup_logging()

fig = plt.figure(figsize=(10., 4.))
fig.subplots_adjust(left=0., right=1., bottom=0., top=1.)
axes = fig.add_subplot(1, 1, 1)

for i in range(200):

    # create random moment tensor
    mt = pmt.MomentTensor.random_mt()

    try:
        # create beachball from moment tensor
        beachball.plot_beachball_mpl(
            mt, axes,
            # type of beachball: deviatoric, full or double couple (dc)
            beachball_type='full',
            size=random.random()*120.,
            position=(random.random()*10., random.random()*10.),
            alpha=random.random(),
Exemple #16
0
                           (vp / km), source, target) - textra * 0.2
            tmax = store.t('{vel:%g}' %
                           (vs / km), source, target) + textra * 0.2

            for tr in trs + trs2:
                tr.chop(tmin, tmax)

            denom = 0.0
            for cha in 'rtz':
                t1 = g(trs, cha)
                t2 = g(trs2, cha)
                denom += num.sum(t1.ydata**2) + num.sum(t2.ydata**2)

            ds = []
            for cha in 'rtz':
                t1 = g(trs, cha)
                t2 = g(trs2, cha)
                ds.append(2.0 * num.sum((t1.ydata - t2.ydata)**2) / denom)

            ds = num.array(ds)

            # if not num.all(ds < 0.05):
            #    trace.snuffle(trs+trs2)

            assert num.all(ds < 0.05)


if __name__ == '__main__':
    util.setup_logging('test_gf_qseis', 'warning')
    unittest.main()
                replace_topo_color_only=tile,
                illuminate=True)

            m.draw_cities()
            fname = 'automap_test_fidshi.png'
            fpath = self.fpath(fname)
            m.save(fpath)
            self.compare_with_ref(fname, 0.01, show=False)

    def test_new_zealand(self):
        m = automap.Map(
            lat=-42.57,
            lon=173.01,
            radius=1000.*km,
            width=20.,
            height=20.,
            color_dry=gmtpy.color_tup('aluminium1'),
            show_topo=False,
            show_rivers=False,
            show_plates=True)

        m.draw_cities()
        fname = 'new_zealand.pdf'
        fpath = self.fpath(fname)
        m.save(fpath)


if __name__ == "__main__":
    util.setup_logging('test_automap', 'warning')
    unittest.main()
Exemple #18
0
                target_q2.azimuth = 0.
                target_q2.dip = 90.

            target_q = copy.deepcopy(target_q2)
            target_q.store_id = 'qseis2d_test_q'
            target_q.codes = ('', '0000', 'Q', cha)
            targets_q2.append(target_q2)
            targets_q.append(target_q)

        targets = targets_q + targets_q2
        engine = gf.LocalEngine(store_dirs=[q2_store_dir, q_store_dir])
        response = engine.process(source, targets)

        qtrcs = []
        q2trcs = []
        for s, target, trc in response.iter_results():
            if target.codes[2] == 'Q':
                qtrcs.append(trc)
            else:
                q2trcs.append(trc)

        for q, q2 in zip(qtrcs, q2trcs):
            num.testing.assert_allclose(q.ydata, q2.ydata, atol=4e-23)


#        trace.snuffle(qtrcs + q2trcs)

if __name__ == '__main__':
    util.setup_logging('test_qseis_qseis2d', 'warning')
    unittest.main()
        emarker.set_alerted(True)

        markers = [_marker, emarker, pmarker]
        fn = tempfile.mkstemp()[1]

        marker.save_markers(markers, fn)

        in_markers = marker.load_markers(fn)
        in__marker, in_emarker, in_pmarker = in_markers
        for i, m in enumerate(in_markers):
            if not isinstance(m, marker.EventMarker):
                assert (m.tmax - m.tmin) == 9.
            else:
                assert not m.is_alerted()

        marker.associate_phases_to_events([in_pmarker, in_emarker])

        in_event = in_pmarker.get_event()

        assert all((in_event.lat == 111., in_event.lon == 111.,
                    in_event.depth == 111., in_event.time == 111.))

        assert in_pmarker.get_event_hash() == in_event.get_hash()
        assert in_pmarker.get_event_time() == 111.


if __name__ == "__main__":
    util.setup_logging('test_marker', 'warning')
    unittest.main()
Exemple #20
0
    if config.config().earthdata_credentials is None:
        return False
    return True


class TopoTestCase(unittest.TestCase):
    @unittest.skipUnless(have_srtm_credentials(),
                         'No Earthdata credentials in config.')
    def test_srtm(self):
        srtm = topo.srtmgl3
        tiles = list(srtm.available_tilenames())

        tilenum = num.random.randint(0, len(tiles) - 1)
        srtm.download_tile(tiles[tilenum])
        srtm.get_tile(0, 0)

    @unittest.skip('etopo not downloaded.')
    def test_etopo(self):
        topo.etopo1.make_tiles()

    def test_tile(self):
        tile1 = topo.tile.Tile(0., 0., 1., 1., num.ones((100, 100)))
        tile2 = topo.tile.Tile(0., 0., 1., 1., num.ones((100, 100)))

        topo.tile.combine([tile1, tile2])


if __name__ == '__main__':
    util.setup_logging('test_topo', 'debug')
    unittest.main()
Exemple #21
0
def snuffler_from_commandline(args=None):
    if args is None:
        args = sys.argv[1:]

    usage = '''usage: %prog [options] waveforms ...'''
    parser = OptionParser(usage=usage)

    parser.add_option(
        '--format',
        dest='format',
        default='detect',
        choices=io.allowed_formats('load'),
        help='assume input files are of given FORMAT. Choices: %s'
             % io.allowed_formats('load', 'cli_help', 'detect'))

    parser.add_option(
        '--pattern',
        dest='regex',
        metavar='REGEX',
        help='only include files whose paths match REGEX')

    parser.add_option(
        '--stations',
        dest='station_fns',
        action='append',
        default=[],
        metavar='STATIONS',
        help='read station information from file STATIONS')

    parser.add_option(
        '--stationxml',
        dest='stationxml_fns',
        action='append',
        default=[],
        metavar='STATIONSXML',
        help='read station information from XML file STATIONSXML')

    parser.add_option(
        '--event', '--events',
        dest='event_fns',
        action='append',
        default=[],
        metavar='EVENT',
        help='read event information from file EVENT')

    parser.add_option(
        '--markers',
        dest='marker_fns',
        action='append',
        default=[],
        metavar='MARKERS',
        help='read marker information file MARKERS')

    parser.add_option(
        '--follow',
        type='float',
        dest='follow',
        metavar='N',
        help='follow real time with a window of N seconds')

    parser.add_option(
        '--cache',
        dest='cache_dir',
        default=config.config().cache_dir,
        metavar='DIR',
        help='use directory DIR to cache trace metadata '
             '(default=\'%default\')')

    parser.add_option(
        '--force-cache',
        dest='force_cache',
        action='store_true',
        default=False,
        help='use the cache even when trace attribute spoofing is active '
             '(may have silly consequences)')

    parser.add_option(
        '--store-path',
        dest='store_path',
        metavar='PATH_TEMPLATE',
        help='store data received through streams to PATH_TEMPLATE')

    parser.add_option(
        '--store-interval',
        type='float',
        dest='store_interval',
        default=600,
        metavar='N',
        help='dump stream data to file every N seconds [default: %default]')

    parser.add_option(
        '--ntracks',
        type='int',
        dest='ntracks',
        default=24,
        metavar='N',
        help='initially use N waveform tracks in viewer [default: %default]')

    parser.add_option(
        '--opengl',
        dest='opengl',
        action='store_true',
        default=False,
        help='use OpenGL for drawing')

    parser.add_option(
        '--qt5',
        dest='gui_toolkit_qt5',
        action='store_true',
        default=False,
        help='use Qt5 for the GUI')

    parser.add_option(
        '--qt4',
        dest='gui_toolkit_qt4',
        action='store_true',
        default=False,
        help='use Qt4 for the GUI')

    parser.add_option(
        '--debug',
        dest='debug',
        action='store_true',
        default=False,
        help='print debugging information to stderr')

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

    if options.debug:
        util.setup_logging('snuffler', 'debug')
    else:
        util.setup_logging('snuffler', 'warning')

    if options.gui_toolkit_qt4:
        config.override_gui_toolkit = 'qt4'

    if options.gui_toolkit_qt5:
        config.override_gui_toolkit = 'qt5'

    this_pile = pile.Pile()
    stations = []
    for stations_fn in extend_paths(options.station_fns):
        stations.extend(model.station.load_stations(stations_fn))

    for stationxml_fn in extend_paths(options.stationxml_fns):
        stations.extend(
            stationxml.load_xml(
                filename=stationxml_fn).get_pyrocko_stations())

    events = []
    for event_fn in extend_paths(options.event_fns):
        events.extend(model.load_events(event_fn))

    markers = []
    for marker_fn in extend_paths(options.marker_fns):
        markers.extend(marker.load_markers(marker_fn))

    return snuffle(
        this_pile,
        stations=stations,
        events=events,
        markers=markers,
        ntracks=options.ntracks,
        follow=options.follow,
        controls=True,
        opengl=options.opengl,
        paths=args,
        cache_dir=options.cache_dir,
        regex=options.regex,
        format=options.format,
        force_cache=options.force_cache,
        store_path=options.store_path,
        store_interval=options.store_interval)
Exemple #22
0
        tn = self.tilename(itx, ity)
        if tn not in self.available_tilenames():
            return None
        else:
            fpath = self.tilepath(tn)
            if not op.exists(fpath):
                self.download_tile(tn)

            zipf = zipfile.ZipFile(fpath, 'r')
            rawdata = zipf.read(tn + '.hgt')
            zipf.close()
            data = num.fromstring(rawdata, dtype=self.dtype)
            assert data.size == self.ntx * self.nty
            data = data.reshape(self.nty, self.ntx)[::-1, ::]
            return tile.Tile(self.xmin + itx * self.stx,
                             self.ymin + ity * self.sty, self.dx, self.dx,
                             data)


if __name__ == '__main__':
    import sys

    util.setup_logging('pyrocko.topo.srtmgl3', 'info')

    if len(sys.argv) != 2:
        sys.exit('usage: python -m pyrocko.topo.srtmgl3 download')

    if sys.argv[1] == 'download':
        srtmgl3 = SRTMGL3()
        srtmgl3.download()
Exemple #23
0
        s = collection.get_scenario('gnss')
        assert len(s.get_gnss_campaigns()) == 1

    @unittest.skipUnless(
        gmtpy.have_gmt(), 'GMT not available')
    @unittest.skipUnless(
        have_srtm_credentials(),
        'No Earthdata credentials in config.')
    def test_scenario_map(self):
        tempdir = mkdtemp(prefix='pyrocko-scenario')
        self.tempdirs.append(tempdir)

        generator = self.generator
        engine = gf.get_engine()

        collection = scenario.ScenarioCollection(tempdir, engine)
        collection.add_scenario('plot', generator)

        s = collection.get_scenario('plot')
        s.get_map()

    def assert_traces_almost_equal(self, trs1, trs2):
        assert len(trs1) == len(trs2)
        for (tr1, tr2) in zip(trs1, trs2):
            tr1.assert_almost_equal(tr2)


if __name__ == '__main__':
    util.setup_logging('test_scenario', 'warning')
    unittest.main()
Exemple #24
0
            metavar='FILENAME',
            help='Read stations from FILENAME')

        parser.add_option(
            '--provider',
            dest='map_provider',
            default='google',
            help='map provider [google | osm] (default=osm)')


def __snufflings__():
    return [MapMaker()]


if __name__ == '__main__':
    util.setup_logging('map.py', 'info')
    s = MapMaker()
    options, args, parser = s.setup_cli()
    s.markers = []

    if options.stations_filename:
        stations = model.load_stations(options.stations_filename)
        s.stations = stations
    else:
        s.stations = None

    if options.events_filename:
        events = model.load_events(filename=options.events_filename)
        markers = [gui_util.EventMarker(e) for e in events]
        s.markers.extend(markers)
def produce(deltat, duration):
    logging.debug('rate %g Hz, duration %g s' % (1./deltat, duration))
    tbegin = time.time()
    n = 0
    while True:
        t = time.time() - tbegin
        nt = int(t/deltat)
        while n < nt:
            d = random.randint(-127, 128)
            sys.stdout.write("%i\n" % d)
            n += 1

        sys.stdout.flush()

        tsleep = 0.01
        time.sleep(tsleep)

        if t > duration:
            break


util.setup_logging('producer', 'debug')

produce(0.0025, 20.)
logging.debug('sleep 2 s')
time.sleep(2.)
produce(0.0025, 20.)
produce(0.005, 20.)
produce(0.005005, 20.)
Exemple #26
0
def main(args=None):
    if args is None:
        args = sys.argv[1:]

    parser = OptionParser(
        usage=usage,
        description=description)

    parser.add_option(
        '--width',
        dest='width',
        type='float',
        default=20.0,
        metavar='FLOAT',
        help='set width of output image [cm] (%default)')

    parser.add_option(
        '--height',
        dest='height',
        type='float',
        default=15.0,
        metavar='FLOAT',
        help='set height of output image [cm] (%default)')

    parser.add_option(
        '--topo-resolution-min',
        dest='topo_resolution_min',
        type='float',
        default=40.0,
        metavar='FLOAT',
        help='minimum resolution of topography [dpi] (%default)')

    parser.add_option(
        '--topo-resolution-max',
        dest='topo_resolution_max',
        type='float',
        default=200.0,
        metavar='FLOAT',
        help='maximum resolution of topography [dpi] (%default)')

    parser.add_option(
        '--no-grid',
        dest='show_grid',
        default=True,
        action='store_false',
        help='don\'t show grid lines')

    parser.add_option(
        '--no-topo',
        dest='show_topo',
        default=True,
        action='store_false',
        help='don\'t show topography')

    parser.add_option(
        '--no-cities',
        dest='show_cities',
        default=True,
        action='store_false',
        help='don\'t show cities')

    parser.add_option(
        '--no-illuminate',
        dest='illuminate',
        default=True,
        action='store_false',
        help='deactivate artificial illumination of topography')

    parser.add_option(
        '--illuminate-factor-land',
        dest='illuminate_factor_land',
        type='float',
        metavar='FLOAT',
        help='set factor for artificial illumination of land (0.5)')

    parser.add_option(
        '--illuminate-factor-ocean',
        dest='illuminate_factor_ocean',
        type='float',
        metavar='FLOAT',
        help='set factor for artificial illumination of ocean (0.25)')

    parser.add_option(
        '--theme',
        choices=['topo', 'soft'],
        default='topo',
        help='select color theme, available: topo, soft (topo)"')

    parser.add_option(
        '--download-etopo1',
        dest='download_etopo1',
        action='store_true',
        help='download full ETOPO1 topography dataset')

    parser.add_option(
        '--download-srtmgl3',
        dest='download_srtmgl3',
        action='store_true',
        help='download full SRTMGL3 topography dataset')

    parser.add_option(
        '--make-decimated-topo',
        dest='make_decimated',
        action='store_true',
        help='pre-make all decimated topography datasets')

    parser.add_option(
        '--stations',
        dest='stations_fn',
        metavar='FILENAME',
        help='load station coordinates from FILENAME')

    parser.add_option(
        '--events',
        dest='events_fn',
        metavar='FILENAME',
        help='load event coordinates from FILENAME')

    parser.add_option(
        '--debug',
        dest='debug',
        action='store_true',
        default=False,
        help='print debugging information to stderr')

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

    if options.debug:
        util.setup_logging(program_name, 'debug')
    else:
        util.setup_logging(program_name, 'info')

    if options.download_etopo1:
        import pyrocko.datasets.topo.etopo1
        pyrocko.datasets.topo.etopo1.download()

    if options.download_srtmgl3:
        import pyrocko.datasets.topo.srtmgl3
        pyrocko.datasets.topo.srtmgl3.download()

    if options.make_decimated:
        import pyrocko.datasets.topo
        pyrocko.datasets.topo.make_all_missing_decimated()

    if (options.download_etopo1 or options.download_srtmgl3 or
            options.make_decimated) and len(args) == 0:

        sys.exit(0)

    if options.theme == 'soft':
        color_kwargs = {
            'illuminate_factor_land': options.illuminate_factor_land or 0.2,
            'illuminate_factor_ocean': options.illuminate_factor_ocean or 0.15,
            'color_wet': (216, 242, 254),
            'color_dry': (238, 236, 230),
            'topo_cpt_wet': 'light_sea_uniform',
            'topo_cpt_dry': 'light_land_uniform'}
    elif options.theme == 'topo':
        color_kwargs = {
            'illuminate_factor_land': options.illuminate_factor_land or 0.5,
            'illuminate_factor_ocean': options.illuminate_factor_ocean or 0.25}

    events = []
    if options.events_fn:
        events = model.load_events(options.events_fn)

    stations = []

    if options.stations_fn:
        stations = model.load_stations(options.stations_fn)

    if not (len(args) == 4 or (
            len(args) == 1 and (events or stations))):

        parser.print_help()
        sys.exit(1)

    if len(args) == 4:
        try:
            lat = float(args[0])
            lon = float(args[1])
            radius = float(args[2])*km
        except Exception:
            parser.print_help()
            sys.exit(1)
    else:
        lats, lons = latlon_arrays(stations+events)
        lat, lon = map(float, od.geographic_midpoint(lats, lons))
        radius = float(
            num.max(od.distance_accurate50m_numpy(lat, lon, lats, lons)))
        radius *= 1.1

    m = automap.Map(
        width=options.width,
        height=options.height,
        lat=lat,
        lon=lon,
        radius=radius,
        topo_resolution_max=options.topo_resolution_max,
        topo_resolution_min=options.topo_resolution_min,
        show_topo=options.show_topo,
        show_grid=options.show_grid,
        illuminate=options.illuminate,
        **color_kwargs)

    logger.debug('map configuration:\n%s' % str(m))

    if options.show_cities:
        m.draw_cities()

    if stations:
        lats = [s.lat for s in stations]
        lons = [s.lon for s in stations]

        m.gmt.psxy(
            in_columns=(lons, lats),
            S='t8p',
            G='black',
            *m.jxyr)

        for s in stations:
            m.add_label(s.lat, s.lon, '%s' % '.'.join(
                x for x in s.nsl() if x))

    if events:
        beachball_symbol = 'mt'
        beachball_size = 20.0
        for ev in events:
            if ev.moment_tensor is None:
                m.gmt.psxy(
                    in_rows=[[ev.lon, ev.lat]],
                    S='c12p',
                    G=gmtpy.color('scarletred2'),
                    W='1p,black',
                    *m.jxyr)

            else:
                devi = ev.moment_tensor.deviatoric()
                mt = devi.m_up_south_east()
                mt = mt / ev.moment_tensor.scalar_moment() \
                    * pmt.magnitude_to_moment(5.0)
                m6 = pmt.to6(mt)
                data = (ev.lon, ev.lat, 10) + tuple(m6) + (1, 0, 0)

                if m.gmt.is_gmt5():
                    kwargs = dict(
                        M=True,
                        S='%s%g' % (
                            beachball_symbol[0], beachball_size / gmtpy.cm))
                else:
                    kwargs = dict(
                        S='%s%g' % (
                            beachball_symbol[0], beachball_size*2 / gmtpy.cm))

                m.gmt.psmeca(
                    in_rows=[data],
                    G=gmtpy.color('chocolate1'),
                    E='white',
                    W='1p,%s' % gmtpy.color('chocolate3'),
                    *m.jxyr,
                    **kwargs)

    m.save(args[-1])
            dest='markers_filename',
            metavar='FILENAME',
            help='Read markers from FILENAME')

         parser.add_option(
            '--output',
            dest='out_filename',
            default=default_output_filename,
            metavar='FILENAME',
            help='set output filename template (default="%s")' % default_output_filename)


def __snufflings__():
    return [ExtractEvents()]


if __name__ == '__main__':
    import logging
    logger = logging.getLogger()
    util.setup_logging('extract_events.py', 'info')
    s = ExtractEvents()
    options, args, parser = s.setup_cli()
    s.markers_filename = options.markers_filename
    s.out_filename = options.out_filename
    if not options.markers_filename:
        logger.critical('no markers file given; use the --markers=FILENAME option')
        sys.exit(1)

    s.call()

Exemple #28
0
                    lab.plot(f, num.angle(t_sx), color='black')
                    lab.plot(f, num.angle(t_er), color='red')
                    lab.xscale('log')
                    lab.show()

                else:
                    print 'ok'
            except:
                print 'failed: ', nslc


import time
gt = None


def lap():
    global gt
    t = time.time()
    if gt is not None:
        diff = t - gt
    else:
        diff = 0

    gt = t
    return diff


if __name__ == '__main__':
    util.setup_logging('test_fdsn_station', 'warning')
    unittest.main()
Exemple #29
0
            if zmin == 0.:
                assert isinstance(elements[0], cake.Surface)

    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())


if __name__ == "__main__":
    util.setup_logging('test_cake', 'warning')
    unittest.main()
            axes1.imshow(img)
            axes1.set_title('Candidate')
            axes2.imshow(img_ref)
            axes2.set_title('Reference')
            axes3.imshow(d)
            axes3.set_title('Mean abs difference: %g' % merr)
            plt.show()
            plt.close(fig)

        assert merr <= tolerance

    def test_response_plot(self):
        for fn, format in [('test1.resp', 'resp'), ('test1.sacpz', 'sacpz')]:

            fpath_resp = common.test_data_file(fn)
            fname = 'test_response_plot_%s.png' % fn
            fpath_png = self.fpath(fname)
            resps, labels = response_plot.load_response_information(
                fpath_resp, format)
            labels = [lab[len(fpath_resp) + 1:] or 'dummy' for lab in labels]
            response_plot.plot(responses=resps,
                               labels=labels,
                               filename=fpath_png,
                               dpi=50)
            self.compare_with_ref(fname, 0.01)


if __name__ == "__main__":
    util.setup_logging('test_response_plot', 'warning')
    unittest.main()
import sys
import matplotlib
matplotlib.use('Qt4Agg')
import logging
import os.path as op
import numpy as num
import progressbar

from pyrocko import model, trace, util, orthodrome, cake, gui_util
from pyrocko.gf.seismosizer import Target, SeismosizerTrace
from pyrocko.snuffling import Snuffling, Choice, Param, Switch
from similarity import SimilarityMatrix, Similarity
import matplotlib.pyplot as plt
util.setup_logging('cc.py')
logger = logging.getLogger('cc-snuffling')

def make_targets(pile, stations):
    targets = []
    for nslc_id in pile.nslc_ids.keys():
        for s in stations:
            if util.match_nslc('%s.*'%(s.nsl_string()), nslc_id):
                targets.append(Target(lat=s.lat,
                                     lon=s.lon,
                                     depth=s.depth,
                                     elevation=s.elevation,
                                     codes=nslc_id))
            else:
                continue
    return targets

Exemple #32
0
                stalta = tr.copy()
                stalta.sta_lta_right(tshort, tlong)
                stalta.set_codes(location='stalta')

                ydata = num.zeros(n)

                s = int(round(tshort / tr.deltat))
                l = int(round(tlong / tr.deltat))

                for i in xrange(l - s, n - s):
                    ydata[i] = (1.0 / s * num.sum(y[i:i + s])) / (
                        1.0 / l *
                        num.sum(y[i + s - l:i + s])) * float(s) / float(l)

                stalta_ref = trace.Trace('',
                                         'X',
                                         'ref',
                                         '',
                                         ydata=ydata,
                                         deltat=1.0)

                stalta_ref.chop(float(l - s), float(n - s))

                assert numeq(stalta.ydata, stalta_ref.ydata, 1e-3)


if __name__ == "__main__":
    util.setup_logging('test_trace', 'warning')
    unittest.main()
        for n in range(nsrc):
            src = gf.RectangularSource(
                lat=0., lon=0.,
                anchor='bottom',
                north_shift=5000., east_shift=9000., depth=4.*km,
                width=2.*km, length=8.*km,
                dip=0., rake=0., strike=(180./nsrc + 1) * n,
                slip=1.)
            rect_sources.append(src)

    @staticmethod
    def plot_rectangular_source(src, store):
        from matplotlib import pyplot as plt
        from matplotlib.patches import Polygon
        ax = plt.gca()
        ne = src.outline(cs='xy')
        p = Polygon(num.fliplr(ne), fill=False, color='r', alpha=.7)
        ax.add_artist(p)

        mt = src.discretize_basesource(store)
        ax.scatter(mt.east_shifts, mt.north_shifts, alpha=1)
        ax.scatter(src.east_shift, src.north_shift, color='r')

        plt.axis('equal')
        plt.show()


if __name__ == '__main__':
    util.setup_logging('test_gf_source_types', 'warning')
    unittest.main(defaultTest='GFSourceTypesTestCase')
Exemple #34
0
    for scheme in config_type_class.provided_schemes:
        for discretized_source_class in gf.discretized_source_classes:
            if scheme in discretized_source_class.provided_schemes:
                name = 'test_homogeneous_scenario_%s_%s_%s' % (
                    config_type_class.short_type, scheme,
                    discretized_source_class.__name__)

                def make_method(config_type_class, scheme,
                                discretized_source_class):
                    @unittest.skipIf(
                        scheme.startswith('poro')
                        or config_type_class.short_type == 'C',
                        'todo: test poro and store type C')
                    def test_homogeneous_scenario(self):
                        return self._test_homogeneous_scenario(
                            config_type_class, scheme,
                            discretized_source_class)

                    test_homogeneous_scenario.__name__ = name

                    return test_homogeneous_scenario

                setattr(
                    GFTestCase, name,
                    make_method(config_type_class, scheme,
                                discretized_source_class))

if __name__ == '__main__':
    util.setup_logging('test_gf', 'warning')
    unittest.main()
Exemple #35
0
        if tn not in self.available_tilenames():
            return None
        else:
            fpath = self.tilepath(tn)
            if not op.exists(fpath):
                self.download_tile(tn)

            zipf = zipfile.ZipFile(fpath, 'r')
            rawdata = zipf.read(tn + '.hgt')
            zipf.close()
            data = num.fromstring(rawdata, dtype=self.dtype)
            assert data.size == self.ntx * self.nty
            data = data.reshape(self.nty, self.ntx)[::-1, ::]
            return tile.Tile(
                self.xmin + itx*self.stx,
                self.ymin + ity*self.sty,
                self.dx, self.dx, data)


if __name__ == '__main__':
    import sys

    util.setup_logging('pyrocko.topo.srtmgl3', 'info')

    if len(sys.argv) != 2:
        sys.exit('usage: python -m pyrocko.topo.srtmgl3 download')

    if sys.argv[1] == 'download':
        srtmgl3 = SRTMGL3()
        srtmgl3.download()
Exemple #36
0
from pyrocko import gf
from pyrocko import model, util
from pyrocko import orthodrome as otd
from pyrocko import moment_tensor as mt
from pyrocko import trace
from beat.sources import RectangularSource
from beat import ffi, models

import numpy as num
from beat import inputf, utility, heart, config
import os

km = 1000.
util.setup_logging('test_ffi_stacking', 'info')


# set random seed for reproducible station locations
num.random.seed(10)

nuc_dip = 5.
nuc_strike = 2.
time_shift = -10.   # from previous inversion

# general
project_dir = '/home/vasyurhm/BEATS/LaquilaJointPonlyUPDATE_wide_kin3'
store_superdirs = ['/home/vasyurhm/GF/Laquila']
white_noise_perc_max = 0.025   # White noise to disturb the synthetic data, in percent to the maximum amplitude [Hallo et al. 2016 use 0.01]

problem = models.load_model(project_dir, mode='ffi', build=False)
event = problem.config.event
Exemple #37
0
        for x in range(nx):
            strike = fuzz_angle(0., 360.)
            dip = fuzz_angle(0., 90.)
            rake = fuzz_angle(-180., 180.)

            mt = mtm.MomentTensor(
                strike=strike,
                dip=dip,
                rake=rake)

            self.compare_beachball(mt)

    def test_specific_dcs(self):
        for strike, dip, rake in [
                [270., 0.0, 0.01],
                [360., 28.373841741182012, 90.],
                [0., 0., 0.]]:

            mt = mtm.MomentTensor(
                strike=strike,
                dip=dip,
                rake=rake)

            self.compare_beachball(mt)


if __name__ == "__main__":
    util.setup_logging('test_moment_tensor', 'warning')
    unittest.main()
Exemple #38
0
                      north_shift=500., east_shift=500.)
                    for lat in lats]

                dsources = [
                    s.discretize_basesource(store, target=dummy_target)
                    for s in sources]

                DS = dsources[0].__class__

                dsource = DS.combine(dsources)
                assert dsource.nelements == sum(s.nelements for s in dsources)

    def test_source_times(self):
        store = self.dummy_store()
        dummy_target = gf.Target()
        for S in gf.source_classes:
            if not hasattr(S, 'discretize_basesource'):
                continue

            for t in [0.0, util.str_to_time('2014-01-01 10:00:00')]:
                source = S(time=t)
                dsource = source.discretize_basesource(
                    store, target=dummy_target)
                cent = dsource.centroid()
                assert numeq(cent.time + source.get_timeshift(), t, 0.0001)


if __name__ == '__main__':
    util.setup_logging('test_gf_sources', 'warning')
    unittest.main()
                    except IOError as e:
                        if e.errno == errno.ENOLCK:
                            time.sleep(0.01)
                            pass
                        else:
                            raise

                f.seek(0)
                assert '' == f.read()
                f.write('%s' % x)
                f.flush()
                # time.sleep(0.01)
                f.seek(0)
                f.truncate(0)
                fcntl.lockf(f, fcntl.LOCK_UN)

        fos, fn = tempfile.mkstemp()  # (dir='/try/with/nfs/mounted/dir')
        f = open(fn, 'w')
        f.close()

        for x in parimap(work, range(100), nprocs=10, eprintignore=()):
            pass

        os.close(fos)
        os.remove(fn)


if __name__ == '__main__':
    util.setup_logging('test_parimap', 'warning')
    unittest.main()
Exemple #40
0
                    resp = engine.process(sources, targets, nprocs=nprocs)
                    t1 = time.time()
                    if temperature == 'hot':
                        dur_pyrocko = t1 - t0

                    del resp

                ksources = map(to_kiwi_source, sources)

                for temperature in ['cold', 'hot']:
                    t0 = time.time()
                    seis.make_misfits_for_sources(ksources,
                                                  show_progress=False)
                    t1 = time.time()
                    if temperature == 'hot':
                        dur_kiwi = t1 - t0

                print 'pyrocko %-5s %5.2fs  %5.1fx' % (sourcetype, dur_pyrocko,
                                                       1.0)
                print 'kiwi    %-5s %5.2fs  %5.1fx' % (sourcetype, dur_kiwi,
                                                       dur_pyrocko / dur_kiwi)

        finally:
            seis.close()
            del seis


if __name__ == '__main__':
    util.setup_logging('test_gf_scenarios', 'warning')
    unittest.main()
Exemple #41
0
        engine = gf.LocalEngine(store_dirs=[store_dir])
        trs2 = engine.process(source, targets).pyrocko_traces()
        for tr in trs2:
            tr.snap(interpolate=True)
            tr.lowpass(4, 0.05)
            tr.highpass(4, 0.01)

        def g(trs, cha):
            for tr in trs:
                if tr.channel == cha:
                    return tr

        for cha in 'rtz':
            t1 = g(trs, cha)
            t2 = g(trs2, cha)
            tmin = max(t1.tmin, t2.tmin)
            tmax = min(t1.tmax, t2.tmax)
            t1.chop(tmin, tmax)
            t2.chop(tmin, tmax)
            d = 2.0 * num.sum((t1.ydata - t2.ydata)**2) / \
                (num.sum(t1.ydata**2) + num.sum(t2.ydata**2))

            assert d < 0.05

        # trace.snuffle(trs+trs2)

if __name__ == '__main__':
    util.setup_logging('test_gf_qseis', 'warning')
    unittest.main()
Exemple #42
0
            beachball.plot_beachball_mpl_construction(mt,
                                                      axes4,
                                                      show='patches')
            beachball.plot_beachball_mpl_construction(mt, axes5, show='lines')

            if mopad:
                try:
                    mop_mt = mopad.MomentTensor(M=mt.m6())
                    mop_beach = mopad.BeachBall(mop_mt)
                    kwargs = dict(plot_projection='lambert',
                                  plot_nodalline_width=2,
                                  plot_faultplane_width=2,
                                  plot_outerline_width=2)

                    mop_beach.ploBB(kwargs, ax=axes3)

                except Exception:
                    print(
                        'mopad failed (maybe patched mopad version is needed')

            fig.canvas.draw()

        if nx == 1:
            plt.show()


if __name__ == "__main__":
    util.setup_logging('test_beachball', 'warning')
    unittest.main()
Exemple #43
0
        for tr in traces.values():
            yield tr


def detect(first512):
    # does not work properly, produces too many false positives
    # difficult to improve due to the very compact GCF header
    try:
        if len(first512) < 512:
            return False

        f = StringIO(first512)
        read_header(f)
        return True

    except:
        return False


if __name__ == '__main__':
    from pyrocko import util
    util.setup_logging('warn')

    all_traces = []
    for fn in sys.argv[1:]:
        if detect(open(fn).read(512)):
            print fn
            all_traces.extend(iload(fn))

    trace.snuffle(all_traces)
Exemple #44
0
                                 response=cr.response)

            stations[net, sta].channel_list.append(channel)
        else:
            logger.warn('no station information for %s.%s.%s' %
                        (net, sta, loc))

    for station in stations.values():
        station.channel_list.sort(key=lambda c: (c.location_code, c.code))

    return fs.FDSNStationXML(
        source='Converted from Pyrocko stations file and RESP information',
        created=time.time(),
        network_list=[networks[net_] for net_ in sorted(networks.keys())])


if __name__ == '__main__':
    import sys
    from pyrocko import model

    util.setup_logging(__name__)

    if len(sys.argv) < 2:
        sys.exit('usage: python -m pyrocko.station.resp <stations> <resp> ...')

    stations = model.load_stations(sys.argv[1])

    sxml = make_stationxml(stations, iload(sys.argv[2:]))

    print sxml.dump_xml()
                        rc[i][1].min(), rc[i][1].max()))
                    print('irecord_p: {0:>7}, {1:>7}'.format(
                        rp[i][1].min(), rp[i][1].max()))

                if False:
                    print('weights_c: {0:>7}, {1:>7}'.format(
                        rc[i][0].min(), rc[i][0].max()))
                    print('weights_p: {0:>7}, {1:>7}'.format(
                        rp[i][0].min(), rp[i][0].max()))

        '''
        Testing loop
        '''
        dims = [2*km, 5*km, 8*km, 16*km]
        ntargets = [10, 100, 1000]

        dims = [16*km]
        ntargets = [1000]
        store = self.dummy_store()
        store.open()

        for interpolation in ['multilinear', 'nearest_neighbor']:
            for d in dims:
                for nt in ntargets:
                    test_weights_bench(store, d, nt, interpolation)


if __name__ == '__main__':
    util.setup_logging('test_gf', 'warning')
    unittest.main(defaultTest='GFBenchmarkTest.test_sum_benchmark')
Exemple #46
0
from pyrocko import gse, io, util

util.setup_logging('test_gse', 'debug')

for gse in gse.readgse('test.gse'):
    print gse
    tr = gse.waveforms[0].trace()
    io.save([tr], 'aa.mseed')
Exemple #47
0
import unittest
from pyrocko import geonames, util


class GeonamesTestCase(unittest.TestCase):

    def test_geonames(self):

        cities = geonames.get_cities(53.6, 10.0, 100e3, 200000)
        assert sorted(c.asciiname for c in cities) == \
            ['Bremen', 'Hamburg', 'Kiel', 'Luebeck']


if __name__ == "__main__":
    util.setup_logging('test_geonames', 'warning')
    unittest.main()
Exemple #48
0
            if level.vmin < 0.:
                level.vmin = 0.

            levels.append(level)

    combi = CPT(color_below=wet.color_below,
                color_above=dry.color_above,
                color_nan=dry.color_nan,
                levels=levels)

    return combi


if __name__ == '__main__':
    from pyrocko import util
    util.setup_logging('pyrocko.automap', 'info')

    import sys
    if len(sys.argv) == 2:

        n = int(sys.argv[1])

    for i in range(n):
        m = Map(lat=rand(-60., 60.),
                lon=rand(-180., 180.),
                radius=math.exp(rand(math.log(500 * km), math.log(3000 * km))),
                width=30.,
                height=30.,
                show_grid=True,
                show_topo=True,
                color_dry=(238, 236, 230),
Exemple #49
0
        except ExternalProgramMissing as e:
            raise unittest.SkipTest(str(e))

        except ImportError as e:
            raise unittest.SkipTest(str(e))

        except topo.AuthenticationRequired as e:
            raise unittest.SkipTest('cannot download topo data (no auth credentials)')

        except Exception as e:
            raise e

    f.__name__ = 'test_example_' + test_name

    return f


for fn in sorted(example_files):
    test_name = op.splitext(op.split(fn)[-1])[0]
    setattr(
        ExamplesTestCase,
        'test_example_' + test_name,
        _make_function(test_name, fn))


if __name__ == '__main__':
    util.setup_logging('test_examples', 'warning')
    common.matplotlib_use_agg()
    unittest.main()
Exemple #50
0
        assert abs(rays2[0].t - 915.9) < 0.1

    def test_path(self):
        mod = cake.load_model()
        phase = cake.PhaseDef('P')
        ray = mod.arrivals(phases=[phase], distances=[70.], zstart=100.)

        z, x, t = ray[0].zxt_path_subdivided()
        assert z[0].size == 681

    def test_to_phase_defs(self):
        pdefs = cake.to_phase_defs(['p,P', cake.PhaseDef('PP')])
        assert len(pdefs) == 3
        for pdef in pdefs:
            assert isinstance(pdef, cake.PhaseDef)

        pdefs = cake.to_phase_defs(cake.PhaseDef('PP'))
        assert len(pdefs) == 1
        for pdef in pdefs:
            assert isinstance(pdef, cake.PhaseDef)

        pdefs = cake.to_phase_defs('P,p')
        assert len(pdefs) == 2
        for pdef in pdefs:
            assert isinstance(pdef, cake.PhaseDef)


if __name__ == "__main__":
    util.setup_logging('test_cake', 'warning')
    unittest.main()
Exemple #51
0
  2.12669298e-02  5.21898977e-02 -6.61517353e-03 -8.83535221e-02 -3.66062373e-02
  1.86273292e-01  4.03764486e-01
'''  # noqa

        s2 = ims.write_string(ims.iload_string(s))
        for a, b in zip(s.strip().splitlines(), s2.strip().splitlines()):
            if a != b:
                print a
                print b
                print

        assert s.strip() == s2.strip()

    def test_ref_example11(self):

        s = '''
DATA_TYPE OUTAGE GSE2.1
Report period from 1994/12/24 00:00:00.000 to 1994/12/25 12:00:00.000
NET       Sta  Chan Aux      Start Date Time          End Date Time        Duration Comment
IDC_SEIS  APL   shz      1994/12/24 08:13:05.000 1994/12/24 08:14:10.000     65.000
IDC_SEIS  APL   shn      1994/12/25 10:00:00.000 1994/12/25 10:00:00.030      0.030
'''  # noqa

        s2 = ims.write_string(ims.iload_string(s))
        assert s.strip() == s2.strip()


if __name__ == "__main__":
    util.setup_logging('test_ims', 'warning')
    unittest.main()
Exemple #52
0
from beat.sampler import choose_proposal, available_proposals
from beat.sampler.base import multivariate_proposals

from pyrocko import util
import numpy as num

logger = logging.getLogger('test_proposals')


class TestProposals(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)
        self.draws = 10

    def test_proposals(self):

        for proposal in available_proposals():
            if proposal in multivariate_proposals:
                scale = num.eye(2) * 0.5
            else:
                scale = 1

            draw = choose_proposal(proposal, scale=scale)
            print(proposal, draw(self.draws))


if __name__ == '__main__':

    util.setup_logging('test_proposals', 'info')
    unittest.main()
                shift=float(shifts[ista, 1]),
                sigma=float(sigma[ista, 1]))
            up = model.gnss.GNSSComponent(
                shift=float(shifts[ista, 2]),
                sigma=float(sigma[ista, 2]))

            station = model.gnss.GNSSStation(
                lat=float(lats[ista]),
                lon=float(lons[ista]),
                north=north,
                east=east,
                up=up)

            campaign.add_station(station)

        campaign.dump(filename=fn)

        campaign2 = load(filename=fn)

        s1 = campaign.stations[0]

        s_add = s1.north + s1.north
        assert s_add.shift == (s1.north.shift + s1.north.shift)

        assert len(campaign.stations) == len(campaign2.stations)


if __name__ == "__main__":
    util.setup_logging('test_trace', 'warning')
    unittest.main()
        except example.util.DownloadError:
            raise unittest.SkipTest('could not download required data file')

        except ExternalProgramMissing as e:
            raise unittest.SkipTest(str(e))

        except ImportError as e:
            raise unittest.SkipTest(str(e))

        except topo.AuthenticationRequired as e:
            raise unittest.SkipTest(
                'cannot download topo data (no auth credentials)')

        except Exception as e:
            raise e

    f.__name__ = 'test_example_' + test_name

    return f


for fn in sorted(example_files):
    test_name = op.splitext(op.split(fn)[-1])[0]
    setattr(ExamplesTestCase, 'test_example_' + test_name,
            _make_function(test_name, fn))

if __name__ == '__main__':
    util.setup_logging('test_examples', 'warning')
    common.matplotlib_use_agg()
    unittest.main()
Exemple #55
0
            
        s = 0
        for traces in p.chopper(tmin=None, tmax=p.tmax+1., tinc=122. ): #tpad=10.):
            for trace in traces:
                s += num.sum(trace.ydata)
        
        assert s == nfiles*nsamples

        for fn in filenames:
            os.utime(fn, None)
        
        p.reload_modified()

        pile.get_cache(cachedir).clean()
        shutil.rmtree(datadir)
    
    def testMemTracesFile(self):
        tr = trace.Trace(ydata=num.arange(100,dtype=num.float))
        
        f = pile.MemTracesFile(None,[tr])
        p = pile.Pile()
        p.add_file(f)
        for tr in p.iter_all(include_last=True):
            assert numeq(tr.ydata, num.arange(100, dtype=num.float), 0.001)
        
        
if __name__ == "__main__":
    util.setup_logging('test_pile', 'warning')
    unittest.main()

Exemple #56
0
from matplotlib import pyplot as plt
import unittest
import logging
from time import time

logger = logging.getLogger('test_covariance')


class TestUtility(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)

    def test_non_toeplitz(self):

        ws = 500
        a = num.random.normal(scale=2, size=ws)
        cov = non_toeplitz_covariance(a, window_size=ws / 5)
        d = num.diag(cov)

        print d.mean()
        fig, axs = plt.subplots(1, 2)
        im = axs[0].matshow(cov)
        axs[1].plot(d)
        plt.colorbar(im)
        plt.show()


if __name__ == '__main__':
    util.setup_logging('test_covariance', 'warning')
    unittest.main()
#        levels2d = num.linspace(-uz2d_absmax, uz2d_absmax, 21)

#        from matplotlib import pyplot as plt

#        fontsize = 10.
#        plot.mpl_init(fontsize=fontsize)

#        cmap = plt.cm.get_cmap('coolwarm')
#        fig = plt.figure(figsize=plot.mpl_papersize('a4', 'landscape'))
#        plot.mpl_margins(fig, w=14., h=6., units=fontsize)

#        axes1 = fig.add_subplot(1, 2, 1, aspect=1.0)
#        cs1 = axes1.contourf(
#            easts / km, norths / km, uz, levels=levels, cmap=cmap)
#        plt.colorbar(cs1)

#        axes2 = fig.add_subplot(1, 2, 2, aspect=1.0)
#        cs2 = axes2.contourf(
#            easts / km, norths / km, uz2d, levels=levels2d, cmap=cmap)
#        plt.colorbar(cs2)

#        axes1.set_xlabel('Easting [km]')
#        axes1.set_ylabel('Northing [km]')

#        fig.savefig('staticGFvs2d_Afmu_diff.pdf')


if __name__ == '__main__':
    util.setup_logging('test_gf_psgrn_pscmp', 'warning')
    unittest.main()
logger = logging.getLogger('pyrocko.test.test_crust2x2')


class Crust2x2TestCase(unittest.TestCase):

    def setUp(self):
        self.tmpdir = mkdtemp('pyrocko.crust2x2')
        self.db = crust2x2.Crust2()

    def tearDown(self):
        shutil.rmtree(self.tmpdir)

    def test_crust2(self):
        nprofiles = 25
        lons = num.random.randint(-180, 180, nprofiles)
        lats = num.random.randint(-90, 90, nprofiles)
        for i in range(nprofiles):
            self.db.get_profile(lats[i], lons[i])

    def test_profiles(self):
        p = self.db.get_profile(25, 30)
        p.elevation()
        p.get_layer(1)
        p.get_weeded()
        p.averages()


if __name__ == "__main__":
    util.setup_logging('test_crust2x2', 'info')
    unittest.main()
Exemple #59
0
        assert m1.magnitude == mag

        want_mag = 3.5
        m1.magnitude = want_mag
        mom = magnitude_to_moment(want_mag)
        assert m1.moment == mom

    def testKagan(self):
        eps = 0.01
        for _ in xrange(500):
            mt1 = MomentTensor.random_mt(magnitude=-1.0)
            assert 0.0 == kagan_angle(mt1, mt1)

            mt1 = MomentTensor.random_dc(magnitude=-1.0)
            assert 0.0 == kagan_angle(mt1, mt1)

            angle = random.random() * 90.0

            rot = rotation_from_angle_and_axis(angle, random_axis())

            mrot = rot.T * mt1.m() * rot
            mt2 = MomentTensor(m=mrot)
            angle2 = kagan_angle(mt1, mt2)

            assert abs(angle - angle2) < eps


if __name__ == "__main__":
    util.setup_logging("test_moment_tensor", "warning")
    unittest.main()
Exemple #60
0
            beachball.plot_beachball_mpl_construction(
                mt, axes4, show='patches')
            beachball.plot_beachball_mpl_construction(
                mt, axes5, show='lines')

            if mopad:
                try:
                    mop_mt = mopad.MomentTensor(M=mt.m6())
                    mop_beach = mopad.BeachBall(mop_mt)
                    kwargs = dict(
                        plot_projection='lambert',
                        plot_nodalline_width=2,
                        plot_faultplane_width=2,
                        plot_outerline_width=2)

                    mop_beach.ploBB(kwargs, ax=axes3)

                except:
                    print 'mopad failed (maybe patched mopad version is needed'

            fig.canvas.draw()

        if nx == 1:
            plt.show()


if __name__ == "__main__":
    util.setup_logging('test_moment_tensor', 'warning')
    unittest.main()