Пример #1
0
    def __init__(self):
        self.fname_holocene = op.join(config.config().volcanoes_dir,
                                      'smithsonian-holocene.csv')
        self.fname_pleistocene = op.join(config.config().volcanoes_dir,
                                         'smithsonian-pleistocene.csv')

        if not op.exists(self.fname_holocene) \
                or not op.exists(self.fname_pleistocene):
            self.download()

        self.volcanoes = []
        self._load_volcanoes(self.fname_holocene, VolcanoHolocene)
        self._load_volcanoes(self.fname_pleistocene, VolcanoPleistocene)
Пример #2
0
def load(zfn, fn, minpop=1000000, region=None):
    geonames_dir = config.config().geonames_dir
    filepath = op.join(geonames_dir, zfn or fn)
    if not os.path.exists(filepath):
        download_file(zfn or fn, geonames_dir)

    if region:
        w, e, s, n = positive_region(region)

    if zfn is not None:
        import zipfile
        z = zipfile.ZipFile(filepath, 'r')
        f = z.open(fn, 'r')
    else:
        z = None
        f = open(filepath, 'r')

    for line in f:
        t = line.split('\t')
        pop = int(t[14])
        if minpop <= pop:
            lat = float(t[4])
            lon = float(t[5])
            if not region or (
                    (w <= lon <= e or w <= lon + 360. <= e)
                    and (s <= lat <= n)):

                yield GeoName2(
                    t[1].decode('utf8'),
                    t[2].decode('utf8').encode('ascii', 'replace'),
                    lat, lon, pop)

    f.close()
    if z is not None:
        z.close()
Пример #3
0
def ne_to_latlon_alternative_method(lat0, lon0, north_m, east_m):
    '''Like ne_to_latlon(), but this method, although it should be numerically
    more stable, suffers problems at points which are 'across the pole' as seen
    from the carthesian origin.'''

    b = math.pi / 2. - lat0 * d2r
    a = num.sqrt(north_m**2 + east_m**2) / config().earthradius

    gamma = num.arctan2(east_m, north_m)
    alphasign = 1.
    alphasign = num.where(gamma < 0., -1., 1.)
    gamma = num.abs(gamma)

    z1 = num.cos((a - b) / 2.) * num.cos(gamma / 2.)
    n1 = num.cos((a + b) / 2.) * num.sin(gamma / 2.)
    z2 = num.sin((a - b) / 2.) * num.cos(gamma / 2.)
    n2 = num.sin((a + b) / 2.) * num.sin(gamma / 2.)
    t1 = num.arctan2(z1, n1)
    t2 = num.arctan2(z2, n2)

    alpha = t1 + t2
    beta = t1 - t2

    sin_t1 = num.sin(t1)
    sin_t2 = num.sin(t2)
    c = num.where(
        num.abs(sin_t1) > num.abs(sin_t2),
        num.arccos(z1 / sin_t1) * 2.,
        num.arcsin(z2 / sin_t2) * 2.)

    lat = r2d * (math.pi / 2. - c)
    lon = wrap(lon0 + r2d * alpha * alphasign, -180., 180.)
    return lat, lon
Пример #4
0
def make_pile( paths=None, selector=None, regex=None,
        fileformat = 'mseed',
        cachedirname=None, show_progress=True ):
    
    '''Create pile from given file and directory names.
    
    :param paths: filenames and/or directories to look for traces. If paths is 
        ``None`` ``sys.argv[1:]`` is used.
    :param selector: lambda expression taking group dict of regex match object as
        a single argument and which returns true or false to keep or reject
        a file
    :param regex: regular expression which filenames have to match
    :param fileformat: format of the files ('mseed', 'sac', 'kan', 
        'from_extension', 'try')
    :param cachedirname: loader cache is stored under this directory. It is
        created as neccessary.
    :param show_progress: show progress bar and other progress information
    '''
    if isinstance(paths, str):
        paths = [ paths ]
        
    if paths is None:
        paths = sys.argv[1:]

    if cachedirname is None:
        cachedirname = config.config().cache_dir
    
    fns = util.select_files(paths, selector, regex, show_progress=show_progress)

    cache = get_cache(cachedirname)
    p = Pile()
    p.load_files( sorted(fns), cache=cache, fileformat=fileformat, show_progress=show_progress)
    return p
