コード例 #1
0
def main():
    print("command line:\n{}\n".format(' '.join(sys.argv)))

    args = parse_args()

    dpi = args.dpi
    image_resolution = args.resolution
    figure_dimensions = [
        float(image_resolution[0]) / dpi,
        float(image_resolution[1]) / dpi
    ]

    print("STATUS: Initializing canvas")
    figure = pyplot.figure(figsize=figure_dimensions)

    axes = figure.add_axes([0, 0, 1, 1], frameon=False)
    axes.set_frame_on(False)

    print("STATUS: Initializing trajectory source")
    trajectory_source = setup_trajectory_source(args.trajectory_data_file[0],
                                                args)

    # This is a little bit ugly but I don't yet know of a better way
    # to do it.  If we want to automatically compute the bounding box
    # of the data points before we render anything we must read all the
    # points at least once.
    #
    # That gives us a choice: read them once and keep them all in
    # memory, or make one pass through the file to compute the
    # bounding box and then another to read and render the points?
    #
    # For the moment I elect to read the points and keep them in memory.
    if args.domain == 'cartesian2d' and args.map_bbox is None:
        print("STATUS: Collecting points to compute bounding box")
        all_trajectories = itertools.chain(list(trajectory_source))
        data_bbox = geomath.compute_bounding_box(all_points)
        point_source = all_points
        args.map_bbox = data_bbox

    print("STATUS: Creating map projection")
    mapmaker_args = argument_groups.extract_arguments("mapmaker", args)
    (mymap, map_actors) = mapmaker.mapmaker(**mapmaker_args)

    print("STATUS: Reading trajectories and rendering data")
    color_scale = matplotlib.colors.Normalize(vmin=0, vmax=1)

    render_trajectories(mymap, trajectory_source, args)

    print("STATUS: Saving figure to file")
    pyplot.savefig(
        args.image_file[0],
        #                   facecolor=figure.get_facecolor(),
        facecolor='white',
        figsize=figure_dimensions,
        dpi=dpi,
        frameon=False)

    pyplot.close()

    return 0
コード例 #2
0
def main():
    print("command line:\n{}\n".format(' '.join(sys.argv)))

    args = parse_args()

    dpi = args.dpi
    image_resolution = args.resolution
    figure_dimensions = [ float(image_resolution[0]) / dpi, float(image_resolution[1]) / dpi ]

    print("STATUS: Initializing canvas")
    figure = pyplot.figure(figsize=figure_dimensions, facecolor='black', edgecolor='black')

    axes = figure.add_axes([0, 0, 1, 1], frameon=False, axisbg='black')
    axes.set_frame_on(False)

    print("STATUS: Initializing point source")
    point_source = setup_point_source(args.point_data_file[0], args)

    # This is a little bit ugly but I don't yet know of a better way
    # to do it.  If we want to automatically compute the bounding box
    # of the data points before we render anything we must read all the
    # points at least once.
    #
    # That gives us a choice: read them once and keep them all in
    # memory, or make one pass through the file to compute the
    # bounding box and then another to read and render the points?
    #
    # For the moment I elect to read the points and keep them in memory.
    if args.domain == 'cartesian2d' and args.map_bbox is None:
        print("STATUS: Collecting points to compute bounding box")
        all_points = [ point for point in point_source ] # list(point_source)
        data_bbox = geomath.compute_bounding_box(all_points)
        point_source = all_points
        args.map_bbox = data_bbox

    print("STATUS: Creating map projection")
    mapmaker_args = argument_groups.extract_arguments("mapmaker", args)
    (mymap, map_actors) = mapmaker.mapmaker(**mapmaker_args)

    print("STATUS: Initializing trajectory source")
    trajectory_source = setup_trajectory_source(point_source, args)

    print("STATUS: Reading points, assembling trajectories and rendering data")
    color_scale = matplotlib.colors.Normalize(vmin=0, vmax=1)

    render_trajectories(mymap,
                        trajectory_source,
                        args)

    print("STATUS: Saving figure to file")
    pyplot.savefig(args.image_file[0],
                   facecolor=figure.get_facecolor(),
                   figsize=figure_dimensions,
                   dpi=dpi,
                   frameon=False)

    pyplot.close()

    return 0
