def test_midpoint(self):
        center_lons = num.linspace(0., 180., 5)
        center_lats = [0., 89.]
        npoints = 10000
        half_side_length = 1000000.
        distance_error_max = 50000.
        for lat in center_lats:
            for lon in center_lons:
                n = num.random.uniform(
                    -half_side_length, half_side_length, npoints)
                e = num.random.uniform(
                    -half_side_length, half_side_length, npoints)
                dlats, dlons = orthodrome.ne_to_latlon(lat, lon, n, e)
                clat, clon = orthodrome.geographic_midpoint(dlats, dlons)
                d = orthodrome.distance_accurate50m_numpy(
                    clat, clon, lat, lon)[0]

                if plot:
                    import matplotlib.pyplot as plt
                    fig = plt.figure()
                    ax = fig.add_subplot(111)
                    ax.scatter(n, e)
                    c_n, c_e = orthodrome.latlon_to_ne_numpy(
                        lat, lon, clat, clon)
                    ax.plot(c_n, c_e, 'ro')
                    plt.show()

                self.assertTrue(d < distance_error_max, 'Distance %s > %s' %
                                (d, distance_error_max) +
                                '(maximum error)\n tested lat/lon: %s/%s' %
                                (lat, lon))
Example #2
0
    def test_midpoint(self):
        center_lons = num.linspace(0., 180., 5)
        center_lats = [0., 89.]
        npoints = 10000
        half_side_length = 1000000.
        distance_error_max = 50000.
        for lat in center_lats:
            for lon in center_lons:
                n = num.random.uniform(-half_side_length, half_side_length,
                                       npoints)
                e = num.random.uniform(-half_side_length, half_side_length,
                                       npoints)
                dlats, dlons = orthodrome.ne_to_latlon(lat, lon, n, e)
                clat, clon = orthodrome.geographic_midpoint(dlats, dlons)
                d = orthodrome.distance_accurate50m_numpy(
                    clat, clon, lat, lon)[0]

                if plot:
                    import matplotlib.pyplot as plt
                    fig = plt.figure()
                    ax = fig.add_subplot(111)
                    ax.scatter(n, e)
                    c_n, c_e = orthodrome.latlon_to_ne_numpy(
                        lat, lon, clat, clon)
                    ax.plot(c_n, c_e, 'ro')
                    plt.show()

                self.assertTrue(
                    d < distance_error_max,
                    'Distance %s > %s' % (d, distance_error_max) +
                    '(maximum error)\n tested lat/lon: %s/%s' % (lat, lon))
def get_center_station(stations, select_closest=False):
    ''' gravitations center of *stations* list.'''
    n = len(stations)
    slats = num.empty(n)
    slons = num.empty(n)
    for i, s in enumerate(stations):
        slats[i] = s.lat
        slons[i] = s.lon

    center_lat, center_lon = ortho.geographic_midpoint(slats, slons)

    if select_closest:
        center_lats = num.ones(n)*center_lat
        center_lons = num.ones(n)*center_lon
        dists = ortho.distance_accurate50m_numpy(
            center_lats, center_lons, slats, slons)

        return stations[num.argmin(dists)]
    else:
        return model.Station(center_lat, center_lon)
Example #4
0
def get_center_station(stations, select_closest=False):
    ''' gravitations center of *stations* list.'''
    n = len(stations)
    slats = num.empty(n)
    slons = num.empty(n)
    for i, s in enumerate(stations):
        slats[i] = s.lat
        slons[i] = s.lon

    center_lat, center_lon = ortho.geographic_midpoint(slats, slons)

    if select_closest:
        center_lats = num.ones(n) * center_lat
        center_lons = num.ones(n) * center_lon
        dists = ortho.distance_accurate50m_numpy(center_lats, center_lons,
                                                 slats, slons)

        return stations[num.argmin(dists)]
    else:
        return model.Station(center_lat, center_lon)
