Exemplo n.º 1
0
def stamps2kite(dirname='.',
                bins=(800, 800),
                convert_m=True,
                import_var=False,
                **kwargs):
    '''Convert StaMPS velocity data to a Kite Scene

    Loads the mean PS velocities (from e.g. ``ps_plot(..., -1)``) from a
    StaMPS project, and grids the data into mean velocity bins. The LOS
    velocities will be converted to a Kite Scene (:class:`~kite.Scene`).

    If explicit filenames `fn_ps` or `fn_ps_plot` are not passed an
    auto-discovery of :file:`ps?.mat` and :file:`ps_plot*.mat` in
    directory :param:`dirname` is approached.

    .. note ::

        Running the stamps2kite script on your StaMPS project does
        the trick in most cases.

    :param dirname: Folder containing data from the StaMPS project.
        Defaults to ``.``.
    :type dirname: str
    :param fn_ps2: :file:`ps2.mat` file with lat/lon information about the PS
        scene. Defaults to ``ps2.mat``.
    :type fn_ps2: str
    :param fn_mv2: :file:`mv2.mat` file with mean velocity standard deviations
        of every PS point, created by `ps_plot(...)`. Defaults to ``mv2.mat``.
    :type fn_mv2: str
    :param fn_ps_plot: Processed output from StaMPS ``ps_plot`` function, e.g.
        :file:`ps_plot*.mat`. Defaults to ``ps_plot*.mat``.
    :type fn_ps_plot: str
    :param fn_parms: :file:`parms.mat` from StaMPS, holding essential meta-
        information. Defaults to ``parms.mat``.
    :type fn_parms: str
    :param fn_look_angle: The :file:`look_angle.1.in` holds the a 50x50 grid
        with look angle information. Defaults to ``look_angle.1.in``.
    :type fn_look_angle: str
    :param fn_width: The :file:`width.txt` containing number of radar columns.
        Defaults to ``width.txt``.
    :type fn_width: str
    :param fn_len: The :file:`len.txt` containing number of rows in the
        interferogram. Defaults to ``len.txt``.
    :type fn_len: str

    :param bins: Number of pixels/bins in East and North dimension.
        Default (800, 800).
    :type bins: tuple

    :returns: Kite Scene from the StaMPS data
    :rtype: :class:`kite.Scene`
    '''
    data = read_mat_data(dirname, import_mv2=import_var, **kwargs)
    log.info('Found a StaMPS project at %s', op.abspath(dirname))

    if convert_m:
        data.ps_mean_v /= 1e3

    if convert_m and import_var:
        data.ps_mean_std /= 1e3

    bin_ps_data(data, bins=bins)
    interpolate_look_angles(data)

    log.debug('Processing of LOS angles')
    data.bin_theta = data.bin_look_angles * d2r

    phi_angle = -data.heading * d2r + num.pi
    if phi_angle > num.pi:
        phi_angle -= 2 * num.pi
    data.bin_phi = num.full_like(data.bin_theta, phi_angle)
    data.bin_phi[num.isnan(data.bin_theta)] = num.nan

    log.debug('Setting up the Kite Scene')
    config = SceneConfig()
    config.frame.llLat = data.bin_edg_lat.min()
    config.frame.llLon = data.bin_edg_lon.min()
    config.frame.dE = data.bin_edg_lon[1] - data.bin_edg_lon[0]
    config.frame.dN = data.bin_edg_lat[1] - data.bin_edg_lat[0]
    config.frame.spacing = 'degree'

    scene_name = op.basename(op.abspath(dirname))
    config.meta.scene_title = '%s (StamPS import)' % scene_name
    config.meta.scene_id = scene_name
    config.meta.time_master = data.tmin.timestamp()
    config.meta.time_slave = data.tmax.timestamp()

    scene = Scene(theta=data.bin_theta,
                  phi=data.bin_phi,
                  displacement=data.bin_ps_mean_v,
                  config=config)

    if import_var:
        scene.displacement_px_var = data.bin_mean_var

    return scene
Exemplo n.º 2
0
        msg_box.setDefaultButton(QtWidgets.QMessageBox.Save)
        ret = msg_box.exec()

        if ret == QtWidgets.QMessageBox.Save:
            self.onSaveScene()
        elif ret == QtWidgets.QMessageBox.Cancel:
            ev.ignore()


class KiteParameterTree(pg.parametertree.ParameterTree):
    pass


def spool(*args, **kwargs):
    spool_app = Spool(*args, **kwargs)
    spool_app.exec_()
    spool_app.quit()