def test_compute_bounding_box_after_pickle():
    error_count = 0

    albuquerque = TerrestrialTrajectoryPoint(-106.6504, 35.0844)
    albuquerque.timestamp = datetime.datetime(year=2020,
                                              month=1,
                                              day=1,
                                              hour=12)
    san_francisco = TerrestrialTrajectoryPoint(-122.4194, 37.7749)
    san_francisco.timestamp = albuquerque.timestamp + datetime.timedelta(
        hours=3)
    tokyo = TerrestrialTrajectoryPoint(-221.6917, 35.6895)
    tokyo.timestamp = albuquerque.timestamp + datetime.timedelta(hours=12)

    trajectory_generator = TrajectoryPointSource()
    trajectory_generator.start_point = albuquerque
    trajectory_generator.end_point = tokyo
    trajectory_generator.num_points = 20

    print("DEBUG: TerrestrialTrajectory: {}".format(TerrestrialTrajectory))
    albuquerque_to_tokyo = TerrestrialTrajectory.from_position_list(
        list(trajectory_generator.points()))

    expected_min_corner = tracktable.domain.domain_class_for_object(
        albuquerque, 'BasePoint')()
    expected_max_corner = tracktable.domain.domain_class_for_object(
        albuquerque, 'BasePoint')()

    expected_min_corner[0] = min(albuquerque[0], tokyo[0])
    expected_min_corner[1] = min(albuquerque[1], tokyo[1])
    expected_max_corner[0] = max(albuquerque[0], tokyo[0])
    expected_max_corner[1] = max(albuquerque[1], tokyo[1])

    bbox_before_pickling = geomath.compute_bounding_box(albuquerque_to_tokyo)

    store = io.BytesIO()
    pickle.dump(albuquerque_to_tokyo, store)
    store.seek(0)
    restored_trajectory = pickle.load(store)
    bbox_after_pickling = geomath.compute_bounding_box(restored_trajectory)

    print("Bounding box before pickling: ({} {}) - ({} {})".format(
        bbox_before_pickling.min_corner[0], bbox_before_pickling.min_corner[1],
        bbox_before_pickling.max_corner[0],
        bbox_before_pickling.max_corner[1]))
    print("Bounding box after pickling: ({} {}) - ({} {})".format(
        bbox_after_pickling.min_corner[0], bbox_after_pickling.min_corner[1],
        bbox_after_pickling.max_corner[0], bbox_after_pickling.max_corner[1]))

    bbox_min_delta = (bbox_after_pickling.min_corner[0] -
                      bbox_before_pickling.min_corner[0],
                      bbox_after_pickling.min_corner[1] -
                      bbox_before_pickling.min_corner[1])
    bbox_max_delta = (bbox_after_pickling.max_corner[0] -
                      bbox_before_pickling.max_corner[0],
                      bbox_after_pickling.max_corner[1] -
                      bbox_before_pickling.max_corner[1])

    if (math.fabs(bbox_min_delta[0]) > 0.01
            or math.fabs(bbox_min_delta[1]) > 0.01
            or math.fabs(bbox_max_delta[0]) > 0.01
            or math.fabs(bbox_max_delta[1]) > 0.01):
        print(
            ("ERROR: Expected delta between bounding box before and after "
             "pickling to be zero.  Delta for minimum corner is {}.  "
             "Delta for maximum corner is {}.").format(bbox_min_delta,
                                                       bbox_max_delta))
        error_count += 1

    return error_count
