#!/usr/bin/env python

"""
author: Lu LIU
created at: 2014-07-25
Description:
    a sample of how to use pymmrouting to find multimodal optimal paths in
    transportation networks
"""

from pymmrouting.routeplanner import MultimodalRoutePlanner
from pymmrouting.inferenceengine import RoutingPlanInferer
from termcolor import colored
import datetime
import argparse
import json
import logging.config
import os

LOGGING_CONF_FILE = 'logging.json'
DEFAULT_LOGGING_LVL = logging.INFO
path = LOGGING_CONF_FILE
value = os.getenv('LOG_CFG', None)
if value:
    path = value
if os.path.exists(path):
    with open(path, 'rt') as f:
        config = json.load(f)
    logging.config.dictConfig(config)
else:
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.INFO)

parser = argparse.ArgumentParser()
parser.add_argument("ROUTING_OPTIONS_FILE",
                    help="User-defined options about travelling")
parser.add_argument("-c", "--APP-CONFIG", default="config.json",
                    help="config for client application")
args = parser.parse_args()
ROUTING_OPTIONS_FILE = args.ROUTING_OPTIONS_FILE
CONFIG_FILE = args.APP_CONFIG

with open(ROUTING_OPTIONS_FILE) as f:
    routing_options = json.load(f)

# For multimodal routing, a bunch of options are necessary other than routing
# origin and destination. The acceptable format of multimodal routing options
# are stored in a JSON file.
print "Generating multimodal routing plans... ",
inferer = RoutingPlanInferer()
inferer.load_routing_options(routing_options)
# Routing plans of multimodal paths calculation can be generated by the
# inference engine with the routing options as inputs
routing_plans = inferer.generate_routing_plan()
print colored("done!", "green")
print "Inferred plans: "
for i, p in enumerate(routing_plans):
    print "== " + str(i+1) + ". " + p.description + " =="
    print "modes: " + str(p.mode_list)
    print "switch types: " + str(p.switch_type_list)
    print "source: " + str(p.source)
    print "target: " + str(p.target)
    print "public transits: " + str(p.public_transit_set)
    print "switch constraints: " + str(p.switch_constraint_list)
route_planner = MultimodalRoutePlanner()
# A multimodal network data model is necessary for multimodal path finding. It
# loads network dataset from external sources, e.g. PostgreSQL database, plain
# text file, etc. A multimodal network is assembled on-the-fly according to a
# concrete routing plan
print "Routing from " + \
    colored(str(routing_options['source']['value']['x']) + ',' +
            str(routing_options['source']['value']['y']), 'red') + " to " + \
    colored(str(routing_options['target']['value']['x']) + ',' +
            str(routing_options['target']['value']['y']), 'red')
final_results = route_planner.batch_find_path(routing_plans)
print colored("Finish doing routing plan!", "green")
print "Final refined routing results are: "
for i, r in enumerate(final_results["routes"]):
    print "== " + str(i + 1) + ". " + r["summary"] + " =="
    print "Does it exist? ",
    if r["existence"] is True:
        print colored(str(r["existence"]), "green")
    else:
        print colored(str(r["existence"]), "red")
    print "Total distance: ",
    print colored(str(r["distance"]), "red"),
    print " meters"
    print "Total time (estimated): ",
    print colored(str(datetime.timedelta(minutes=float(r["duration"]))), "red")
    print "Total walking distance: ",
    print colored(str(r["walking_distance"]), "red"),
    print " meters"
    print "Total walking time (estimated): ",
    print colored(str(datetime.timedelta(minutes=float(r["walking_duration"]))), "red")
    print "Multimodal path: "
    print str(r["geojson"])
    print "Switch Points along the path: "
    for sp in r["switch_points"]:
        print colored((sp['properties']['switch_type'] + ": "), "blue")
        print str(sp)
with (open("tmp/multimodal_routing_results.json", 'w')) as result_file:
    result_file.write(json.dumps(final_results))
route_planner.cleanup()