Пример #5
0
    def test_markers(self):
        self.add_one_pick()
        pv = self.pile_viewer
        self.assertEqual(pv.viewer.get_active_event(), None)

        conf = config.config('snuffler')

        # test kinds and phases
        kinds = range(5)
        fkey_map = pyrocko_pile_viewer.fkey_map

        for k in kinds:
            for fkey, fkey_int in fkey_map.items():
                fkey_int += 1
                QTest.keyPress(pv, fkey)
                QTest.keyPress(pv, str(k))

                if fkey_int != 10:
                    want = conf.phase_key_mapping.get(
                        "F%s" % fkey_int, 'Undefined')
                else:
                    want = None
                m = pv.viewer.get_markers()[0]
                self.assertEqual(m.kind, k)
                if want:
                    self.assertEqual(m.get_phasename(), want)
Пример #6
0
    def __init__(
        self,
        name='PeterBird2003',
        data_dir=None,
        raw_data_url=(
            'https://mirror.pyrocko.org/peterbird.name/oldFTP/PB2002/%s'
        )):  # noqa

        if data_dir is None:
            data_dir = op.join(config.config().tectonics_dir, name)

        PlatesDataset.__init__(self,
                               name,
                               data_dir=data_dir,
                               citation=self.__citation)

        self.raw_data_url = raw_data_url

        self.filenames = [
            '2001GC000252_readme.txt', 'PB2002_boundaries.dig.txt',
            'PB2002_orogens.dig.txt', 'PB2002_plates.dig.txt',
            'PB2002_poles.dat.txt', 'PB2002_steps.dat.txt'
        ]

        self._full_names = None
Пример #7
0
def load(zfn, fn, minpop=1000000, region=None):
    geonames_dir = config.config().geonames_dir
    filepath = op.join(geonames_dir, zfn or fn)
    if not os.path.exists(filepath):
        download_file(zfn or fn, geonames_dir)

    if region:
        w, e, s, n = positive_region(region)

    if zfn is not None:
        import zipfile
        z = zipfile.ZipFile(filepath, 'r')
        f = z.open(fn, 'r')
    else:
        z = None
        f = open(filepath, 'r')

    for line in f:
        t = line.split('\t')
        pop = int(t[14])
        if minpop <= pop:
            lat = float(t[4])
            lon = float(t[5])
            if not region or ((w <= lon <= e or w <= lon + 360. <= e) and
                              (s <= lat <= n)):

                yield GeoName2(t[1].decode('utf8'),
                               t[2].decode('utf8').encode('ascii', 'replace'),
                               lat, lon, pop)

    f.close()
    if z is not None:
        z.close()
Пример #8
0
    def test_markers(self):
        self.add_one_pick()
        pv = self.pile_viewer
        self.assertEqual(pv.viewer.get_active_event(), None)

        conf = config.config('snuffler')

        # test kinds and phases
        kinds = range(5)
        fkey_map = pyrocko_pile_viewer.fkey_map

        for k in kinds:
            for fkey, fkey_int in fkey_map.items():
                fkey_int += 1
                QTest.keyPress(pv, fkey)
                QTest.keyPress(pv, str(k))

                if fkey_int != 10:
                    want = conf.phase_key_mapping.get("F%s" % fkey_int,
                                                      'Undefined')
                else:
                    want = None
                m = pv.viewer.get_markers()[0]
                self.assertEqual(m.kind, k)
                if want:
                    self.assertEqual(m.get_phasename(), want)
Пример #9
0
def ne_to_latlon_alternative_method( lat0, lon0, north_m, east_m ):

    '''Like ne_to_latlon(), but this method, although it should be numerically
    more stable, suffers problems at points which are 'across the pole' as seen
    from the carthesian origin.'''

    b = math.pi/2.-lat0*d2r
    a = num.sqrt(north_m**2+east_m**2)/config().earthradius

    
    gamma = num.arctan2(east_m,north_m)
    alphasign = 1.
    alphasign = num.where(gamma < 0., -1., 1.)
    gamma = num.abs(gamma)
    
    z1 = num.cos((a-b)/2.)*num.cos(gamma/2.)
    n1 = num.cos((a+b)/2.)*num.sin(gamma/2.)
    z2 = num.sin((a-b)/2.)*num.cos(gamma/2.)
    n2 = num.sin((a+b)/2.)*num.sin(gamma/2.)
    t1 = num.arctan2( z1,n1 )
    t2 = num.arctan2( z2,n2 )
    
    alpha = t1 + t2
    beta  = t1 - t2
    
    sin_t1 = num.sin(t1)
    sin_t2 = num.sin(t2)           
    c = num.where( num.abs(sin_t1)>num.abs(sin_t2), 
                num.arccos(z1/sin_t1)*2.,
                num.arcsin(z2/sin_t2)*2. )
            
    lat = r2d * (math.pi/2. - c)
    lon = wrap(lon0 + r2d*alpha*alphasign,-180.,180.)
    return lat, lon