コード例 #4
0
def test_compute_bounding_box():

    error_count = 0

    bbox_type = TerrestrialTrajectoryPoint.domain_classes['BoundingBox']
    expected_min_corner = TerrestrialTrajectoryPoint.domain_classes[
        'BasePoint']()
    expected_max_corner = TerrestrialTrajectoryPoint.domain_classes[
        'BasePoint']()

    albuquerque = TerrestrialTrajectoryPoint(-106.6504, 35.0844)
    san_francisco = TerrestrialTrajectoryPoint(-122.4194, 37.7749)
    tokyo = TerrestrialTrajectoryPoint(-221.6917, 35.6895)

    small_traj = TrajectoryPointSource()
    small_traj.start_point = albuquerque
    small_traj.end_point = san_francisco
    small_traj.num_points = 2

    long_traj = TrajectoryPointSource()
    long_traj.start_point = tokyo
    long_traj.end_point = san_francisco
    long_traj.num_points = 2

    #Test smallish basic bounding box
    expected_min_corner[0] = san_francisco[0]
    expected_min_corner[1] = albuquerque[1]
    expected_max_corner[0] = albuquerque[0]
    expected_max_corner[1] = san_francisco[1]
    expected = bbox_type(expected_min_corner, expected_max_corner)

    map_bbox = geomath.compute_bounding_box(small_traj.points())
    error_count += verify_result(expected, map_bbox, "Basic small box")

    #Test larger basic bounding box
    expected_min_corner[0] = tokyo[0]
    expected_min_corner[1] = tokyo[1]
    expected_max_corner[0] = san_francisco[0]
    expected_max_corner[1] = san_francisco[1]
    expected = bbox_type(expected_min_corner, expected_max_corner)

    map_bbox = geomath.compute_bounding_box(long_traj.points())
    error_count += verify_result(expected, map_bbox, "Basic large box")

    #Test smallish bounding box with buffer
    lon_buffer = .2
    lat_buffer = .5
    expected_min_corner[0] = san_francisco[0] - (
        (albuquerque[0] - san_francisco[0]) * lon_buffer)
    expected_min_corner[1] = albuquerque[1] - (
        (san_francisco[1] - albuquerque[1]) * lat_buffer)
    expected_max_corner[0] = albuquerque[0] + (
        (albuquerque[0] - san_francisco[0]) * lon_buffer)
    expected_max_corner[1] = san_francisco[1] + (
        (san_francisco[1] - albuquerque[1]) * lat_buffer)
    expected = bbox_type(expected_min_corner, expected_max_corner)

    map_bbox = geomath.compute_bounding_box(small_traj.points(),
                                            (lon_buffer, lat_buffer))
    error_count += verify_result(expected, map_bbox, "Buffered small box")

    #Test larger basic bounding box with buffer
    lon_buffer = .2
    lat_buffer = .1
    expected_min_corner[0] = tokyo[0] - (
        (san_francisco[0] - tokyo[0]) * lon_buffer)
    expected_min_corner[1] = tokyo[1] - (
        (san_francisco[1] - tokyo[1]) * lat_buffer)
    expected_max_corner[0] = san_francisco[0] + (
        (san_francisco[0] - tokyo[0]) * lon_buffer)
    expected_max_corner[1] = san_francisco[1] + (
        (san_francisco[1] - tokyo[1]) * lat_buffer)
    expected = bbox_type(expected_min_corner, expected_max_corner)

    map_bbox = geomath.compute_bounding_box(long_traj.points(),
                                            (lon_buffer, lat_buffer))
    error_count += verify_result(expected, map_bbox, "Buffered large box")

    #Test cartesian based boxes
    c_bbox_type = Cartesian2dTrajectoryPoint.domain_classes['BoundingBox']
    c_expected_min_corner = Cartesian2dTrajectoryPoint.domain_classes[
        'BasePoint']()
    c_expected_max_corner = Cartesian2dTrajectoryPoint.domain_classes[
        'BasePoint']()

    point0 = Cartesian2dTrajectoryPoint(0, 0)
    point1 = Cartesian2dTrajectoryPoint(1, 1)
    point2 = Cartesian2dTrajectoryPoint(2, 2)

    c_expected_min_corner = Cartesian2dTrajectoryPoint(0, 0)
    c_expected_max_corner = Cartesian2dTrajectoryPoint(2, 2)
    expected = c_bbox_type(c_expected_min_corner, c_expected_max_corner)

    map_bbox = geomath.compute_bounding_box([point0, point1, point2])
    error_count += verify_result(expected, map_bbox, "Basic cartesian box")

    #Test cartesian box with buffer
    x_buffer = .5
    y_buffer = 1.
    c_expected_min_corner[0] = point0[0] - ((point2[0] - point0[0]) * x_buffer)
    c_expected_min_corner[1] = point0[1] - ((point2[1] - point0[1]) * y_buffer)
    c_expected_max_corner[0] = point2[0] + ((point2[0] - point0[0]) * x_buffer)
    c_expected_max_corner[1] = point2[1] + ((point2[1] - point0[1]) * y_buffer)
    expected = c_bbox_type(c_expected_min_corner, c_expected_max_corner)

    map_bbox = geomath.compute_bounding_box([point0, point1, point2],
                                            (x_buffer, y_buffer))
    error_count += verify_result(expected, map_bbox, "Buffered cartesian box")

    # Test error conditions
    map_bbox = geomath.compute_bounding_box([])
    if (map_bbox != None):
        sys.stderr.write('ERROR: Empty point sequence did not return None')
        error_count += 1

    map_bbox = geomath.compute_bounding_box(long_traj.points(), (1.0, ))
    if (map_bbox != None):
        sys.stderr.write('ERROR: Buffer tuple length of 1 did not return None')
        error_count += 1

    map_bbox = geomath.compute_bounding_box(long_traj.points(),
                                            (1.0, 2.0, 3.0))
    if (map_bbox != None):
        sys.stderr.write('ERROR: Buffer tuple length of 3 did not return None')
        error_count += 1

    return error_count
