예제 #1
0
def generic_postman(postman_type):
    """
    Runs the CPP or RPP algorithm, prints solution, saves visualizations to filesystem

    Args:
        postman_type (str): "rural" or "chinese"
    """

    if postman_type == 'rural':
        postman_algo = rpp
    elif postman_type == 'chinese':
        postman_algo = cpp

    # get args
    args = get_args()

    # setup logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    logger.info('Solving the {} postman problem..'.format(postman_type))
    circuit, graph = postman_algo(edgelist_filename=args.edgelist,
                                       start_node=args.start_node,
                                       edge_weight=args.edge_weight)

    logger.info('Solution:')
    for edge in circuit:
        logger.info(edge)

    logger.info('Solution summary stats:')
    for k, v in calculate_postman_solution_stats(circuit).items():
        logger.info(str(k) + ' : ' + str(v))

    if args.viz:
        logger.info('Creating single image of {} postman solution...'.format(postman_type))
        message_static = plot_circuit_graphviz(circuit=circuit,
                                               graph=graph,
                                               filename=args.viz_filename,
                                               format=args.viz_format,
                                               engine=args.viz_engine)
        logger.info(message_static)

    if args.animation:
        animation_images_dir = args.animation_images_dir if args.animation_images_dir else os.path.join(
            os.path.dirname(args.animation_filename), 'img')

        logger.info('Creating individual files for animation...')
        message_images = make_circuit_images(circuit=circuit,
                                             graph=graph,
                                             outfile_dir=animation_images_dir,
                                             format=args.animation_format,
                                             engine=args.animation_engine)
        logger.info(message_images)

        logger.info('Creating animation...')
        message_animation = make_circuit_video(infile_dir_images=animation_images_dir,
                                               outfile_movie=args.animation_filename,
                                               fps=args.fps,
                                               format=args.animation_format)
        logger.info(message_animation)
예제 #2
0
def main():
    """Solve the RPP and save visualizations of the solution"""

    # PARAMS / DATA ---------------------------------------------------------------------

    # inputs
    START_NODE = 'a'
    N_NODES = 13

    # filepaths
    CPP_REQUIRED_SVG_FILENAME = pkg_resources.resource_filename(
        'postman_problems', 'examples/star/output/cpp_graph_req')
    CPP_OPTIONAL_SVG_FILENAME = pkg_resources.resource_filename(
        'postman_problems', 'examples/star/output/cpp_graph_opt')
    RPP_SVG_FILENAME = pkg_resources.resource_filename(
        'postman_problems', 'examples/star/output/rpp_graph')
    RPP_BASE_SVG_FILENAME = pkg_resources.resource_filename(
        'postman_problems', 'examples/star/output/base_rpp_graph')
    PNG_PATH = pkg_resources.resource_filename('postman_problems',
                                               'examples/star/output/png/')
    RPP_GIF_FILENAME = pkg_resources.resource_filename(
        'postman_problems', 'examples/star/output/rpp_graph.gif')

    # setup logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    # CREATE GRAPH ----------------------------------------------------------------------

    logger.info('Solve RPP')
    graph_base = create_star_graph(N_NODES)
    edgelist = nx.to_pandas_edgelist(graph_base,
                                     source='_node1',
                                     target='_node2')

    # SOLVE CPP -------------------------------------------------------------------------

    # with required edges only
    edgelist_file = create_mock_csv_from_dataframe(edgelist)
    circuit_cpp_req, graph_cpp_req = cpp(edgelist_file, start_node=START_NODE)
    logger.info('Print the CPP solution (required edges only):')
    for e in circuit_cpp_req:
        logger.info(e)

    # with required and optional edges as required
    edgelist_all_req = edgelist.copy()
    edgelist_all_req.drop(['required'], axis=1, inplace=True)
    edgelist_file = create_mock_csv_from_dataframe(edgelist_all_req)
    circuit_cpp_opt, graph_cpp_opt = cpp(edgelist_file, start_node=START_NODE)
    logger.info('Print the CPP solution (optional and required edges):')
    for e in circuit_cpp_opt:
        logger.info(e)

    # SOLVE RPP -------------------------------------------------------------------------

    edgelist_file = create_mock_csv_from_dataframe(
        edgelist)  # need to regenerate
    circuit_rpp, graph_rpp = rpp(edgelist_file, start_node=START_NODE)

    logger.info('Print the RPP solution:')
    for e in circuit_rpp:
        logger.info(e)

    logger.info('Solution summary stats:')
    for k, v in calculate_postman_solution_stats(circuit_rpp).items():
        logger.info(str(k) + ' : ' + str(v))

    # VIZ -------------------------------------------------------------------------------

    try:
        from postman_problems.viz import plot_circuit_graphviz, plot_graphviz, make_circuit_images, make_circuit_video

        logger.info('Creating single SVG of base graph')
        plot_graphviz(graph=graph_base,
                      filename=RPP_BASE_SVG_FILENAME,
                      edge_label_attr='distance',
                      format='svg',
                      engine='circo',
                      graph_attr={
                          'label': 'Base Graph: Distances',
                          'labelloc': 't'
                      })

        logger.info(
            'Creating single SVG of CPP solution (required edges only)')
        plot_circuit_graphviz(
            circuit=circuit_cpp_req,
            graph=graph_cpp_req,
            filename=CPP_REQUIRED_SVG_FILENAME,
            format='svg',
            engine='circo',
            graph_attr={
                'label':
                'Base Graph: Chinese Postman Solution (required edges only)',
                'labelloc': 't'
            })

        logger.info(
            'Creating single SVG of CPP solution (required & optional edges)')
        plot_circuit_graphviz(
            circuit=circuit_cpp_opt,
            graph=graph_cpp_opt,
            filename=CPP_OPTIONAL_SVG_FILENAME,
            format='svg',
            engine='circo',
            graph_attr={
                'label':
                'Base Graph: Chinese Postman Solution (required & optional edges)',
                'labelloc': 't'
            })

        logger.info('Creating single SVG of RPP solution')
        plot_circuit_graphviz(circuit=circuit_rpp,
                              graph=graph_rpp,
                              filename=RPP_SVG_FILENAME,
                              format='svg',
                              engine='circo',
                              graph_attr={
                                  'label':
                                  'Base Graph: Rural Postman Solution',
                                  'labelloc': 't'
                              })

        logger.info('Creating PNG files for GIF')
        make_circuit_images(circuit=circuit_rpp,
                            graph=graph_rpp,
                            outfile_dir=PNG_PATH,
                            format='png',
                            engine='circo')

        logger.info('Creating GIF')
        make_circuit_video(infile_dir_images=PNG_PATH,
                           outfile_movie=RPP_GIF_FILENAME,
                           fps=1)

    except FileNotFoundError(OSError) as e:
        print(e)
        print(
            "Sorry, looks like you don't have all the needed visualization dependencies."
        )