Пример #10
0
    def __init__(
            self,
            name='PeterBird2003',
            data_dir=None,
            raw_data_url=('http://peterbird.name/oldFTP/PB2002/%s')):

        if data_dir is None:
            data_dir = op.join(config.config().tectonics_dir, name)

        PlatesDataset.__init__(
            self,
            name,
            data_dir=data_dir,
            citation=self.__citation)

        self.raw_data_url = raw_data_url

        self.filenames = [
            '2001GC000252_readme.txt',
            'PB2002_boundaries.dig.txt',
            'PB2002_orogens.dig.txt',
            'PB2002_plates.dig.txt',
            'PB2002_poles.dat.txt',
            'PB2002_steps.dat.txt']

        self._full_names = None
Пример #11
0
    def _getRepositoryDatabase():
        from pyrocko import config

        name = path.basename(db_url)
        data_path = path.join(config.config().crustdb_dir, name)
        if not path.exists(data_path):
            from pyrocko import util
            util.download_file(db_url, data_path, None, None)

        return data_path
Пример #12
0
    def _getRepositoryDatabase():
        from pyrocko import config

        name = path.basename(db_url)
        data_path = path.join(config.config().crustdb_dir, name)
        if not path.exists(data_path):
            from pyrocko import util
            util.download_file(db_url, data_path, None, None)

        return data_path
Пример #13
0
    def ensure_gfstores(self, interactive=False, gf_store_superdirs_extra=[]):
        if not self.stores_missing:
            return

        from pyrocko.gf import ws

        cfg = config.config()

        if len(cfg.gf_store_superdirs) == 0:
            store_dir = op.expanduser(
                op.join(config.pyrocko_dir_tmpl, 'gf_stores'))
            logger.debug('Creating default gf_store_superdirs: %s' % store_dir)

            util.ensuredir(store_dir)
            cfg.gf_store_superdirs = [store_dir]
            config.write_config(cfg)

        gf_store_superdirs = cfg.gf_store_superdirs + gf_store_superdirs_extra

        if interactive:
            print('We could not find the following Green\'s function stores:\n'
                  ' %s\n'
                  'We can try to download the stores from '
                  'http://kinherd.org into one of the following '
                  'directories.'
                  % '\n'.join(self.stores_missing))
            for idr, dr in enumerate(gf_store_superdirs):
                print(' %d. %s' % ((idr+1), dr))
            s = input('\nInto which directory should we download the GF '
                      'store(s)?\nDefault 1, (C)ancel: ')
            if s in ['c', 'C']:
                print('Canceled!')
                sys.exit(1)
            elif s == '':
                s = 0
            try:
                s = int(s)
                if s > len(gf_store_superdirs):
                    raise ValueError
            except ValueError:
                print('Invalid selection: %s' % s)
                sys.exit(1)
        else:
            s = 1

        download_dir = gf_store_superdirs[s-1]
        logger.info('Downloading Green\'s functions stores to %s'
                    % download_dir)

        oldwd = os.getcwd()
        for store in self.stores_missing:
            os.chdir(download_dir)
            ws.download_gf_store(site='kinherd', store_id=store)

        os.chdir(oldwd)
Пример #14
0
    def add_waveforms(self, paths, regex=None, fileformat='detect',
                      show_progress=False):
        cachedirname = config.config().cache_dir

        logger.debug('Selecting waveform files %s...' % quote_paths(paths))
        fns = util.select_files(paths, regex=regex,
                                show_progress=show_progress)
        cache = pile.get_cache(cachedirname)
        logger.debug('Scanning waveform files %s...' % quote_paths(paths))
        self.pile.load_files(sorted(fns), cache=cache,
                             fileformat=fileformat,
                             show_progress=show_progress)
Пример #15
0
    def _update_pile(self):
        while self._pile_update_args:
            paths, regex, fileformat, show_progress = \
                self._pile_update_args.pop(0)

            logger.debug('Loading waveform data from %s' % paths)

            cachedirname = config.config().cache_dir
            fns = util.select_files(paths, regex=regex,
                                    show_progress=show_progress)
            cache = pile.get_cache(cachedirname)
            self._pile.load_files(sorted(fns), cache=cache,
                                 fileformat=fileformat,
                                 show_progress=show_progress)
