Esempio n. 1
0
    def post_process(self, engine, source, statics):
        campaign = gnss.GNSSCampaign()

        for ista in range(self.ntargets):
            north = gnss.GNSSComponent(
                shift=float(statics['displacement.n'][ista]))
            east = gnss.GNSSComponent(
                shift=float(statics['displacement.e'][ista]))
            up = gnss.GNSSComponent(
                shift=-float(statics['displacement.d'][ista]))

            coords = self.coords5
            station = gnss.GNSSStation(
                lat=float(coords[ista, 0]),
                lon=float(coords[ista, 1]),
                east_shift=float(coords[ista, 2]),
                north_shift=float(coords[ista, 3]),
                elevation=float(coords[ista, 4]),
                north=north,
                east=east,
                up=up)

            campaign.add_station(station)

        return meta.GNSSCampaignResult(result=statics, campaign=campaign)
Esempio n. 2
0
def load_ascii_gnss_globk(filedir,
                          filename,
                          components=['east', 'north', 'up']):
    """
    Load ascii file columns containing:
    station name, Lon, Lat, ve, vn, vu, sigma_ve, sigma_vn, sigma_vu
    location [decimal deg]
    measurement unit [mm/yr]

    Returns
    -------
    :class:`pyrocko.model.gnss.GNSSCampaign`
    """
    from pyrocko.model import gnss

    filepath = os.path.join(filedir, filename)
    skiprows = 3
    if os.path.exists(filepath):
        names = num.loadtxt(filepath,
                            skiprows=skiprows,
                            usecols=[12],
                            dtype='str')
        d = num.loadtxt(filepath,
                        skiprows=skiprows,
                        usecols=range(12),
                        dtype='float')
    elif len(os.path.splitext(filepath)[1]) == 0:
        logger.info('File %s is not an ascii text file!' % filepath)
        return
    else:
        raise ImportError('Did not find data under: %s' % filepath)

    component_to_idx_map = {'east': (2, 6), 'north': (3, 7), 'up': (9, 11)}

    # velocity_idxs = [2, 3, 9]
    # std_idxs = [6, 7, 11]

    if names.size != d.shape[0]:
        raise Exception('Number of stations and available data differs!')

    data = gnss.GNSSCampaign(name=filename)
    for i, name in enumerate(names):
        #code = str(name.split('_')[0])  # may produce duplicate sites
        code = str(name)
        gnss_station = gnss.GNSSStation(code=code,
                                        lon=float(d[i, 0]),
                                        lat=float(d[i, 1]))
        for j, comp in enumerate(components):
            vel_idx, std_idx = component_to_idx_map[comp]

            setattr(
                gnss_station, comp,
                gnss.GNSSComponent(shift=float(d[i, vel_idx] / km),
                                   sigma=float(d[i, std_idx] / km)))
        logger.debug('Loaded station %s' % gnss_station.code)
        data.add_station(gnss_station)

    return data