コード例 #5
0
def main():
    args = parse_args()

    dpi = args.dpi
    image_resolution = args.resolution
    if image_resolution is None:
        image_resolution = [ 800, 600 ]
    figure_dimensions = [ float(image_resolution[0]) / dpi, float(image_resolution[1]) / dpi ]


    print("STATUS: Initializing canvas")
    figure = pyplot.figure(figsize=figure_dimensions, facecolor='black', edgecolor='black')
    axes = figure.add_axes([0, 0, 1, 1], frameon=False, axisbg='black')
    axes.set_frame_on(False)

    print("STATUS: Initializing point source")
    point_source = setup_point_source(args.point_data_file[0], args)

    # This is a little bit ugly but I don't yet know of a better way
    # to do it.  If we want to automatically compute the bounding box
    # of the data points before we render anything we must read all the
    # points at least once.
    #
    # That gives us a choice: read them once and keep them all in
    # memory, or make one pass through the file to compute the
    # bounding box and then another to read and render the points?
    #
    # For the moment I elect to read the points and keep them in memory.
    data_bbox = None
    if args.domain == 'cartesian2d' and args.map_bbox is None:
        print("STATUS: Collecting points to compute bounding box")
        all_points = list(point_source)
        data_bbox = geomath.compute_bounding_box(all_points)
        point_source = all_points

    print("STATUS: Initializing map projection")
    mapmaker_kwargs = argument_groups.extract_arguments("mapmaker", args)
    (mymap, base_artists) = mapmaker.mapmaker(computed_bbox=data_bbox, **mapmaker_kwargs)

    print("STATUS: Initializing trajectory source")
    trajectory_source = setup_trajectory_source(point_source, args)

    print("STATUS: Collecting all trajectories")
    print("DEBUG: Trajectory source is a {}".format(type(trajectory_source)))
    all_trajectories = list(trajectory_source)

    print("STATUS: Done collecting trajectories")
    movie_kwargs = argument_groups.extract_arguments("movie_rendering", args)

    movie_writer = example_movie_rendering.setup_encoder(**movie_kwargs)

    # This set of arguments will be passed to the savefig() call that
    # grabs the latest movie frame.  This is the place to put things
    # like background color, tight layout and friends.
    savefig_kwargs = { 'facecolor': figure.get_facecolor(),
                       'figsize': figure_dimensions,
                       'frameon': False }

    trajectory_kwargs = argument_groups.extract_arguments("trajectory_rendering", args)

    example_movie_rendering.render_trajectory_movie(
        movie_writer,
        map_projection=mymap,
        trajectories=all_trajectories,
        dpi=args.dpi,
        figure=figure,
        filename=args.movie_file[0],
        num_frames=movie_kwargs['fps'] * movie_kwargs['duration'],
        start_time=movie_kwargs['start_time'],
        end_time=movie_kwargs['end_time'],
        trail_duration = datetime.timedelta(seconds=args.trail_duration),
        savefig_kwargs=savefig_kwargs,
        axes=axes,
        trajectory_rendering_args=trajectory_kwargs
    )

    pyplot.close()

    return 0