def main():
    """Solve the RPP and save visualizations of the solution"""

    # PARAMS / DATA ---------------------------------------------------------------------

    # inputs
    EDGELIST = pkg_resources.resource_filename(
        'postman_problems',
        'examples/sleeping_giant/edgelist_sleeping_giant.csv')
    NODELIST = pkg_resources.resource_filename(
        'postman_problems',
        'examples/sleeping_giant/nodelist_sleeping_giant.csv')
    START_NODE = "b_end_east"

    # outputs
    GRAPH_ATTR = {'dpi': '65'}
    EDGE_ATTR = {'fontsize': '20'}
    NODE_ATTR = {
        'shape': 'point',
        'color': 'black',
        'width': '0.1',
        'fixedsize': 'true'
    }

    PNG_PATH = pkg_resources.resource_filename(
        'postman_problems', 'examples/sleeping_giant/output/png/')
    RPP_SVG_FILENAME = pkg_resources.resource_filename(
        'postman_problems', 'examples/sleeping_giant/output/rpp_graph')
    RPP_GIF_FILENAME = pkg_resources.resource_filename(
        'postman_problems', 'examples/sleeping_giant/output/rpp_graph.gif')

    # setup logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    # SOLVE RPP -------------------------------------------------------------------------

    logger.info('Solve RPP')
    circuit, graph = rpp(EDGELIST, START_NODE)

    logger.info('Print the RPP solution:')
    for e in circuit:
        logger.info(e)

    logger.info('Solution summary stats:')
    for k, v in calculate_postman_solution_stats(circuit).items():
        logger.info(str(k) + ' : ' + str(v))

    # VIZ -------------------------------------------------------------------------------

    try:
        from postman_problems.viz import (add_pos_node_attribute,
                                          add_node_attributes,
                                          plot_circuit_graphviz,
                                          make_circuit_images,
                                          make_circuit_video)

        logger.info('Add node attributes to graph')
        nodelist_df = pd.read_csv(NODELIST)
        graph = add_node_attributes(graph, nodelist_df)  # add attributes
        graph = add_pos_node_attribute(
            graph,
            origin='topleft')  # add X,Y positions in format for graphviz

        logger.info('Add style edge attribute to make optional edges dotted')
        for e in graph.edges(data=True, keys=True):
            graph[e[0]][e[1]][e[2]]['style'] = 'solid' if graph[e[0]][e[1]][
                e[2]]['required'] else 'dashed'

        logger.info('Creating single SVG of RPP solution')
        plot_circuit_graphviz(circuit=circuit,
                              graph=graph,
                              filename=RPP_SVG_FILENAME,
                              format='svg',
                              engine='neato',
                              graph_attr=GRAPH_ATTR,
                              edge_attr=EDGE_ATTR,
                              node_attr=NODE_ATTR)

        logger.info('Creating PNG files for GIF')
        images_message = make_circuit_images(circuit=circuit,
                                             graph=graph,
                                             outfile_dir=PNG_PATH,
                                             format='png',
                                             engine='neato',
                                             graph_attr=GRAPH_ATTR,
                                             edge_attr=EDGE_ATTR,
                                             node_attr=NODE_ATTR)
        logger.info(images_message)

        logger.info('Creating GIF')
        video_message = make_circuit_video(infile_dir_images=PNG_PATH,
                                           outfile_movie=RPP_GIF_FILENAME,
                                           fps=3)
        logger.info(video_message)
        logger.info("and that's a wrap, checkout the output!")

    except FileNotFoundError(OSError) as e:
        print(e)
        print(
            "Sorry, looks like you don't have all the needed visualization dependencies."
        )