Esempio n. 3
0
        def plot_gnss(gnss_target, result, ifig, vertical=False):
            campaign = gnss_target.campaign
            item = PlotItem(
                name='fig_%i' % ifig,
                attributes={'targets': gnss_target.path},
                title=u'Static GNSS Surface Displacements - Campaign %s' %
                campaign.name,
                description=u'''
Static surface displacement from GNSS campaign %s (black vectors) and
displacements derived from best model (red).
''' % campaign.name)

            event = source.pyrocko_event()
            locations = campaign.stations + [event]

            lat, lon = od.geographic_midpoint_locations(locations)

            if self.radius is None:
                coords = num.array([loc.effective_latlon for loc in locations])
                radius = od.distance_accurate50m_numpy(lat[num.newaxis],
                                                       lon[num.newaxis],
                                                       coords[:, 0].max(),
                                                       coords[:, 1]).max()
                radius *= 1.1

            if radius < 30. * km:
                logger.warn('Radius of GNSS campaign %s too small, defaulting'
                            ' to 30 km' % campaign.name)
                radius = 30 * km

            model_camp = gnss.GNSSCampaign(stations=copy.deepcopy(
                campaign.stations),
                                           name='grond model')
            for ista, sta in enumerate(model_camp.stations):
                sta.north.shift = result.statics_syn['displacement.n'][ista]
                sta.north.sigma = 0.

                sta.east.shift = result.statics_syn['displacement.e'][ista]
                sta.east.sigma = 0.

                if sta.up:
                    sta.up.shift = -result.statics_syn['displacement.d'][ista]
                    sta.up.sigma = 0.

            m = automap.Map(width=self.size_cm[0],
                            height=self.size_cm[1],
                            lat=lat,
                            lon=lon,
                            radius=radius,
                            show_topo=self.show_topo,
                            show_grid=self.show_grid,
                            show_rivers=self.show_rivers,
                            color_wet=(216, 242, 254),
                            color_dry=(238, 236, 230))

            all_stations = campaign.stations + model_camp.stations
            offset_scale = num.zeros(len(all_stations))

            for ista, sta in enumerate(all_stations):
                for comp in sta.components.values():
                    offset_scale[ista] += comp.shift
            offset_scale = num.sqrt(offset_scale**2).max()

            m.add_gnss_campaign(campaign,
                                psxy_style={
                                    'G': 'black',
                                    'W': '0.8p,black',
                                },
                                offset_scale=offset_scale,
                                vertical=vertical)

            m.add_gnss_campaign(model_camp,
                                psxy_style={
                                    'G': 'red',
                                    'W': '0.8p,red',
                                    't': 30,
                                },
                                offset_scale=offset_scale,
                                vertical=vertical,
                                labels=False)

            if isinstance(problem, CMTProblem) \
                    or isinstance(problem, VLVDProblem):
                from pyrocko import moment_tensor
                from pyrocko.plot import gmtpy

                mt = event.moment_tensor.m_up_south_east()
                ev_lat, ev_lon = event.effective_latlon

                xx = num.trace(mt) / 3.
                mc = num.matrix([[xx, 0., 0.], [0., xx, 0.], [0., 0., xx]])
                mc = mt - mc
                mc = mc / event.moment_tensor.scalar_moment() * \
                    moment_tensor.magnitude_to_moment(5.0)
                m6 = tuple(moment_tensor.to6(mc))
                symbol_size = 20.
                m.gmt.psmeca(S='%s%g' % ('d', symbol_size / gmtpy.cm),
                             in_rows=[(ev_lon, ev_lat, 10) + m6 + (1, 0, 0)],
                             M=True,
                             *m.jxyr)

            elif isinstance(problem, RectangularProblem):
                m.gmt.psxy(in_rows=source.outline(cs='lonlat'),
                           L='+p2p,black',
                           W='1p,black',
                           G='black',
                           t=60,
                           *m.jxyr)

            elif isinstance(problem, VolumePointProblem):
                ev_lat, ev_lon = event.effective_latlon
                dV = abs(source.volume_change)
                sphere_radius = num.cbrt(dV / (4. / 3. * num.pi))

                volcanic_circle = [ev_lon, ev_lat, '%fe' % sphere_radius]
                m.gmt.psxy(S='E-',
                           in_rows=[volcanic_circle],
                           W='1p,black',
                           G='orange3',
                           *m.jxyr)

            return (item, m)
Esempio n. 4
0
from pyrocko.model import gnss, location
from pyrocko.plot.automap import Map

km = 1e3
DIST_MAX = 80. * km
RIDGECREST_EQ = location.Location(lat=35.766, lon=-117.605)
GNSS_URL = 'http://geodesy.unr.edu/news_items/20190707/ci38457511_forweb.txt'

fname = 'ci38457511_forweb.txt'
# Download the data
with open(fname, 'wb') as f:
    print('Downloading data from UNR...')
    r = requests.get(GNSS_URL)
    f.write(r.content)