コード例 #6
0
def main():
    args = parse_args()
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    dpi = args.dpi
    image_resolution = args.resolution
    figure_dimensions = [
        float(image_resolution[0]) / dpi,
        float(image_resolution[1]) / dpi
    ]

    logger.info("Initializing image canvas.")
    figure = pyplot.figure(figsize=figure_dimensions,
                           facecolor='black',
                           edgecolor='black')
    axes = figure.add_axes([0, 0, 1, 1], frameon=False, facecolor='black')
    axes.set_frame_on(False)

    logger.info("Initializing point source.")
    point_filename = args.point_data_file[0]
    with open(point_filename, 'r') as infile:
        point_source = points_from_file(
            infile,
            args.coordinate0,
            args.coordinate1,
            comment_character=args.comment_character,
            field_delimiter=args.delimiter,
            domain=args.domain)

        # This is a little bit ugly but I don't yet know of a better way
        # to do it.  If we want to automatically compute the bounding box
        # of the data points before we render anything we must read all the
        # points at least once.
        #
        # That gives us a choice: read them once and keep them all in
        # memory, or make one pass through the file to compute the
        # bounding box and then another to read and render the points?
        #
        # For the moment I elect to read the points and keep them in memory.
        if args.domain == 'cartesian2d':
            if args.map_bbox is None:
                logger.info(('Collecting points to compute Cartesian '
                             'bounding box.'))
                point_source = list(point_source)
                data_bbox = geomath.compute_bounding_box(point_source)
            else:
                # The bounding box on the command line is
                # [x_min, y_min, x_max, y_max]
                data_bbox = cartesian2d.BoundingBox(
                    (args.map_bbox[0], args.map_bbox[1]),
                    (args.map_bbox[2], args.map_bbox[3])
                    )
        else:
            # Default to taking the histogram bounds from the map extent.
            data_bbox = None
            if args.map_bbox is not None:
                # The bounding box on the command line is
                # [x_min, y_min, x_max, y_max]
                data_bbox = terrestrial.BoundingBox(
                    (args.map_bbox[0], args.map_bbox[1]),
                    (args.map_bbox[2], args.map_bbox[3])
                    )

        logger.info("Creating map projection.")
        # There are a lot of keyword arguments for the map -- see
        # tracktable.script_helpers.argument_groups.mapmaker --
        # so rather than pull them out individually like we did for
        # the point reader we extract the whole dict using
        # tracktable.script_helpers.argument_groups.extract_arguments().
        mapmaker_kwargs = argument_groups.extract_arguments("mapmaker", args)
        (mymap, artists) = mapmaker.mapmaker(**mapmaker_kwargs)

        logger.info("Rendering histogram.")
        render_histogram(mymap,
                         domain=args.domain,
                         bounding_box=data_bbox,
                         point_source=point_source,
                         bin_size=args.histogram_bin_size,
                         color_map=args.colormap,
                         scale_type=args.scale)

    # We're done with the points so we exit the with: block where we held
    # the input file open.
    if args.title is not None:
        logger.info("Setting title: {}".format(args.title))
        figure.suptitle(args.title, color='white')

    logger.info("STATUS: Saving figure to file")
    savefig_kwargs = {'figsize': figure_dimensions,
                      'dpi': dpi,
                      'facecolor': args.bgcolor
                      }
    pyplot.savefig(args.image_file[0],
                   **savefig_kwargs)

    pyplot.close()

    return 0
コード例 #7
0
def main():
    args = parse_args()

    dpi = args.dpi
    image_resolution = args.resolution
    if image_resolution is None:
        image_resolution = [800, 600]
    figure_dimensions = [
        float(image_resolution[0]) / dpi,
        float(image_resolution[1]) / dpi
    ]

    print("STATUS: Initializing canvas")
    figure = pyplot.figure(figsize=figure_dimensions,
                           facecolor='black',
                           edgecolor='black')
    axes = figure.add_axes([0, 0, 1, 1], frameon=False, axisbg='black')
    axes.set_frame_on(False)

    print("STATUS: Initializing point source")
    point_source = setup_point_source(args.point_data_file[0], args)

    # This is a little bit ugly but I don't yet know of a better way
    # to do it.  If we want to automatically compute the bounding box
    # of the data points before we render anything we must read all the
    # points at least once.
    #
    # That gives us a choice: read them once and keep them all in
    # memory, or make one pass through the file to compute the
    # bounding box and then another to read and render the points?
    #
    # For the moment I elect to read the points and keep them in memory.
    data_bbox = None
    if args.domain == 'cartesian2d' and args.map_bbox is None:
        print("STATUS: Collecting points to compute bounding box")
        all_points = list(point_source)
        data_bbox = geomath.compute_bounding_box(all_points)
        point_source = all_points

    print("STATUS: Initializing map projection")
    mapmaker_kwargs = argument_groups.extract_arguments("mapmaker", args)
    (mymap, base_artists) = mapmaker.mapmaker(computed_bbox=data_bbox,
                                              **mapmaker_kwargs)

    print("STATUS: Initializing trajectory source")
    trajectory_source = setup_trajectory_source(point_source, args)

    print("STATUS: Collecting all trajectories")
    print("DEBUG: Trajectory source is a {}".format(type(trajectory_source)))
    all_trajectories = list(trajectory_source)

    print("STATUS: Done collecting trajectories")
    movie_kwargs = argument_groups.extract_arguments("movie_rendering", args)

    movie_writer = example_movie_rendering.setup_encoder(**movie_kwargs)

    # This set of arguments will be passed to the savefig() call that
    # grabs the latest movie frame.  This is the place to put things
    # like background color, tight layout and friends.
    savefig_kwargs = {
        'facecolor': figure.get_facecolor(),
        'figsize': figure_dimensions,
        'frameon': False
    }

    trajectory_kwargs = argument_groups.extract_arguments(
        "trajectory_rendering", args)

    example_movie_rendering.render_trajectory_movie(
        movie_writer,
        map_projection=mymap,
        trajectories=all_trajectories,
        dpi=args.dpi,
        figure=figure,
        filename=args.movie_file[0],
        num_frames=movie_kwargs['fps'] * movie_kwargs['duration'],
        start_time=movie_kwargs['start_time'],
        end_time=movie_kwargs['end_time'],
        trail_duration=datetime.timedelta(seconds=args.trail_duration),
        savefig_kwargs=savefig_kwargs,
        axes=axes,
        trajectory_rendering_args=trajectory_kwargs)

    pyplot.close()

    return 0