Пример #16
0
    def ensure_gfstores(self, interactive=False):
        if not self.stores_missing:
            return

        from pyrocko.gf import ws

        cfg = config.config()

        engine = self.get_engine()

        gf_store_superdirs = engine.store_superdirs

        if interactive:
            print('We could not find the following Green\'s function stores:\n'
                  '%s\n'
                  'We can try to download the stores from '
                  'http://kinherd.org into one of the following '
                  'directories.'
                  % '\n'.join('  ' + s for s in self.stores_missing))
            for idr, dr in enumerate(gf_store_superdirs):
                print(' %d. %s' % ((idr+1), dr))
            s = input('\nInto which directory should we download the GF '
                      'store(s)?\nDefault 1, (C)ancel: ')
            if s in ['c', 'C']:
                print('Canceled!')
                sys.exit(1)
            elif s == '':
                s = 0
            try:
                s = int(s)
                if s > len(gf_store_superdirs):
                    raise ValueError
            except ValueError:
                print('Invalid selection: %s' % s)
                sys.exit(1)
        else:
            s = 1

        download_dir = gf_store_superdirs[s-1]
        util.ensuredir(download_dir)
        logger.info('Downloading Green\'s functions stores to %s'
                    % download_dir)

        oldwd = os.getcwd()
        for store in self.stores_missing:
            os.chdir(download_dir)
            ws.download_gf_store(site='kinherd', store_id=store)

        os.chdir(oldwd)
Пример #17
0
    def ensure_gfstores(self, interactive=False):
        if not self.stores_missing:
            return

        from pyrocko.gf import ws

        cfg = config.config()

        engine = self.get_engine()

        gf_store_superdirs = engine.store_superdirs

        if interactive:
            print('We could not find the following Green\'s function stores:\n'
                  '%s\n'
                  'We can try to download the stores from '
                  'http://kinherd.org into one of the following '
                  'directories.' % '\n'.join('  ' + s
                                             for s in self.stores_missing))
            for idr, dr in enumerate(gf_store_superdirs):
                print(' %d. %s' % ((idr + 1), dr))
            s = input('\nInto which directory should we download the GF '
                      'store(s)?\nDefault 1, (C)ancel: ')
            if s in ['c', 'C']:
                print('Canceled!')
                sys.exit(1)
            elif s == '':
                s = 0
            try:
                s = int(s)
                if s > len(gf_store_superdirs):
                    raise ValueError
            except ValueError:
                print('Invalid selection: %s' % s)
                sys.exit(1)
        else:
            s = 1

        download_dir = gf_store_superdirs[s - 1]
        util.ensuredir(download_dir)
        logger.info('Downloading Green\'s functions stores to %s' %
                    download_dir)

        oldwd = os.getcwd()
        for store in self.stores_missing:
            os.chdir(download_dir)
            ws.download_gf_store(site='kinherd', store_id=store)

        os.chdir(oldwd)
Пример #18
0
def ne_to_latlon(lat0, lon0, north_m, east_m):
    '''Transform local carthesian coordinates to latitude and longitude.
    
    lat0, lon0:      Origin of the carthesian coordinate system.
    north_m, east_m: 1D numpy arrays with distances from origin in meters.
    
    Returns: lat, lon: 1D numpy arrays with latitudes and longitudes
    
    The projection used preserves the azimuths of the input points.
    '''

    a = num.sqrt(north_m**2 + east_m**2) / config().earthradius
    gamma = num.arctan2(east_m, north_m)

    return azidist_to_latlon_rad(lat0, lon0, gamma, a)
Пример #19
0
def ne_to_latlon( lat0, lon0, north_m, east_m ):
    '''Transform local carthesian coordinates to latitude and longitude.
    
    lat0, lon0:      Origin of the carthesian coordinate system.
    north_m, east_m: 1D numpy arrays with distances from origin in meters.
    
    Returns: lat, lon: 1D numpy arrays with latitudes and longitudes
    
    The projection used preserves the azimuths of the input points.
    '''
    
    a = num.sqrt(north_m**2+east_m**2)/config().earthradius
    gamma = num.arctan2(east_m,north_m)
    
    return azidist_to_latlon_rad( lat0, lon0, gamma, a)
Пример #20
0
    def __init__(self,
                 name='GSRM1.2',
                 data_dir=None,
                 raw_data_url=('http://gsrm.unavco.org/model/files/1.2/%s')):

        if data_dir is None:
            data_dir = op.join(config.config().tectonics_dir, name)

        StrainRateDataset.__init__(self,
                                   name,
                                   data_dir=data_dir,
                                   citation=self.__citation)

        self.raw_data_url = raw_data_url
        self._full_names = None
        self._names = None
Пример #21
0
    def __init__(
            self,
            name='GSRM1.2',
            data_dir=None,
            raw_data_url=('http://gsrm.unavco.org/model/files/1.2/%s')):

        if data_dir is None:
            data_dir = op.join(config.config().tectonics_dir, name)

        StrainRateDataset.__init__(
            self,
            name,
            data_dir=data_dir,
            citation=self.__citation)

        self.raw_data_url = raw_data_url
        self._full_names = None
        self._names = None