__all__ = ["Spool", "spool"]

if __name__ == "__main__":
    from kite.scene import SceneSynTest

    if len(sys.argv) > 1:
        sc = Scene.load(sys.argv[1])
    else:
        sc = SceneSynTest.createGauss()

    Spool(scene=sc)
Exemplo n.º 3
0
def mintpy2kite(ifg, attr, date1, date2, inc_angle, az_angle, out_file):
    """Create KITE container.
    Parameters: fig       - 2D np.ndarray for displacement in meters
                attr      - dict, dictionary of mintpy metadata
                date1/2   - str, reference/secondary date in YYYYMMDD format
                inc_angle - 2D np.ndarray, incidence angle of the LOS vector in degree
                az_angle  - 2D np.ndarray, azimutth  angle of the LOS vector in degree
                out_file  - str, path of the output file name of the KITE container
    Returns:    scene     - kite.scene.Scene object
    """
    try:
        from kite.scene import Scene, SceneConfig
    except ImportError:
        raise ImportError('Can not import kite / pyrocko!')

    print('\n---------------PREPARING KITE CONTAINER-----------')
    # fill the Kite container
    config = SceneConfig()
    config.frame.llLat = float(
        attr['Y_FIRST']) + float(attr['Y_STEP']) * float(attr['LENGTH'])
    config.frame.llLon = float(attr['X_FIRST'])
    config.frame.dE = float(attr['X_STEP'])
    config.frame.dN = float(attr['Y_STEP']) * -1
    config.frame.spacing = 'degree'

    config.meta.scene_title = attr['PROJECT_NAME']
    config.meta.scene_id = attr['trackNumber']

    if date1 is not None:
        utc_sec = dt.timedelta(seconds=float(attr['CENTER_LINE_UTC']))
        config.meta.time_master = dt.datetime.strptime(date1,
                                                       '%Y%m%d') + utc_sec
        config.meta.time_slave = dt.datetime.strptime(date2,
                                                      '%Y%m%d') + utc_sec

    config.meta.orbital_node = 'Ascending' if attr['ORBIT_DIRECTION'].upper(
    ).startswith('ASC') else 'Descending'
    config.meta.wavelength = attr['WAVELENGTH']
    config.meta.satellite_name = attr['PLATFORM']

    scene = Scene(
        theta=np.flipud(np.pi / 2 - inc_angle * d2r),
        phi=np.flipud(az_angle * d2r) + np.pi / 2,
        displacement=np.flipud(ifg),
        config=config,
    )

    #Save kite container
    scene.save(out_file)

    # print out msg
    urLat = config.frame.llLat + config.frame.dN * float(attr['LENGTH'])
    urLon = config.frame.llLon + config.frame.dE * float(attr['WIDTH'])
    print('\nKite Scene info:')
    print('Scene title: {}'.format(config.meta.scene_title))
    print('Scene id: {}'.format(config.meta.scene_id))
    print('Scene orbit: {}'.format(config.meta.orbital_node))
    print('Scene platform: {}'.format(config.meta.satellite_name))
    print('Scene wavelength: {}'.format(config.meta.wavelength))
    print('Scene frame cols / rows: {0:g} / {1:g}'.format(
        float(attr['WIDTH']), float(attr['LENGTH'])))
    print('Scene frame first / last LAT: {0:.2f} / {1:.2f} °'.format(
        config.frame.llLat, urLat))
    print('Scene frame first / last LON: {0:.2f} / {1:.2f} °'.format(
        config.frame.llLon, urLon))
    print('Scene frame spacing in x / y: {} / {} {}'.format(
        config.frame.dE, config.frame.dN, config.frame.spacing))
    print(
        'Scene min / mean / max displacement    : {0:.2f} / {1:.2f} / {2:.2f} m'
        .format(np.nanmin(scene.displacement), np.nanmean(scene.displacement),
                np.nanmax(scene.displacement)))
    print(
        'Scene min / mean / max incidence angle : {0:.2f} / {1:.2f} / {2:.2f} °'
        .format(
            np.nanmin(scene.theta) * r2d,
            np.nanmean(scene.theta) * r2d,
            np.nanmax(scene.theta) * r2d))
    print(
        'Scene min / mean / max azimuth angle   : {0:.2f} / {1:.2f} / {2:.2f} °'
        .format(
            np.nanmin(scene.phi) * r2d,
            np.nanmean(scene.phi) * r2d,
            np.nanmax(scene.phi) * r2d))
    print('\n---------------SAVING KITE CONTAINER-----------')
    print('Save KITE data in file: {0}.npz {0}.yaml'.format(out_file))
    print('Import to KITE: spool {}'.format(out_file))

    return scene