예제 #4
0
def main():
    """Solve the CPP and save visualizations of the solution"""

    # PARAMS / DATA ---------------------------------------------------------------------

    # inputs
    EDGELIST = pkg_resources.resource_filename(
        'postman_problems',
        'examples/seven_bridges/edgelist_seven_bridges.csv')
    START_NODE = 'D'

    # outputs
    PNG_PATH = pkg_resources.resource_filename(
        'postman_problems', 'examples/seven_bridges/output/png/')
    CPP_VIZ_FILENAME = pkg_resources.resource_filename(
        'postman_problems', 'examples/seven_bridges/output/cpp_graph')
    CPP_BASE_VIZ_FILENAME = pkg_resources.resource_filename(
        'postman_problems', 'examples/seven_bridges/output/base_cpp_graph')
    CPP_GIF_FILENAME = pkg_resources.resource_filename(
        'postman_problems', 'examples/seven_bridges/output/cpp_graph.gif')

    # setup logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    # SOLVE CPP -------------------------------------------------------------------------

    logger.info('Solve CPP')
    circuit, graph = cpp(edgelist_filename=EDGELIST, start_node=START_NODE)

    logger.info('Print the CPP solution:')
    for e in circuit:
        logger.info(e)

    logger.info('Solution summary stats:')
    for k, v in calculate_postman_solution_stats(circuit).items():
        logger.info(str(k) + ' : ' + str(v))

    # VIZ -------------------------------------------------------------------------------

    try:
        from postman_problems.viz import plot_circuit_graphviz, make_circuit_images, make_circuit_video

        logger.info('Creating single SVG of base graph')
        plot_circuit_graphviz(circuit=circuit,
                              graph=graph,
                              filename=CPP_BASE_VIZ_FILENAME,
                              edge_label_attr='distance',
                              format='svg',
                              engine='circo',
                              graph_attr={
                                  'label': 'Base Graph: Distances',
                                  'labelloc': 't'
                              })

        logger.info('Creating single SVG of CPP solution')
        plot_circuit_graphviz(circuit=circuit,
                              graph=graph,
                              filename=CPP_VIZ_FILENAME,
                              format='svg',
                              engine='circo',
                              graph_attr={
                                  'label':
                                  'Base Graph: Chinese Postman Solution',
                                  'labelloc': 't'
                              })

        logger.info('Creating PNG files for GIF')
        make_circuit_images(circuit=circuit,
                            graph=graph,
                            outfile_dir=PNG_PATH,
                            format='png',
                            engine='circo',
                            graph_attr={
                                'label':
                                'Base Graph: Chinese Postman Solution',
                                'labelloc': 't'
                            })

        logger.info('Creating GIF')
        video_message = make_circuit_video(infile_dir_images=PNG_PATH,
                                           outfile_movie=CPP_GIF_FILENAME,
                                           fps=0.5)

        logger.info(video_message)
        logger.info("and that's a wrap, checkout the output!")

    except FileNotFoundError(OSError) as e:
        print(e)
        print(
            "Sorry, looks like you don't have all the needed visualization dependencies."
        )