Пример #22
0
def read_leap_seconds2():
    from pyrocko import config
    conf = config.config()
    fn = conf.leapseconds_path
    url = conf.leapseconds_url
    try:
        return parse_leap_seconds_list(fn)

    except LeapSecondsOutdated:
        try:
            logger.info('updating leap seconds list...')
            download_file(url, fn)

        except Exception:
            raise LeapSecondsError(
                'cannot download leap seconds list from %s to %s' % (url, fn))

        return parse_leap_seconds_list(fn)
Пример #23
0
def read_leap_seconds2():
    from pyrocko import config
    conf = config.config()
    fn = conf.leapseconds_path
    url = conf.leapseconds_url
    try:
        return parse_leap_seconds_list(fn)

    except LeapSecondsOutdated:
        try:
            logger.info('updating leap seconds list...')
            download_file(url, fn)

        except Exception:
            raise LeapSecondsError(
                'cannot download leap seconds list from %s to %s' (url, fn))

        return parse_leap_seconds_list(fn)
Пример #24
0
    def __init__(
            self,
            name='SRTMGL3',
            data_dir=op.join(op.dirname(__file__), 'data', 'SRTMGL3'),
            raw_data_url='https://e4ftl01.cr.usgs.gov/MEASURES/SRTMGL3.003/'
                         '2000.02.11'):

        dataset.TiledGlobalDataset.__init__(
            self,
            name,
            432001, 216001, 1201, 1201,
            num.dtype('>i2'),
            data_dir=data_dir,
            citation=citation,
            region=(-180., 180., -60., 60.))

        self.raw_data_url = raw_data_url
        self._available_tilenames = None
        self.config = config.config()
Пример #25
0
    def __init__(self,
                 name='SRTMGL3',
                 data_dir=op.join(op.dirname(__file__), 'data', 'SRTMGL3'),
                 raw_data_url='https://e4ftl01.cr.usgs.gov/SRTM/SRTMGL3.003/'
                 '2000.02.11'):

        dataset.TiledGlobalDataset.__init__(self,
                                            name,
                                            432001,
                                            216001,
                                            1201,
                                            1201,
                                            num.dtype('>i2'),
                                            data_dir=data_dir,
                                            citation=citation,
                                            region=(-180., 180., -60., 60.))

        self.raw_data_url = raw_data_url
        self._available_tilenames = None
        self.config = config.config()
Пример #26
0
def ne_to_latlon(lat0, lon0, north_m, east_m):
    '''Transform local cartesian coordinates to latitude and longitude.

    From east and north coordinates (``x`` and ``y`` coordinate
    :py:class:`numpy.ndarray`)  relative to a reference differences in
    longitude and latitude are calculated, which are effectively changes in
    azimuth and distance, respectively:

    .. math::

        \\text{distance change:}\; \Delta {\\bf{a}} &= \sqrt{{\\bf{y}}^2 + \
                                           {\\bf{x}}^2 }/ \mathrm{R_E},

        \\text{azimuth change:}\; \Delta \\bf{\gamma} &= \\arctan( \\bf{x}  \
                                                         / \\bf{y}).

    The projection used preserves the azimuths of the input points.

    :param lat0: Latitude origin of the cartesian coordinate system.
    :param lon0: Longitude origin of the cartesian coordinate system.
    :param north_m: Northing distances from origin in meters.
    :param east_m: Easting distances from origin in meters.
    :type north_m: :py:class:`numpy.ndarray`, ``(N)``
    :type east_m: :py:class:`numpy.ndarray`, ``(N)``
    :type lat0: float
    :type lon0: float

    :return: Array with latitudes and longitudes
    :rtype: :py:class:`numpy.ndarray`, ``(2xN)``

    '''

    a = num.sqrt(north_m**2 + east_m**2) / config().earthradius
    gamma = num.arctan2(east_m, north_m)

    return azidist_to_latlon_rad(lat0, lon0, gamma, a)
Пример #27
0
def have_srtm_credentials():
    if config.config().earthdata_credentials is None:
        return False
    return True