コード例 #8
0
def main():
    args = parse_args()

    dpi = args.dpi
    image_resolution = args.resolution
    figure_dimensions = [
        float(image_resolution[0]) / dpi,
        float(image_resolution[1]) / dpi
    ]

    print("STATUS: Initializing image")
    figure = pyplot.figure(figsize=figure_dimensions,
                           facecolor='black',
                           edgecolor='black')
    axes = figure.add_axes([0, 0, 1, 1], frameon=False, axisbg='black')
    axes.set_frame_on(False)

    print("STATUS: Initializing point source")
    point_source = setup_point_source(args.point_data_file[0], args)

    # This is a little bit ugly but I don't yet know of a better way
    # to do it.  If we want to automatically compute the bounding box
    # of the data points before we render anything we must read all the
    # points at least once.
    #
    # That gives us a choice: read them once and keep them all in
    # memory, or make one pass through the file to compute the
    # bounding box and then another to read and render the points?
    #
    # For the moment I elect to read the points and keep them in memory.
    if args.domain == 'cartesian2d' and args.map_bbox is None:
        print("STATUS: Collecting points to compute bounding box")
        all_points = [point for point in point_source]  # list(point_source)
        data_bbox = geomath.compute_bounding_box(all_points)
        point_source = all_points
        args.map_bbox = data_bbox

    print("STATUS: Creating map projection")
    mapmaker_kwargs = argument_groups.extract_arguments("mapmaker", args)
    (mymap, artists) = mapmaker.mapmaker(**mapmaker_kwargs)

    print("STATUS: Rendering histogram")
    render_histogram(mymap,
                     domain=args.domain,
                     bounding_box=args.map_bbox,
                     point_source=point_source,
                     bin_size=args.histogram_bin_size,
                     color_map=args.colormap,
                     scale_type=args.scale)

    if args.title is not None:
        print("Setting title: {}".format(args.title))
        figure.suptitle(args.title, color='white')

    print("STATUS: Saving figure to file")
    savefig_kwargs = {
        'figsize': figure_dimensions,
        'dpi': dpi,
        'frameon': False,
        'facecolor': args.bgcolor
    }
    pyplot.savefig(args.image_file[0], **savefig_kwargs)

    pyplot.close()

    return 0
コード例 #9
0
def main():
    logger = logging.getLogger(__name__)

    # Step 0: Parse the command line arguments and grab sets we will need
    # later.
    args = parse_args()
    mapmaker_kwargs = argument_groups.extract_arguments("mapmaker", args)
    movie_kwargs = argument_groups.extract_arguments("movie_rendering", args)