Exemplo n.º 4
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)
Exemplo n.º 5
0
    dN=250)

# Resolution of the scene
npx_east = 800
npx_north = 800

# 2D arrays for displacement and look vector
displacement = num.empty((npx_east, npx_north))

# Look vectors
# Theta is elevation angle from horizon
theta = num.full_like(displacement, 48. * d2r)
# Phi is azimuth towards the satellite, counter-clockwise from East
phi = num.full_like(displacement, 23. * d2r)

scene = Scene(displacement=displacement, phi=phi, theta=theta, frame=frame)

# Or just load an existing scene!
# scene = Scene.load('my_scene_asc.npy')

satellite_target = gf.KiteSceneTarget(scene, store_id=store_id)

# Forward model!
result = engine.process(
    rect_source,
    satellite_target,
    # Use all available cores
    nthreads=0)

kite_scenes = result.kite_scenes()
Exemplo n.º 6
0
def bbd2kite(filename, px_size=(500, 500), import_var=False, convert_m=True):
    '''Convert BGR BodenBewegungsdienst PS velocity data to a Kite Scene

    Loads the mean PS velocities (from e.g. ``ps_plot(..., -1)``) from a
    BGR BodenBewegungsdienst, and grids the data into mean velocity bins.
    The LOS velocities will be converted to a Kite Scene
    (:class:`~kite.Scene`).

    :param filename: Name of the BGR BBD as ESRI shapefile.
    :type filename: str
    :param px_size: Size of pixels in North and East in meters.
        Default (500, 500).
    :type px_size: tuple
    :param convert_m: Convert displacement to meters, default True.
    :type convert_m: bool
    :param import_var: Import the mean velocity variance, this information
        is used by the Kite scene to define the covariance.
    :param import_var: bool
    '''
    data = read_shapefile(filename)

    if convert_m:
        data.ps_mean_v /= 1e3

    if convert_m and import_var:
        data.ps_mean_var /= 1e3

    # lengthN = od.distance_accurate50m(
    #     data.bbox[1], data.bbox[0],
    #     data.bbox[3], data.bbox[0])
    # lengthE = od.distance_accurate50m(
    #     data.bbox[1], data.bbox[0],
    #     data.bbox[1], data.bbox[2])

    lengthE = data.bbox[2] - data.bbox[0]
    lengthN = data.bbox[3] - data.bbox[1]

    bins = (round(lengthE / px_size[0]), round(lengthN / px_size[1]))

    bin_ps_data(data, bins=bins)

    log.debug('Setting up the Kite Scene')
    config = SceneConfig()
    zone, letter = read_projection(filename)

    llLat, llLon = utm.to_latlon(data.bbox[0], data.bbox[1], zone, letter)
    config.frame.llLat = llLat
    config.frame.llLon = llLon

    config.frame.dE = data.bin_edg_E[1] - data.bin_edg_E[0]
    config.frame.dN = data.bin_edg_N[1] - data.bin_edg_N[0]
    config.frame.spacing = 'meter'

    scene_name = op.basename(op.abspath(filename))
    config.meta.scene_title = '%s (BodenbewegunsDienst import)' % scene_name
    config.meta.scene_id = scene_name
    # config.meta.time_master = data.tmin.timestamp()
    # config.meta.time_slave = data.tmax.timestamp()

    scene = Scene(theta=data.bin_theta,
                  phi=data.bin_phi,
                  displacement=data.bin_ps_mean_v,
                  config=config)

    if import_var:
        scene.displacement_px_var = data.bin_mean_var

    return scene