Пример #28
0
def ne_to_latlon_alternative_method(lat0, lon0, north_m, east_m):
    '''Transform local cartesian coordinates to latitude and longitude.

    Like :py:func:`pyrocko.orthodrome.ne_to_latlon`,
    but this method (implementation below), although it should be numerically
    more stable, suffers problems at points which are *across the pole*
    as seen from the cartesian origin.

    .. math::

        \\text{distance change:}\; \Delta {{\\bf a}_i} &=\sqrt{{\\bf{y}}^2_i +
                                        {\\bf{x}}^2_i }/ \mathrm{R_E},\\\\
        \\text{azimuth change:}\; \Delta {\\bf \gamma}_i &=
                                        \\arctan( {\\bf x}_i {\\bf y}_i). \\\\
        \mathrm{b} &= \\frac{\pi}{2} -\\frac{\pi}{180} \;\mathrm{lat_0}\\\\

    .. math::

        {{\\bf z}_1}_i &= \\cos{\\left( \\frac{\Delta {\\bf a}_i - \
                            \\mathrm{b}}{2} \\right)} \
                            \\cos {\\left( \\frac{|\gamma_i|}{2} \\right) }\\\\
        {{\\bf n}_1}_i &= \\cos{\\left( \\frac{\Delta {\\bf a}_i + \
                            \\mathrm{b}}{2} \\right)}\
                            \\sin {\\left( \\frac{|\gamma_i|}{2} \\right) }\\\\
        {{\\bf z}_2}_i &= \\sin{\\left( \\frac{\Delta {\\bf a}_i - \
                            \\mathrm{b}}{2} \\right)}\
                            \\cos {\\left( \\frac{|\gamma_i|}{2} \\right) }\\\\
        {{\\bf n}_2}_i &= \\sin{\\left( \\frac{\Delta {\\bf a}_i + \
                            \\mathrm{b}}{2} \\right)}\
                            \\sin {\\left( \\frac{|\gamma_i|}{2} \\right) }\\\\
        {{\\bf t}_1}_i &= \\arctan{\\left( \\frac{{{\\bf z}_1}_i} \
                                    {{{\\bf n}_1}_i} \\right) }\\\\
        {{\\bf t}_2}_i &= \\arctan{\\left( \\frac{{{\\bf z}_2}_i} \
                                    {{{\\bf n}_2}_i} \\right) } \\\\[0.5cm]
        c &= \\begin{cases}
              2 \cdot \\arccos \\left( {{\\bf z}_1}_i / \\sin({{\\bf t}_1}_i) \
                              \\right),\; \\text{if } \
                              |\\sin({{\\bf t}_1}_i)| > \
                                |\\sin({{\\bf t}_2}_i)|,\; \\text{else} \\\\
              2 \cdot \\arcsin{\\left( {{\\bf z}_2}_i / \
                                 \\sin({{\\bf t}_2}_i) \\right)}.
             \\end{cases}\\\\

    .. math::

        {\\bf {lat}}_i  &= \\frac{180}{ \pi } \\left( \\frac{\pi}{2} \
                                              - {\\bf {c}}_i \\right) \\\\
        {\\bf {lon}}_i &=  {\\bf {lon}}_0 + \\frac{180}{ \pi } \
                                      \\frac{\gamma_i}{|\gamma_i|}, \
                                     \\text{ with}\; \gamma \\in [-\pi,\pi]

    :param lat0: Latitude origin of the cartesian coordinate system.
    :param lon0: Longitude origin of the cartesian coordinate system.
    :param north_m: Northing distances from origin in meters.
    :param east_m: Easting distances from origin in meters.
    :type north_m: :py:class:`numpy.ndarray`, ``(N)``
    :type east_m: :py:class:`numpy.ndarray`, ``(N)``
    :type lat0: float
    :type lon0: float

    :return: Array with latitudes and longitudes
    :rtype: :py:class:`numpy.ndarray`, ``(2xN)``
    '''

    b = math.pi / 2. - lat0 * d2r
    a = num.sqrt(north_m**2 + east_m**2) / config().earthradius

    gamma = num.arctan2(east_m, north_m)
    alphasign = 1.
    alphasign = num.where(gamma < 0., -1., 1.)
    gamma = num.abs(gamma)

    z1 = num.cos((a - b) / 2.) * num.cos(gamma / 2.)
    n1 = num.cos((a + b) / 2.) * num.sin(gamma / 2.)
    z2 = num.sin((a - b) / 2.) * num.cos(gamma / 2.)
    n2 = num.sin((a + b) / 2.) * num.sin(gamma / 2.)
    t1 = num.arctan2(z1, n1)
    t2 = num.arctan2(z2, n2)

    alpha = t1 + t2

    sin_t1 = num.sin(t1)
    sin_t2 = num.sin(t2)
    c = num.where(
        num.abs(sin_t1) > num.abs(sin_t2),
        num.arccos(z1 / sin_t1) * 2.,
        num.arcsin(z2 / sin_t2) * 2.)

    lat = r2d * (math.pi / 2. - c)
    lon = wrap(lon0 + r2d * alpha * alphasign, -180., 180.)
    return lat, lon