campaign = gnss.GNSSCampaign(name='Ridgecrest coseismic (UNR)')
print('Loading Ridgecrest GNSS data from %s (max_dist = %.1f km)' %
      (fname, DIST_MAX / km))

# load station names and data
with open(fname, 'r') as f:
    for header in range(2):
        next(f)
    names = [line.split(' ')[0] for line in f]
gnss_data = num.loadtxt(fname, skiprows=2, usecols=(1, 2, 3, 4, 5, 6, 7, 8))

for ista, sta_data in enumerate(gnss_data):
    name = names[ista]
    lon, lat, de, dn, du, sde, sdn, sdu = map(float, sta_data)

    station = gnss.GNSSStation(code=name, lat=lat, lon=lon, elevation=0.)
Esempio n. 5
0
# K. W. Hudnut, Z. Shen, M. Murray, S. McClusky, R. King, T. Herring,
# B. Hager, Y. Feng, P. Fang, A. Donnellan, Y. Bock;
# Co-seismic displacements of the 1994 Northridge, California, earthquake.
# Bulletin of the Seismological Society of America ; 86 (1B): S19–S36. doi:

# https://pasadena.wr.usgs.gov/office/hudnut/hudnut/nr_bssa.html

mm = 1e3

fn_stations = 'GPS_Stations-Northridge-1994_Hudnut.csv'
fn_displacements = 'GPS_Data-Northridge-1994_Hudnut.csv'

get_example_data(fn_stations)
get_example_data(fn_displacements)

campaign = gnss.GNSSCampaign(name='Northridge 1994')

# Load the stations
with open(fn_stations, 'r') as f:
    for line in f:
        if line.startswith('#'):
            continue
        row = line.split(',')
        sta = gnss.GNSSStation(
            code=row[0].strip(),
            lat=float(row[1]),
            lon=float(row[2]),
            elevation=float(row[3]))
        campaign.add_station(sta)

# Load the displacements
Esempio n. 6
0
    def export(self,
               point,
               results_path,
               stage_number,
               fix_output=False,
               force=False,
               update=False):

        from pyrocko.guts import dump
        from kite.scene import Scene, UserIOWarning
        from beat.plotting import map_displacement_grid

        gc = self.config

        results = self.assemble_results(point)

        def get_filename(attr, ending='csv'):
            return os.path.join(
                results_path, '{}_{}_{}.{}'.format(
                    os.path.splitext(dataset.name)[0], attr, stage_number,
                    ending))

        # export for gnss
        for typ, config in gc.types.items():
            if 'GNSS' == typ:
                from pyrocko.model import gnss

                logger.info('Exporting GNSS data ...')
                campaigns = config.load_data(campaign=True)

                for campaign in campaigns:
                    model_camp = gnss.GNSSCampaign(
                        stations=copy.deepcopy(campaign.stations),
                        name='%s_model' % campaign.name)

                    dataset_to_result = {}
                    for dataset, result in zip(self.datasets, results):
                        if dataset.typ == 'GNSS':
                            dataset_to_result[dataset] = result

                    for dataset, result in dataset_to_result.items():
                        for ista, sta in enumerate(model_camp.stations):
                            comp = getattr(sta, dataset.component)
                            comp.shift = result.processed_syn[ista]
                            comp.sigma = 0.

                    outname = os.path.join(
                        results_path, 'gnss_synths_%i.yaml' % stage_number)

                    dump(model_camp, filename=outname)

            elif 'SAR' == typ:
                logger.info('Exporting SAR data ...')
                for dataset, result in zip(self.datasets, results):
                    if dataset.typ == 'SAR':
                        try:
                            scene_path = os.path.join(config.datadir,
                                                      dataset.name)
                            logger.info(
                                'Loading full resolution kite scene: %s' %
                                scene_path)
                            scene = Scene.load(scene_path)
                        except UserIOWarning:
                            logger.warning('Full resolution data could not be'
                                           ' loaded! Skipping ...')
                            continue

                        for attr in [
                                'processed_obs', 'processed_syn',
                                'processed_res'
                        ]:

                            filename = get_filename(attr, ending='csv')
                            displacements = getattr(result, attr)
                            dataset.export_to_csv(filename, displacements)
                            logger.info('Stored CSV file to: %s' % filename)

                            filename = get_filename(attr, ending='yml')
                            vals = map_displacement_grid(displacements, scene)
                            scene.displacement = vals
                            scene.save(filename)
                            logger.info('Stored kite scene to: %s' % filename)