Exemplo n.º 7
0
def stamps2kite(
    dirname=".", px_size=(800, 800), convert_m=True, import_var=False, **kwargs
):
    """Convert StaMPS velocity data to a Kite Scene

    Loads the mean PS velocities (from e.g. ``ps_plot(..., -1)``) from a
    StaMPS project, and grids the data into mean velocity bins. The LOS
    velocities will be converted to a Kite Scene (:class:`~kite.Scene`).

    If explicit filenames `fn_ps` or `fn_ps_plot` are not passed an
    auto-discovery of :file:`ps?.mat` and :file:`ps_plot*.mat` in
    directory :param:`dirname` is approached.

    .. note ::

        Running the stamps2kite script on your StaMPS project does
        the trick in most cases.

    :param dirname: Folder containing data from the StaMPS project.
        Defaults to ``.``.
    :type dirname: str
    :param fn_ps2: :file:`ps2.mat` file with lat/lon information about the PS
        scene. Defaults to ``ps2.mat``.
    :type fn_ps2: str
    :param fn_mv2: :file:`mv2.mat` file with mean velocity standard deviations
        of every PS point, created by `ps_plot(...)`. Defaults to ``mv2.mat``.
    :type fn_mv2: str
    :param fn_ps_plot: Processed output from StaMPS ``ps_plot`` function, e.g.
        :file:`ps_plot*.mat`. Defaults to ``ps_plot*.mat``.
    :type fn_ps_plot: str
    :param fn_parms: :file:`parms.mat` from StaMPS, holding essential meta-
        information. Defaults to ``parms.mat``.
    :type fn_parms: str
    :param fn_look_angle: The :file:`look_angle.1.in` holds the a 50x50 grid
        with look angle information. Defaults to ``look_angle.1.in``.
    :type fn_look_angle: str
    :param fn_width: The :file:`width.txt` containing number of radar columns.
        Defaults to ``width.txt``.
    :type fn_width: str
    :param fn_len: The :file:`len.txt` containing number of rows in the
        interferogram. Defaults to ``len.txt``.
    :type fn_len: str
    :param px_size: Size of pixels in North and East in meters.
        Default (200, 200).
    :type px_size: tuple
    :param convert_m: Convert displacement to meters, default True.
    :type convert_m: bool
    :param import_var: Import the mean velocity variance, this information
        is used by the Kite scene to define the covariance.
    :param import_var: bool

    :returns: Kite Scene from the StaMPS data
    :rtype: :class:`kite.Scene`
    """
    data = read_mat_data(dirname, import_mv2=import_var, **kwargs)
    log.info("Found a StaMPS project at %s", op.abspath(dirname))

    bbox = (data.lons.min(), data.lats.min(), data.lons.max(), data.lats.max())

    lengthN = od.distance_accurate50m(bbox[1], bbox[0], bbox[3], bbox[0])
    lengthE = od.distance_accurate50m(bbox[1], bbox[0], bbox[1], bbox[2])
    bins = (round(lengthE / px_size[0]), round(lengthN / px_size[1]))

    if convert_m:
        data.ps_mean_v /= 1e3

    if convert_m and import_var:
        data.ps_mean_std /= 1e3

    bin_ps_data(data, bins=bins)
    interpolate_look_angles(data)

    log.debug("Processing of LOS angles")
    data.bin_theta = data.bin_look_angles * d2r

    phi_angle = -data.heading * d2r + num.pi
    if phi_angle > num.pi:
        phi_angle -= 2 * num.pi
    data.bin_phi = num.full_like(data.bin_theta, phi_angle)
    data.bin_phi[num.isnan(data.bin_theta)] = num.nan

    log.debug("Setting up the Kite Scene")
    config = SceneConfig()
    config.frame.llLat = data.bin_edg_lat.min()
    config.frame.llLon = data.bin_edg_lon.min()
    config.frame.dE = data.bin_edg_lon[1] - data.bin_edg_lon[0]
    config.frame.dN = data.bin_edg_lat[1] - data.bin_edg_lat[0]
    config.frame.spacing = "degree"

    scene_name = op.basename(op.abspath(dirname))
    config.meta.scene_title = "%s (StamPS import)" % scene_name
    config.meta.scene_id = scene_name
    config.meta.time_master = data.tmin.timestamp()
    config.meta.time_slave = data.tmax.timestamp()

    scene = Scene(
        theta=data.bin_theta,
        phi=data.bin_phi,
        displacement=data.bin_ps_mean_v,
        config=config,
    )

    if import_var:
        scene.displacement_px_var = data.bin_mean_var

    return scene
Exemplo n.º 8
0
from kite.scene import Scene
import scipy.io as io
import os

_file = 'data/20110214_20110401_ml4_sm.unw.geo_ig_dsc_ionnocorr.mat'
mat = io.loadmat(os.path.join(os.path.dirname(__file__), _file))

sc = Scene()
sc.meta.title = 'Matlab Input - Myanmar 2011-02-14'

sc.phi = mat['phi_dsc_defo']
sc.theta = mat['theta_dsc_defo']
sc.displacement = mat['ig_dc']
sc.utm_x = mat['xx_ig']
sc.utm_y = mat['yy_ig']

sc.quadtree.plot.interactive()
# qt = Quadtree(sc)
# qp = Plot2DQuadTree(qt, cmap='RdBu')
# qp.plotInteractive()