Пример #29
0
import math
import os.path as op

from pyrocko import config, util
from pyrocko.topo import srtmgl3, etopo1, dataset, tile

positive_region = tile.positive_region

earthradius = 6371000.0
r2d = 180. / math.pi
d2r = 1. / r2d
km = 1000.
d2m = d2r * earthradius
m2d = 1. / d2m

topo_data_dir = config.config().topo_dir

srtmgl3 = srtmgl3.SRTMGL3(name='SRTMGL3',
                          data_dir=op.join(topo_data_dir, 'SRTMGL3'))

srtmgl3_d2 = dataset.DecimatedTiledGlobalDataset(name='SRTMGL3_D2',
                                                 base=srtmgl3,
                                                 ndeci=2,
                                                 data_dir=op.join(
                                                     topo_data_dir,
                                                     'SRTMGL3_D2'))

srtmgl3_d4 = dataset.DecimatedTiledGlobalDataset(name='SRTMGL3_D4',
                                                 base=srtmgl3_d2,
                                                 ndeci=2,
                                                 data_dir=op.join(
Пример #30
0
# The Pyrocko Developers, 21st Century
# ---|P------/S----------~Lg----------
from __future__ import absolute_import

import logging
import io
import struct
import time
import numpy as num

from os import path

from pyrocko import config, orthodrome

logger = logging.getLogger('pyrocko.dataset.gshhg')
config = config.config()

km = 1e3
micro_deg = 1e-6


class Polygon(object):
    '''Representation of a GSHHG polygon. '''
    RIVER_NOT_SET = 0

    LEVELS = ['LAND', 'LAKE', 'ISLAND_IN_LAKE', 'POND_IN_ISLAND_IN_LAKE',
              'ANTARCTIC_ICE_FRONT', 'ANTARCTIC_GROUNDING_LINE']

    SOURCE = ['CIA_WDBII', 'WVS', 'AC']

    def __init__(self, gshhg_file, offset, *attr):
Пример #31
0
    'koeri': 'http://eida-service.koeri.boun.edu.tr',
    'ethz': 'http://eida.ethz.ch',
    'icgc': 'http://ws.icgc.cat',
    'ipgp': 'http://eida.ipgp.fr',
    'ingv': 'http://webservices.ingv.it',
    'isc': 'http://www.isc.ac.uk',
    'lmu': 'http://erde.geophysik.uni-muenchen.de',
    'noa': 'http://eida.gein.noa.gr',
    'resif': 'http://ws.resif.fr',
    'usp': 'http://seisrequest.iag.usp.br',
    'niep': 'http://eida-sc3.infp.ro'
}

g_default_site = 'geofon'

if config.config().fdsn_timeout is None:
    g_timeout = 20.
else:
    g_timeout = config.config().fdsn_timeout

re_realm_from_auth_header = re.compile(r'(realm)\s*[:=]\s*"([^"]*)"?')


class CannotGetRealmFromAuthHeader(DownloadError):
    pass


class CannotGetCredentialsFromAuthRequest(DownloadError):
    pass

Пример #32
0
def have_srtm_credentials():
    if config.config().earthdata_credentials is None:
        return False
    return True
Пример #33
0
from __future__ import absolute_import

import logging
import io
import struct
import time
import numpy as num

from os import path

from pyrocko import config, orthodrome
from .util import get_download_callback

logger = logging.getLogger('pyrocko.dataset.gshhg')
config = config.config()

km = 1e3
micro_deg = 1e-6


def split_region_0_360(wesn):
    west, east, south, north = wesn
    if west < 0.:
        if east <= 0:
            return [(west + 360., east + 360., south, north)]
        else:
            return [(west + 360., 360., south, north),
                    (0., east, south, north)]
    else:
        return [wesn]
Пример #34
0
def latlondepth_to_carthesian(lat, lon, depth):
    radius = config.config().earthradius - depth
    x = radius * math.cos(d2r*lat) * math.cos(d2r*lon)
    y = radius * math.cos(d2r*lat) * math.sin(d2r*lon)
    z = radius * math.sin(d2r*lat)
    return x, y, z
Пример #35
0
def latlondepth_to_carthesian(lat, lon, depth):
    radius = config.config().earthradius - depth
    x = radius * math.cos(d2r * lat) * math.cos(d2r * lon)
    y = radius * math.cos(d2r * lat) * math.sin(d2r * lon)
    z = radius * math.sin(d2r * lat)
    return x, y, z
Пример #36
0
def srtm_credentials():
    return config.config().earthdata_credentials
Пример #37
0
import numpy as num
import logging

from pyrocko import orthodrome, util
from pyrocko import orthodrome_ext
from ..common import Benchmark
from pyrocko import config
from pyrocko import guts
from pyrocko.model.location import Location

logger = logging.getLogger('pyrocko.test.test_orthodrome')
benchmark = Benchmark()

earth_oblateness = 1. / 298.257223563
earthradius_equator = 6378.14 * 1000.
earthradius = config.config().earthradius

r2d = 180. / math.pi
d2r = 1. / r2d
km = 1000.

plot = int(os.environ.get('MPL_SHOW', 0))

assert_ae = num.testing.assert_almost_equal
assert_allclose = num.testing.assert_allclose


def random_lat(mi=-90., ma=90., rstate=None, size=None):
    if rstate is None:
        rstate = num.random
    mi_ = 0.5 * (math.sin(mi * math.pi / 180.) + 1.)
Пример #38
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)
Пример #39
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.event.Event.load_catalog(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)
Пример #40
0
    'koeri': 'http://eida-service.koeri.boun.edu.tr',
    'ethz': 'http://eida.ethz.ch',
    'icgc': 'http://ws.icgc.cat',
    'ipgp': 'http://eida.ipgp.fr',
    'ingv': 'http://webservices.ingv.it',
    'isc': 'http://www.isc.ac.uk',
    'lmu': 'http://erde.geophysik.uni-muenchen.de',
    'noa': 'http://eida.gein.noa.gr',
    'resif': 'http://ws.resif.fr',
    'usp': 'http://seisrequest.iag.usp.br',
    'niep': 'http://eida-sc3.infp.ro'
}