c17c39abb3ea0aa16059d93b90c57d10e2fcb6d1
#!/usr/bin/env python

"""
author: Lu LIU
created at: 2014-07-25
Description:
    a sample of how to use pymmrouting to find multimodal optimal paths in
    transportation networks
"""

from pymmrouting.routeplanner import MultimodalRoutePlanner
from pymmrouting.inferenceengine import RoutingPlanInferer
from termcolor import colored
import datetime
import argparse
import json
import logging.config
import os

LOGGING_CONF_FILE = 'logging.json'
DEFAULT_LOGGING_LVL = logging.INFO
path = LOGGING_CONF_FILE
value = os.getenv('LOG_CFG', None)
if value:
    path = value
if os.path.exists(path):
    with open(path, 'rt') as f:
        config = json.load(f)
    logging.config.dictConfig(config)
else:
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.INFO)

parser = argparse.ArgumentParser()
parser.add_argument("ROUTING_OPTIONS_FILE",
                    help="User-defined options about travelling")
parser.add_argument("-c", "--APP-CONFIG", default="config.json",
                    help="config for client application")
args = parser.parse_args()
ROUTING_OPTIONS_FILE = args.ROUTING_OPTIONS_FILE
CONFIG_FILE = args.APP_CONFIG

with open(ROUTING_OPTIONS_FILE) as f:
    routing_options = json.load(f)

# For multimodal routing, a bunch of options are necessary other than routing
# origin and destination. The acceptable format of multimodal routing options
# are stored in a JSON file.
print "Generating multimodal routing plans... ",
inferer = RoutingPlanInferer()
inferer.load_routing_options(routing_options)
# Routing plans of multimodal paths calculation can be generated by the
# inference engine with the routing options as inputs
routing_plans = inferer.generate_routing_plan()
print colored("done!", "green")
print "Inferred plans: "
for i, p in enumerate(routing_plans):
    print "== " + str(i+1) + ". " + p.description + " =="
    print "modes: " + str(p.mode_list)
    print "switch types: " + str(p.switch_type_list)
    print "source: " + str(p.source)
    print "target: " + str(p.target)
    print "public transits: " + str(p.public_transit_set)
    print "switch constraints: " + str(p.switch_constraint_list)
route_planner = MultimodalRoutePlanner()
# A multimodal network data model is necessary for multimodal path finding. It
# loads network dataset from external sources, e.g. PostgreSQL database, plain
# text file, etc. A multimodal network is assembled on-the-fly according to a
# concrete routing plan
print "Routing from " + \
    colored(str(routing_options['source']['value']['x']) + ',' +
            str(routing_options['source']['value']['y']), 'red') + " to " + \
    colored(str(routing_options['target']['value']['x']) + ',' +
            str(routing_options['target']['value']['y']), 'red')
final_results = route_planner.batch_find_path(routing_plans)
print colored("Finish doing routing plan!", "green")
print "Final refined routing results are: "
for i, r in enumerate(final_results["routes"]):
    print "== " + str(i + 1) + ". " + r["summary"] + " =="
    print "Does it exist? ",
    if r["existence"] is True:
        print colored(str(r["existence"]), "green")
    else:
        print colored(str(r["existence"]), "red")
    print "Total distance: ",
    print colored(str(r["distance"]), "red"),
    print " meters"
    print "Total time (estimated): ",
    print colored(str(datetime.timedelta(minutes=float(r["duration"]))), "red")
    print "Total walking distance: ",
    print colored(str(r["walking_distance"]), "red"),
    print " meters"
    print "Total walking time (estimated): ",
    print colored(str(datetime.timedelta(minutes=float(r["walking_duration"]))), "red")
    print "Multimodal path: "
    print str(r["geojson"])
    print "Switch Points along the path: "
    for sp in r["switch_points"]:
        print colored((sp['properties']['switch_type'] + ": "), "blue")
        print str(sp)
with (open("tmp/multimodal_routing_results.json", 'w')) as result_file:
    result_file.write(json.dumps(final_results))
route_planner.cleanup()