#   Some of the keyword arguments for trajectory rendering have been renamed.
#   For now, we'll extract them by hand farther down in this function.
#    trajectory_rendering_kwargs = argument_groups.extract_arguments(
#                                    "trajectory_rendering", args)

    # Step 1: Load all the trajectories into memory.
    point_filename = args.point_data_file[0]
    field_assignments = extract_field_assignments(vars(args))

    with open(point_filename, 'r') as infile:
        logger.info('Loading points and building trajectories.')
        trajectories = list(
            trajectories_from_point_file(
                infile,
                object_id_column=args.object_id_column,
                timestamp_column=args.timestamp_column,
                coordinate0_column=args.coordinate0,
                coordinate1_column=args.coordinate1,
                string_fields=field_assignments['string'],
                real_fields=field_assignments['real'],
                time_fields=field_assignments['time'],
                comment_character=args.comment_character,
                field_delimiter=args.delimiter,
                separation_distance=args.separation_distance,
                separation_time=datetime.timedelta(minutes=args.separation_time),
                minimum_length=args.minimum_length,
                domain=args.domain)
            )
        # Add the 'progress' annotation to all of our trajectories so
        # we have some way to color them
        trajectories = [annotations.progress(t) for t in trajectories]

    # We can compute the bounding box for Cartesian data automatically.
    # We don't need to do so for terrestrial data because the map will
    # default to the whole world.
    if (args.domain == 'cartesian2d' and
            (args.map_bbox is None or
             len(args.map_bbox) == 0)):

        args.map_bbox = geomath.compute_bounding_box(
            itertools.chain(*trajectories)
            )

    #
    # Step 3: Set up the map.
    #
    # There are a lot of keyword arguments for the map -- see
    # tracktable.script_helpers.argument_groups.mapmaker --
    # so rather than pull them out individually like we did for
    # the point reader we extract the whole dict using
    # tracktable.script_helpers.argument_groups.extract_arguments().

    logger.info('Initializing map canvas for rendering.')
    (figure, axes) = initialize_canvas(args.resolution,
                                       args.dpi)
    (mymap, map_artists) = mapmaker.mapmaker(**mapmaker_kwargs)

    #
    # Step 4: Set up the video encoder.
    #
    #
    movie_kwargs = argument_groups.extract_arguments("movie_rendering", args)
    movie_writer = setup_encoder(**movie_kwargs)

    # This set of arguments will be passed to the savefig() call that
    # grabs the latest movie frame.  This is the place to put things
    # like background color, tight layout and friends.
    savefig_kwargs = {'facecolor': figure.get_facecolor(),
                      'figsize': compute_figure_dimensions(args.resolution,
                                                           args.dpi),
                      'frameon': False}

    #
    # Lights! Camera! Action!
    #
    if args.trajectory_linewidth == 'taper':
        linewidth_style = 'taper'
        linewidth = args.trajectory_initial_linewidth
        final_linewidth = args.trajectory_final_linewidth
    else:
        linewidth_style = 'constant'
        linewidth = args.trajectory_linewidth
        final_linewidth = linewidth

    # Eventually we will be able to use argument_groups.extract_arguments() for
    # this, but right now it's broken.  Not all of the parameters in the
    # trajectory rendering argument group are supported and some of the names
    # have changed.
    #
    trajectory_rendering_kwargs = {
        'decorate_head': args.decorate_trajectory_head,
        'head_color': args.trajectory_head_color,
        'head_size': args.trajectory_head_dot_size,
        'color_map': args.trajectory_colormap,
        'scalar': args.trajectory_color,
        'scalar_min': args.scalar_min,
        'scalar_max': args.scalar_max,
        'linewidth_style': linewidth_style,
        'linewidth': linewidth,
        'final_linewidth': final_linewidth
    }

    render_trajectory_movie(
        movie_writer,
        axes=mymap,
        trajectories=trajectories,
        dpi=args.dpi,
        figure=figure,
        filename=args.movie_file[0],
        num_frames=movie_kwargs['fps'] * movie_kwargs['duration'],
        start_time=movie_kwargs['start_time'],
        end_time=movie_kwargs['end_time'],
        trail_duration=datetime.timedelta(seconds=args.trail_duration),
        savefig_kwargs=savefig_kwargs,
        trajectory_rendering_kwargs=trajectory_rendering_kwargs,
        domain=args.domain
    )

    pyplot.close()

    logger.info("Movie render complete. File saved to {}".format(args.movie_file[0]))

    return 0