g_default_site = 'geofon'

if config.config().fdsn_timeout is None:
    g_timeout = 20.
else:
    g_timeout = config.config().fdsn_timeout

re_realm_from_auth_header = re.compile(r'(realm)\s*[:=]\s*"([^"]*)"?')


class CannotGetRealmFromAuthHeader(DownloadError):
    pass


class CannotGetCredentialsFromAuthRequest(DownloadError):
    pass

Пример #41
0
from .srtmgl3 import SRTMGL3, AuthenticationRequired
from .etopo1 import ETOPO1
from . import dataset, tile

__doc__ = util.parse_md(__file__)

positive_region = tile.positive_region

earthradius = 6371000.0
r2d = 180./math.pi
d2r = 1./r2d
km = 1000.
d2m = d2r*earthradius
m2d = 1./d2m

topo_data_dir = config.config().topo_dir

srtmgl3 = SRTMGL3(
    name='SRTMGL3',
    data_dir=op.join(topo_data_dir, 'SRTMGL3'))

srtmgl3_d2 = dataset.DecimatedTiledGlobalDataset(
    name='SRTMGL3_D2',
    base=srtmgl3,
    ndeci=2,
    data_dir=op.join(topo_data_dir, 'SRTMGL3_D2'))

srtmgl3_d4 = dataset.DecimatedTiledGlobalDataset(
    name='SRTMGL3_D4',
    base=srtmgl3_d2,
    ndeci=2,
Пример #42
0
import math
import numpy as num
from pyrocko.config import config

d2r = math.pi/180.
r2d = 1./d2r
earth_oblateness = 1./298.257223563
earthradius_equator = 6378.14 * 1000.
earthradius = config().earthradius
d2m = earthradius_equator*math.pi/180.
m2d = 1./d2m

class Loc:
    def __init__(self, lat, lon):
        self.lat = lat
        self.lon = lon

def clip(x, mi, ma):
    return num.minimum(num.maximum(mi,x),ma)
        
def wrap(x, mi, ma):
    return x - num.floor((x-mi)/(ma-mi)) * (ma-mi)

def cosdelta(a, b):
    return min(1.0, math.sin(a.lat*d2r) * math.sin(b.lat*d2r) + math.cos(a.lat*d2r) * math.cos(b.lat*d2r) * math.cos(d2r*(b.lon-a.lon)))
    
def cosdelta_numpy(a_lats, a_lons, b_lats, b_lons):
    return num.minimum(1.0, num.sin(a_lats*d2r) * num.sin(b_lats*d2r) + num.cos(a_lats*d2r) * num.cos(b_lats*d2r) * num.cos(d2r*(b_lons-a_lons)))

def azimuth(a, b):
    return r2d*math.atan2( math.cos(a.lat*d2r) * math.cos(b.lat*d2r) * math.sin(d2r*(b.lon-a.lon)),