Example #5
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])
Example #6
0
    def call(self):
        if not self.viewer_connected:
            self.get_viewer().about_to_close.connect(
                self.file_serving_worker.stop)
            self.viewer_connected = True
        try:
            from OpenGL import GL  # noqa
        except ImportError:
            logger.warn('Could not find package OpenGL, '
                        'if the map does not work try installing OpenGL\n'
                        'e.g. sudo pip install PyOpenGL')

        self.cleanup()

        try:
            viewer = self.get_viewer()
            cli_mode = False
        except NoViewerSet:
            viewer = None
            cli_mode = True

        if not cli_mode:
            if self.only_active:
                _, active_stations = \
                    self.get_active_event_and_stations()
            else:
                active_stations = viewer.stations.values()
        elif cli_mode:
            active_stations = self.stations

        station_list = []
        if active_stations:
            for stat in active_stations:
                is_blacklisted = util.match_nslc(viewer.blacklist, stat.nsl())
                if (viewer and not is_blacklisted) or cli_mode:
                    xml_station_marker = XMLStationMarker(
                        nsl='.'.join(stat.nsl()),
                        longitude=float(stat.lon),
                        latitude=float(stat.lat),
                        active='yes')

                    station_list.append(xml_station_marker)

        active_station_list = StationMarkerList(stations=station_list)

        if self.only_active:
            markers = [viewer.get_active_event_marker()]
        else:
            if cli_mode:
                markers = self.markers
            else:
                markers = self.get_selected_markers()
                if len(markers) == 0:
                    tmin, tmax = self.get_selected_time_range(fallback=True)
                    markers = [
                        m for m in viewer.get_markers()
                        if isinstance(m, gui_util.EventMarker)
                        and m.tmin >= tmin and m.tmax <= tmax
                    ]

        ev_marker_list = []
        for m in markers:
            if not isinstance(m, gui_util.EventMarker):
                continue
            xmleventmarker = convert_event_marker(m)
            if xmleventmarker is None:
                continue
            ev_marker_list.append(xmleventmarker)

        event_list = EventMarkerList(events=ev_marker_list)
        event_station_list = MarkerLists(
            station_marker_list=active_station_list,
            event_marker_list=event_list)

        event_station_list.validate()
        if self.map_kind != 'GMT':
            tempdir = self.marker_tempdir
            if self.map_kind == 'Google Maps':
                map_fn = 'map_googlemaps.html'
            elif self.map_kind == 'OpenStreetMap':
                map_fn = 'map_osm.html'

            url = 'http://localhost:' + str(self.port) + '/%s' % map_fn

            files = ['loadxmldoc.js', 'map_util.js', 'plates.kml', map_fn]
            snuffling_dir = op.dirname(op.abspath(__file__))
            for entry in files:
                shutil.copy(os.path.join(snuffling_dir, entry),
                            os.path.join(tempdir, entry))
            logger.debug('copied data to %s' % tempdir)
            markers_fn = os.path.join(self.marker_tempdir, 'markers.xml')
            self.data_proxy.content_to_serve.emit(self.port)
            dump_xml(event_station_list, filename=markers_fn)

            if self.open_external:
                qg.QDesktopServices.openUrl(qc.QUrl(url))
            else:
                global g_counter
                g_counter += 1
                self.web_frame(url,
                               name='Map %i (%s)' % (g_counter, self.map_kind))
        else:
            lats_all = []
            lons_all = []

            slats = []
            slons = []
            slabels = []
            for s in active_stations:
                slats.append(s.lat)
                slons.append(s.lon)
                slabels.append('.'.join(s.nsl()))

            elats = []
            elons = []
            elats = []
            elons = []
            psmeca_input = []
            markers = self.get_selected_markers()
            for m in markers:
                if isinstance(m, gui_util.EventMarker):
                    e = m.get_event()
                    elats.append(e.lat)
                    elons.append(e.lon)
                    if e.moment_tensor is not None:
                        mt = e.moment_tensor.m6()
                        psmeca_input.append((e.lon, e.lat, e.depth / 1000.,
                                             mt[0], mt[1], mt[2], mt[3], mt[4],
                                             mt[5], 1., e.lon, e.lat, e.name))
                    else:
                        if e.magnitude is None:
                            moment = -1.
                        else:
                            moment = moment_tensor.magnitude_to_moment(
                                e.magnitude)
                            psmeca_input.append(
                                (e.lon, e.lat, e.depth / 1000., moment / 3.,
                                 moment / 3., moment / 3., 0., 0., 0., 1.,
                                 e.lon, e.lat, e.name))

            lats_all.extend(elats)
            lons_all.extend(elons)
            lats_all.extend(slats)
            lons_all.extend(slons)

            lats_all = num.array(lats_all)
            lons_all = num.array(lons_all)

            if len(lats_all) == 0:
                return

            center_lat, center_lon = ortho.geographic_midpoint(
                lats_all, lons_all)
            ntotal = len(lats_all)
            clats = num.ones(ntotal) * center_lat
            clons = num.ones(ntotal) * center_lon
            dists = ortho.distance_accurate50m_numpy(clats, clons, lats_all,
                                                     lons_all)

            maxd = num.max(dists) or 0.
            m = Map(lat=center_lat,
                    lon=center_lon,
                    radius=max(10000., maxd) * 1.1,
                    width=35,
                    height=25,
                    show_grid=True,
                    show_topo=True,
                    color_dry=(238, 236, 230),
                    topo_cpt_wet='light_sea_uniform',
                    topo_cpt_dry='light_land_uniform',
                    illuminate=True,
                    illuminate_factor_ocean=0.15,
                    show_rivers=False,
                    show_plates=False)

            m.gmt.psxy(in_columns=(slons, slats), S='t15p', G='black', *m.jxyr)
            for i in range(len(active_stations)):
                m.add_label(slats[i], slons[i], slabels[i])

            m.gmt.psmeca(in_rows=psmeca_input,
                         S='m1.0',
                         G='red',
                         C='5p,0/0/0',
                         *m.jxyr)

            tmpdir = self.tempdir()

            self.outfn = os.path.join(tmpdir, '%i.png' % self.figcount)
            m.save(self.outfn)
            f = self.pixmap_frame(self.outfn)  # noqa