コード例 #10
0
def main():
    logger = logging.getLogger(__name__)
    args = parse_args()

    mapmaker_kwargs = argument_groups.extract_arguments("mapmaker", args)
    # Some of the argument names for trajectory rendering are out of
    # sync with their command-line parameter names.  We extract those
    # arguments manually at the render_annotated_trajectories
    # call instead of using extract_arguments("trajectory_rendering")
    # here.

    # Step 1: Load all the trajectories into memory.
    point_filename = args.point_data_file[0]
    field_assignments = extract_field_assignments(vars(args))

    with open(point_filename, 'r') as infile:
        logger.info('Loading points and building trajectories.')
        trajectories = list(
            trajectories_from_point_file(
                infile,
                object_id_column=args.object_id_column,
                timestamp_column=args.timestamp_column,
                coordinate0_column=args.coordinate0,
                coordinate1_column=args.coordinate1,
                string_fields=field_assignments['string'],
                real_fields=field_assignments['real'],
                time_fields=field_assignments['time'],
                comment_character=args.comment_character,
                field_delimiter=args.delimiter,
                separation_distance=args.separation_distance,
                separation_time=datetime.timedelta(
                    minutes=args.separation_time),
                minimum_length=args.minimum_length,
                domain=args.domain))
        # Add the 'progress' annotation to all of our trajectories so
        # we have some way to color them
        trajectories = [annotations.progress(t) for t in trajectories]

    # We can compute the bounding box for Cartesian data automatically.
    # We don't need to do so for terrestrial data because the map will
    # default to the whole world.
    if (args.domain == 'cartesian2d'
            and (args.map_bbox is None or len(args.map_bbox) == 0)):

        args.map_bbox = geomath.compute_bounding_box(
            itertools.chain(*trajectories))

    #
    # Step 3: Set up the map.
    #
    # There are a lot of keyword arguments for the map -- see
    # tracktable.script_helpers.argument_groups.mapmaker --
    # so rather than pull them out individually like we did for
    # the point reader we extract the whole dict using
    # tracktable.script_helpers.argument_groups.extract_arguments().

    logger.info('Initializing map canvas for rendering.')
    (figure, axes) = initialize_canvas(args.resolution, args.dpi)
    (mymap, map_artists) = mapmaker.mapmaker(**mapmaker_kwargs)

    if args.trajectory_linewidth == 'taper':
        linewidth_style = 'taper'
        linewidth = args.trajectory_initial_linewidth
        final_linewidth = args.trajectory_final_linewidth
    else:
        linewidth_style = 'constant'
        linewidth = args.trajectory_linewidth
        final_linewidth = linewidth

    # Eventually we will be able to use argument_groups.extract_arguments() for
    # this, but right now it's broken.  Not all of the parameters in the
    # trajectory rendering argument group are supported and some of the names
    # have changed.
    #
    trajectory_rendering_kwargs = {
        'decorate_head': args.decorate_trajectory_head,
        'head_color': args.trajectory_head_color,
        'head_size': args.trajectory_head_dot_size,
        'color_map': args.trajectory_colormap,
        'scalar': args.trajectory_color,
        'scalar_min': args.scalar_min,
        'scalar_max': args.scalar_max,
        'linewidth_style': linewidth_style,
        'linewidth': linewidth,
        'final_linewidth': final_linewidth
    }

    render_annotated_trajectories(trajectories, mymap,
                                  **trajectory_rendering_kwargs)

    print("STATUS: Saving figure to file")
    pyplot.savefig(args.image_file[0],
                   facecolor=figure.get_facecolor(),
                   figsize=compute_figure_dimensions(args.resolution,
                                                     args.dpi),
                   dpi=args.dpi)

    pyplot.close()

    return 0
コード例 #11
0
def main():
    args = parse_args()

    dpi = args.dpi
    image_resolution = args.resolution
    figure_dimensions = [
        float(image_resolution[0]) / dpi,
        float(image_resolution[1]) / dpi
    ]

    print("STATUS: Initializing image")
    figure = pyplot.figure(figsize=figure_dimensions, facecolor='black', edgecolor='black')
    axes = figure.add_axes([0, 0, 1, 1], frameon=False, axisbg='black')
    axes.set_frame_on(False)


    print("STATUS: Initializing point source")
    point_source = setup_point_source(args.point_data_file[0], args)

    # This is a little bit ugly but I don't yet know of a better way
    # to do it.  If we want to automatically compute the bounding box
    # of the data points before we render anything we must read all the
    # points at least once.
    #
    # That gives us a choice: read them once and keep them all in
    # memory, or make one pass through the file to compute the
    # bounding box and then another to read and render the points?
    #
    # For the moment I elect to read the points and keep them in memory.
    if args.domain == 'cartesian2d' and args.map_bbox is None:
        print("STATUS: Collecting points to compute bounding box")
        all_points = [ point for point in point_source ] # list(point_source)
        data_bbox = geomath.compute_bounding_box(all_points)
        point_source = all_points
        args.map_bbox = data_bbox

    print("STATUS: Creating map projection")
    mapmaker_kwargs = argument_groups.extract_arguments("mapmaker", args)
    (mymap, artists) = mapmaker.mapmaker(**mapmaker_kwargs)

    print("STATUS: Rendering histogram")
    render_histogram(mymap,
                     domain=args.domain,
                     bounding_box=args.map_bbox,
                     point_source=point_source,
                     bin_size=args.histogram_bin_size,
                     color_map=args.colormap,
                     scale_type=args.scale)

    if args.title is not None:
        print("Setting title: {}".format(args.title))
        figure.suptitle(args.title, color='white')

    print("STATUS: Saving figure to file")
    savefig_kwargs = { 'figsize': figure_dimensions,
                       'dpi': dpi,
                       'frameon': False,
                       'facecolor': args.bgcolor
                       }
    pyplot.savefig(args.image_file[0],
                   **savefig_kwargs)

    pyplot.close()

    return 0