Esempio n. 7
0
        def plot_gnss(gnss_target, result, ifig, vertical=False):
            campaign = gnss_target.campaign
            item = PlotItem(
                name='fig_%i' % ifig,
                attributes={'targets': gnss_target.path},
                title=u'Static GNSS Surface Displacements - Campaign %s' %
                campaign.name,
                description=u'Static surface displacement from GNSS campaign '
                u'%s (black vectors) and displacements derived '
                u'from best rupture model (red).' % campaign.name)

            lat, lon = campaign.get_center_latlon()

            if self.radius is None:
                radius = campaign.get_radius()

            if radius == 0.:
                logger.warn('Radius of GNSS campaign %s too small, defaulting'
                            ' to 30 km' % campaign.name)
                radius = 30 * km

            model_camp = gnss.GNSSCampaign(stations=copy.deepcopy(
                campaign.stations),
                                           name='grond model')
            for ista, sta in enumerate(model_camp.stations):
                sta.north.shift = result.statics_syn['displacement.n'][ista]
                sta.north.sigma = 0.

                sta.east.shift = result.statics_syn['displacement.e'][ista]
                sta.east.sigma = 0.

                sta.up.shift = -result.statics_syn['displacement.d'][ista]
                sta.up.sigma = 0.

            m = automap.Map(width=self.size_cm[0],
                            height=self.size_cm[1],
                            lat=lat,
                            lon=lon,
                            radius=radius,
                            show_topo=self.show_topo,
                            show_grid=self.show_grid,
                            show_rivers=self.show_rivers,
                            color_wet=(216, 242, 254),
                            color_dry=(238, 236, 230))

            if vertical:
                m.add_gnss_campaign(campaign,
                                    psxy_style={
                                        'G': 'black',
                                        'W': '0.8p,black',
                                    },
                                    vertical=True)

                m.add_gnss_campaign(model_camp,
                                    psxy_style={
                                        'G': 'red',
                                        'W': '0.8p,red',
                                        't': 30,
                                    },
                                    vertical=True,
                                    labels=False)
            else:
                m.add_gnss_campaign(campaign,
                                    psxy_style={
                                        'G': 'black',
                                        'W': '0.8p,black',
                                    })

                m.add_gnss_campaign(model_camp,
                                    psxy_style={
                                        'G': 'red',
                                        'W': '0.8p,red',
                                        't': 30,
                                    },
                                    labels=False)

            if isinstance(problem, CMTProblem):
                from pyrocko import moment_tensor
                from pyrocko.plot import gmtpy

                event = source.pyrocko_event()
                mt = event.moment_tensor.m_up_south_east()

                xx = num.trace(mt) / 3.
                mc = num.matrix([[xx, 0., 0.], [0., xx, 0.], [0., 0., xx]])
                mc = mt - mc
                mc = mc / event.moment_tensor.scalar_moment() * \
                    moment_tensor.magnitude_to_moment(5.0)
                m6 = tuple(moment_tensor.to6(mc))
                symbol_size = 20.
                m.gmt.psmeca(S='%s%g' % ('d', symbol_size / gmtpy.cm),
                             in_rows=[
                                 (source.lon, source.lat, 10) + m6 + (1, 0, 0)
                             ],
                             M=True,
                             *m.jxyr)

            elif isinstance(problem, RectangularProblem):
                m.gmt.psxy(in_rows=source.outline(cs='lonlat'),
                           L='+p2p,black',
                           W='1p,black',
                           G='black',
                           t=60,
                           *m.jxyr)

            return (item, m)