Example #7
0
def plot_polarizations(stations,
                       trs,
                       event=None,
                       size_factor=0.05,
                       fontsize=10.,
                       output_filename=None,
                       output_format=None,
                       output_dpi=None):

    if event is None:
        slats = num.array([s.lat for s in stations], dtype=num.float)
        slons = num.array([s.lon for s in stations], dtype=num.float)
        clat, clon = od.geographic_midpoint(slats, slons)
        event = od.Loc(clat, clon)

    nsl_c_to_trs = defaultdict(dict)
    for tr in trs:
        nsl_c_to_trs[tr.nslc_id[:3]][tr.nslc_id[3]] = tr

    nsl_to_station = dict((s.nsl(), s) for s in stations)

    plot.mpl_init(fontsize=fontsize)
    fig = plt.figure(figsize=plot.mpl_papersize('a4', 'landscape'))
    plot.mpl_margins(fig, w=7., h=6., units=fontsize)

    grid = ImageGrid(fig,
                     111,
                     nrows_ncols=(2, 2),
                     axes_pad=0.5,
                     add_all=True,
                     label_mode='L',
                     aspect=True)

    axes_en = grid[0]
    axes_en.set_ylabel('Northing [km]')

    axes_dn = grid[1]
    axes_dn.locator_params(axis='x', nbins=4)
    axes_dn.set_xlabel('Depth [km]')

    axes_ed = grid[2]
    axes_ed.locator_params(axis='y', nbins=4)
    axes_ed.set_ylabel('Depth [km]')
    axes_ed.set_xlabel('Easting [km]')

    if isinstance(event, model.Event):
        axes_en.plot(0., 0., '*')
        axes_dn.plot(event.depth / km, 0., '*')
        axes_ed.plot(0., event.depth / km, '*')

    grid[3].set_axis_off()

    locations = []
    for nsl in sorted(nsl_c_to_trs.keys()):
        station = nsl_to_station[nsl]
        n, e = od.latlon_to_ne(event.lat, event.lon, station.lat, station.lon)

        locations.append((n, e))

    ns, es = num.array(locations, dtype=num.float).T

    n_min = num.min(ns)
    n_max = num.max(ns)
    e_min = num.min(es)
    e_max = num.max(es)

    factor = max((n_max - n_min) * size_factor, (e_max - e_min) * size_factor)

    fontsize_annot = fontsize * 0.7

    data = {}
    for insl, nsl in enumerate(sorted(nsl_c_to_trs.keys())):

        color = plot.mpl_graph_color(insl)

        try:
            tr_e = nsl_c_to_trs[nsl]['E']
            tr_n = nsl_c_to_trs[nsl]['N']
            tr_z = nsl_c_to_trs[nsl]['Z']

        except KeyError:
            continue

        station = nsl_to_station[nsl]

        n, e = od.latlon_to_ne(event.lat, event.lon, station.lat, station.lon)

        d = station.depth

        axes_en.annotate('.'.join(x for x in nsl if x),
                         xy=(e / km, n / km),
                         xycoords='data',
                         xytext=(fontsize_annot / 3., fontsize_annot / 3.),
                         textcoords='offset points',
                         verticalalignment='bottom',
                         horizontalalignment='left',
                         rotation=0.,
                         size=fontsize_annot)

        axes_en.plot(e / km, n / km, '^', mfc=color, mec=darken(color))
        axes_dn.plot(d / km, n / km, '^', mfc=color, mec=darken(color))
        axes_ed.plot(e / km, d / km, '^', mfc=color, mec=darken(color))

        arr_e = tr_e.ydata
        arr_n = tr_n.ydata
        arr_z = tr_z.ydata
        arr_t = tr_z.get_xdata()

        data[nsl] = (arr_e, arr_n, arr_z, arr_t, n, e, d, color)

    amaxs = []
    amax_hors = []
    for nsl in sorted(data.keys()):
        arr_e, arr_n, arr_z, arr_t, n, e, d, color = data[nsl]
        amaxs.append(num.max(num.abs(num.sqrt(arr_e**2 + arr_n**2 +
                                              arr_z**2))))
        amax_hors.append(num.max(num.abs(num.sqrt(arr_e**2 + arr_n**2))))

    amax = num.median(amaxs)
    amax_hor = num.median(amax_hors)

    for nsl in sorted(data.keys()):
        arr_e, arr_n, arr_z, arr_t, n, e, d, color = data[nsl]
        tmin = arr_t.min()
        tmax = arr_t.max()
        plot_color_line(axes_en, (e + arr_e / amax_hor * factor) / km,
                        (n + arr_n / amax_hor * factor) / km, arr_t, color,
                        tmin, tmax)
        plot_color_line(axes_dn, (d - arr_z / amax * factor) / km,
                        (n + arr_n / amax * factor) / km, arr_t, color, tmin,
                        tmax)
        plot_color_line(axes_ed, (e + arr_e / amax * factor) / km,
                        (d - arr_z / amax * factor) / km, arr_t, color, tmin,
                        tmax)

    axes_ed.invert_yaxis()

    for axes in (axes_dn, axes_ed, axes_en):
        axes.autoscale_view(tight=True)

    if output_filename is None:
        plt.show()
    else:
        fig.savefig(output_filename, format=output_format, dpi=output_dpi)
Example #8
0
    def call(self):
        try:
            global vtk
            import vtk
            import sys
            sys.path[0:0] = [self.module_dir()]
            from grid_topo import setup_vtk_map_actor
            sys.path[0:1] = []
        except ImportError as _import_error:
            self.fail('\nImportError:\n%s' % _import_error)
            vtk = None

        self.cleanup()
        viewer = self.get_viewer()

        stations = []
        events = []
        cone_actors = []
        sphere_actors = []

        if self.want_stations:
            stations = self.get_stations()

        if self.want_events:
            markers = self.get_selected_event_markers()
            if len(markers) == 0:
                tmin, tmax = self.get_selected_time_range(fallback=True)
                markers = filter(lambda x: tmin < x.tmin < tmax,
                                 self.get_event_markers())
            events = [m.get_event() for m in markers]

            active_event = viewer.get_active_event()
            to_rgba = ColorMapper('summer')
            times = [e.time for e in events]
            to_rgba.set_range(min(times), max(times))
            if active_event:

                to_rgba = ColorMapper('gray')
                to_rgba.set_range(min(times), max(times))

            for e in events:
                e.get_vtk_color = to_rgba

            if active_event:

                def return_red(e):
                    return (1., 0., 0., 1.)

                active_event.get_vtk_color = return_red
                events.append(active_event)

        all_lats = []
        all_lons = []

        for s in stations:
            all_lats.append(s.lat)
            all_lons.append(s.lon)

        for e in events:
            all_lats.append(e.lat)
            all_lons.append(e.lon)

        center_lat, center_lon = ortho.geographic_midpoint(
            num.array(all_lats), num.array(all_lons))

        center_lats = num.array([center_lat] * len(all_lats))
        center_lons = num.array([center_lon] * len(all_lons))
        distances = ortho.distance_accurate50m_numpy(num.array(all_lats),
                                                     num.array(all_lons),
                                                     center_lats, center_lons)
        distance_max = num.max(distances)
        size = distance_max / 50.

        if len(events) != 0:
            sphere_actors = events_to_vtksphere_actors(events,
                                                       z_scale=self.z_scale,
                                                       size=size / 2.)

        if len(stations) != 0:
            ns, es, depths = locations_to_ned(stations,
                                              z_scale=self.z_scale,
                                              has_elevation=True)
            adata = num.array((es, ns, -depths)).flatten(order='F')
            data = numpy_support.numpy_to_vtk(adata,
                                              deep=True,
                                              array_type=vtk.VTK_FLOAT)
            data.SetNumberOfComponents(3)

            cone_actors = self.stations_to_vtkcone_actors(data, size=size)

        if self.want_topo:
            distance_max += self.margin_radius * 1000.
            topo_actor = setup_vtk_map_actor(center_lat,
                                             center_lon,
                                             distance_max,
                                             super_elevation=self.z_scale,
                                             decimation=int(self.z_decimation
                                                            or 1),
                                             smoothing=self.smoothing)

        self.frame = self.vtk_frame()

        for actor in cone_actors:
            actor.GetProperty().SetColor(0., 0., 1.)
            self.frame.add_actor(actor)

        for actor in sphere_actors:
            self.frame.add_actor(actor)

        if self.want_topo:
            self.frame.add_actor(topo_actor)
        self.frame.renderer.SetBackground(0.01, 0.05, 0.1)

        self.frame.init()
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])
    def call(self):
        if not self.viewer_connected:
            self.get_viewer().about_to_close.connect(
                self.file_serving_worker.stop)
            self.viewer_connected = True
        try:
            from OpenGL import GL  # noqa
        except ImportError:
            logger.warn(
                'Could not find package OpenGL, '
                'if the map does not work try installing OpenGL\n'
                'e.g. sudo pip install PyOpenGL')

        self.cleanup()

        try:
            viewer = self.get_viewer()
            cli_mode = False
        except NoViewerSet:
            viewer = None
            cli_mode = True

        if not cli_mode:
            if self.only_active:
                _, active_stations = \
                    self.get_active_event_and_stations()
            else:
                active_stations = viewer.stations.values()
        elif cli_mode:
            active_stations = self.stations

        station_list = []
        if active_stations:
            for stat in active_stations:
                is_blacklisted = util.match_nslc(viewer.blacklist, stat.nsl())
                if (viewer and not is_blacklisted) or cli_mode:
                    xml_station_marker = XMLStationMarker(
                        nsl='.'.join(stat.nsl()),
                        longitude=float(stat.lon),
                        latitude=float(stat.lat),
                        active='yes')

                    station_list.append(xml_station_marker)

        active_station_list = StationMarkerList(stations=station_list)

        if self.only_active:
            markers = [viewer.get_active_event_marker()]
        else:
            if cli_mode:
                markers = self.markers
            else:
                markers = self.get_selected_markers()
                if len(markers) == 0:
                    tmin, tmax = self.get_selected_time_range(fallback=True)
                    markers = [m for m in viewer.get_markers()
                               if isinstance(m, gui_util.EventMarker) and
                               m.tmin >= tmin and m.tmax <= tmax]

        ev_marker_list = []
        for m in markers:
            if not isinstance(m, gui_util.EventMarker):
                continue
            xmleventmarker = convert_event_marker(m)
            if xmleventmarker is None:
                continue
            ev_marker_list.append(xmleventmarker)

        event_list = EventMarkerList(events=ev_marker_list)
        event_station_list = MarkerLists(
            station_marker_list=active_station_list,
            event_marker_list=event_list)

        event_station_list.validate()
        if self.map_kind != 'GMT':
            tempdir = self.marker_tempdir
            if self.map_kind == 'Google Maps':
                map_fn = 'map_googlemaps.html'
            elif self.map_kind == 'OpenStreetMap':
                map_fn = 'map_osm.html'

            url = 'http://localhost:' + str(self.port) + '/%s' % map_fn

            files = ['loadxmldoc.js', 'map_util.js', 'plates.kml', map_fn]
            snuffling_dir = op.dirname(op.abspath(__file__))
            for entry in files:
                shutil.copy(os.path.join(snuffling_dir, entry),
                            os.path.join(tempdir, entry))
            logger.debug('copied data to %s' % tempdir)
            markers_fn = os.path.join(self.marker_tempdir, 'markers.xml')
            self.data_proxy.content_to_serve.emit(self.port)
            dump_xml(event_station_list, filename=markers_fn)

            if self.open_external:
                qg.QDesktopServices.openUrl(qc.QUrl(url))
            else:
                global g_counter
                g_counter += 1
                self.web_frame(
                    url,
                    name='Map %i (%s)' % (g_counter, self.map_kind))
        else:
            lats_all = []
            lons_all = []

            slats = []
            slons = []
            slabels = []
            for s in active_stations:
                slats.append(s.lat)
                slons.append(s.lon)
                slabels.append('.'.join(s.nsl()))

            elats = []
            elons = []
            elats = []
            elons = []
            psmeca_input = []
            markers = self.get_selected_markers()
            for m in markers:
                if isinstance(m, gui_util.EventMarker):
                    e = m.get_event()
                    elats.append(e.lat)
                    elons.append(e.lon)
                    if e.moment_tensor is not None:
                        mt = e.moment_tensor.m6()
                        psmeca_input.append(
                            (e.lon, e.lat, e.depth/1000., mt[0], mt[1],
                             mt[2], mt[3], mt[4], mt[5],
                             1., e.lon, e.lat, e.name))
                    else:
                        if e.magnitude is None:
                            moment = -1.
                        else:
                            moment = moment_tensor.magnitude_to_moment(
                                e.magnitude)
                            psmeca_input.append(
                                (e.lon, e.lat, e.depth/1000.,
                                 moment/3., moment/3., moment/3.,
                                 0., 0., 0., 1., e.lon, e.lat, e.name))

            lats_all.extend(elats)
            lons_all.extend(elons)
            lats_all.extend(slats)
            lons_all.extend(slons)

            lats_all = num.array(lats_all)
            lons_all = num.array(lons_all)

            if len(lats_all) == 0:
                return

            center_lat, center_lon = ortho.geographic_midpoint(
                lats_all, lons_all)
            ntotal = len(lats_all)
            clats = num.ones(ntotal) * center_lat
            clons = num.ones(ntotal) * center_lon
            dists = ortho.distance_accurate50m_numpy(
                clats, clons, lats_all, lons_all)

            maxd = num.max(dists) or 0.
            m = Map(
                lat=center_lat, lon=center_lon,
                radius=max(10000., maxd) * 1.1,
                width=35, height=25,
                show_grid=True,
                show_topo=True,
                color_dry=(238, 236, 230),
                topo_cpt_wet='light_sea_uniform',
                topo_cpt_dry='light_land_uniform',
                illuminate=True,
                illuminate_factor_ocean=0.15,
                show_rivers=False,
                show_plates=False)

            m.gmt.psxy(in_columns=(slons, slats), S='t15p', G='black', *m.jxyr)
            for i in range(len(active_stations)):
                m.add_label(slats[i], slons[i], slabels[i])

            m.gmt.psmeca(
                in_rows=psmeca_input, S='m1.0', G='red', C='5p,0/0/0', *m.jxyr)

            tmpdir = self.tempdir()

            self.outfn = os.path.join(tmpdir, '%i.png' % self.figcount)
            m.save(self.outfn)
            f = self.pixmap_frame(self.outfn)  # noqa
    def call(self):
        try:
            global vtk
            import vtk
            from vtk.util import numpy_support
            import sys
            sys.path[0:0] = [self.module_dir()]
            from grid_topo import setup_vtk_map_actor
            sys.path[0:1] = []
        except ImportError as _import_error:
            self.fail('\nImportError:\n%s' % _import_error)
            vtk = None

        self.cleanup()
        stations = []
        events = []
        cone_actors = []
        sphere_actors = []

        if self.want_stations:
            stations = self.get_stations()

        if self.want_events:
            markers = self.get_selected_event_markers()
            if len(markers) == 0:
                tmin, tmax = self.get_selected_time_range(fallback=True)
                markers = filter(lambda x: tmin < x.tmin < tmax,
                                 self.get_event_markers())
            events = [m.get_event() for m in markers]

        all_lats = []
        all_lons = []

        for s in stations:
            all_lats.append(s.lat)
            all_lons.append(s.lon)

        for e in events:
            all_lats.append(e.lat)
            all_lons.append(e.lon)

        center_lat, center_lon = ortho.geographic_midpoint(
            num.array(all_lats), num.array(all_lons))

        center_lats = num.array([center_lat]*len(all_lats))
        center_lons = num.array([center_lon]*len(all_lons))
        distances = ortho.distance_accurate50m_numpy(
            num.array(all_lats), num.array(all_lons),
            center_lats, center_lons)
        distance_max = num.max(distances)
        size = distance_max / 50.

        if len(events) != 0:
            ns, es, depths = self.locations_to_ned(events)
            times = [e.time for e in events]
            adata = num.array((es, ns, -depths))
            adata = adata.flatten(order='F')
            data = numpy_support.numpy_to_vtk(
                adata, deep=True, array_type=vtk.VTK_FLOAT)
            data.SetNumberOfComponents(3)
            sphere_actors = self.events_to_vtksphere_actors(data, times, size=size/2.)

        if len(stations) != 0:
            ns, es, depths = self.locations_to_ned(stations,
                                                   has_elevation=True)
            adata = num.array((es, ns, -depths)).flatten(order='F')
            data = numpy_support.numpy_to_vtk(
                adata, deep=True, array_type=vtk.VTK_FLOAT)
            data.SetNumberOfComponents(3)

            cone_actors = self.stations_to_vtkcone_actors(data, size=size)

        if self.want_topo:
            distance_max += self.margin_radius * 1000
            self.topo_actor = setup_vtk_map_actor(
                center_lat, center_lon, distance_max,
                super_elevation=self.z_scale,
                decimation=int(self.z_decimation or 1),
                smoothing=self.smoothing)

        self.frame = self.vtk_frame()

        for actor in cone_actors:
            actor.GetProperty().SetColor(0., 0., 1.)
            self.frame.add_actor(actor)

        for actor in sphere_actors:
            self.frame.add_actor(actor)

        if self.topo_actor:
            self.frame.add_actor(self.topo_actor)
        self.frame.renderer.SetBackground(0.01, 0.05, 0.1)

        self.frame.init()