Skip to content

Commit

Permalink
fixing style #22
Browse files Browse the repository at this point in the history
  • Loading branch information
behrisch committed Sep 9, 2023
1 parent 3f8288c commit 9621c80
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
netedit.modifyAttribute(netedit.attrs.jpsObstacle.inspect.shape, "12.00,8.00", False)

# Change parameter 1 with a valid value
netedit.modifyAttribute(netedit.attrs.jpsObstacle.inspect.shape, "12.00,8.00 9.00,13.00 12.00,18.00 7.00,15.00 2.00,18.00 " +
netedit.modifyAttribute(netedit.attrs.jpsObstacle.inspect.shape,
"12.00,8.00 9.00,13.00 12.00,18.00 7.00,15.00 2.00,18.00 " +
"5.00,13.00 2.00,8.00 7.00,11.00 12.00,8.00", False)

# Check undos and redos
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
netedit.modifyAttribute(netedit.attrs.jpsSink.inspect.shape, "12.00,8.00", False)

# Change parameter 1 with a valid value
netedit.modifyAttribute(netedit.attrs.jpsSink.inspect.shape, "12.00,8.00 9.00,13.00 12.00,18.00 7.00,15.00 2.00,18.00 " +
netedit.modifyAttribute(netedit.attrs.jpsSink.inspect.shape,
"12.00,8.00 9.00,13.00 12.00,18.00 7.00,15.00 2.00,18.00 " +
"5.00,13.00 2.00,8.00 7.00,11.00 12.00,8.00", False)

# Check undos and redos
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
netedit.modifyAttribute(netedit.attrs.jpsSource.inspect.shape, "12.00,8.00", False)

# Change parameter 1 with a valid value
netedit.modifyAttribute(netedit.attrs.jpsSource.inspect.shape, "12.00,8.00 9.00,13.00 12.00,18.00 7.00,15.00 2.00,18.00 " +
netedit.modifyAttribute(netedit.attrs.jpsSource.inspect.shape,
"12.00,8.00 9.00,13.00 12.00,18.00 7.00,15.00 2.00,18.00 " +
"5.00,13.00 2.00,8.00 7.00,11.00 12.00,8.00", False)

# Check undos and redos
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
netedit.modifyAttribute(netedit.attrs.jpsWaitingArea.inspect.shape, "12.00,8.00", False)

# Change parameter 1 with a valid value
netedit.modifyAttribute(netedit.attrs.jpsWaitingArea.inspect.shape, "12.00,8.00 9.00,13.00 12.00,18.00 7.00,15.00 2.00,18.00 " +
netedit.modifyAttribute(netedit.attrs.jpsWaitingArea.inspect.shape,
"12.00,8.00 9.00,13.00 12.00,18.00 7.00,15.00 2.00,18.00 " +
"5.00,13.00 2.00,8.00 7.00,11.00 12.00,8.00", False)

# Check undos and redos
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
netedit.modifyAttribute(netedit.attrs.jpsWalkableArea.inspect.shape, "12.00,8.00", False)

# Change parameter 1 with a valid value
netedit.modifyAttribute(netedit.attrs.jpsWalkableArea.inspect.shape, "12.00,8.00 9.00,13.00 12.00,18.00 7.00,15.00 2.00,18.00 " +
netedit.modifyAttribute(netedit.attrs.jpsWalkableArea.inspect.shape,
"12.00,8.00 9.00,13.00 12.00,18.00 7.00,15.00 2.00,18.00 " +
"5.00,13.00 2.00,8.00 7.00,11.00 12.00,8.00", False)

# Check undos and redos
Expand Down
39 changes: 23 additions & 16 deletions tools/drt/drtOrtools.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,13 @@ class CostType(Enum):
TIME = 2


def dispatch(reservations, fleet, time_limit, cost_type, drf, waiting_time, end, fix_allocation, solution_requests, verbose):
def dispatch(reservations, fleet, time_limit, cost_type, drf, waiting_time, end,
fix_allocation, solution_requests, verbose):
"""Dispatch using ortools."""
if verbose:
print('Start creating the model.')
data = create_data_model(reservations, fleet, cost_type, drf, waiting_time, end, fix_allocation, solution_requests, verbose)
data = create_data_model(reservations, fleet, cost_type, drf, waiting_time, end,
fix_allocation, solution_requests, verbose)
if verbose:
print('Start solving the problem.')
solution_ortools = ortools_pdp.main(data, time_limit, verbose)
Expand All @@ -64,7 +66,8 @@ def dispatch(reservations, fleet, time_limit, cost_type, drf, waiting_time, end,
return solution_requests


def create_data_model(reservations, fleet, cost_type, drf, waiting_time, end, fix_allocation, solution_requests, verbose):
def create_data_model(reservations, fleet, cost_type, drf, waiting_time, end,
fix_allocation, solution_requests, verbose):
"""Creates the data for the problem."""
n_vehicles = len(fleet)
# use only reservations that haven't been picked up yet; reservation.state!=8 (not picked up)
Expand Down Expand Up @@ -127,7 +130,7 @@ def create_data_model(reservations, fleet, cost_type, drf, waiting_time, end, fi
cost_matrix, time_matrix = get_cost_matrix(edges, type_vehicle, cost_type, pickup_indices, dropoff_indices)

# safe cost and time matrix
#if verbose:
# if verbose:
# import csv
# with open("cost_matrix.csv", 'a') as cost_file:
# wr = csv.writer(cost_file)
Expand Down Expand Up @@ -350,7 +353,8 @@ def solution_by_requests(solution_ortools, reservations, data, verbose=False):
return solution_requests


def run(end=None, interval=30, time_limit=10, cost_type='distance', drf=1.5, waiting_time=900, fix_allocation=False, verbose=False):
def run(end=None, interval=30, time_limit=10, cost_type='distance', drf=1.5, waiting_time=900,
fix_allocation=False, verbose=False):
"""
Execute the TraCI control loop and run the scenario.
Expand Down Expand Up @@ -425,9 +429,10 @@ def run(end=None, interval=30, time_limit=10, cost_type='distance', drf=1.5, wai

fleet = traci.vehicle.getTaxiFleet(-1)
reservations_not_assigned = traci.person.getTaxiReservations(3)

# find and remove unassigned reservations that cannot be picked up by time
reservations_removed = [res for res in reservations_not_assigned if res.reservationTime + waiting_time < timestep]
reservations_removed = [
res for res in reservations_not_assigned if res.reservationTime + waiting_time < timestep]
for res in reservations_removed:
for person in res.persons:
traci.person.removeStages(person)
Expand All @@ -454,8 +459,8 @@ def run(end=None, interval=30, time_limit=10, cost_type='distance', drf=1.5, wai
if reservations_not_assigned:
if verbose:
print("Solve CPDP")
solution_requests = dispatch(reservations_all, fleet, time_limit,
cost_type, drf, waiting_time, int(end), fix_allocation, solution_requests, verbose)
solution_requests = dispatch(reservations_all, fleet, time_limit, cost_type, drf, waiting_time, int(end),
fix_allocation, solution_requests, verbose)
if solution_requests is not None:
for index_vehicle in solution_requests: # for each vehicle
id_vehicle = fleet[index_vehicle]
Expand Down Expand Up @@ -503,8 +508,8 @@ def get_arguments():
ap.add_argument("-a", "--fix-allocation", action="store_true", default=False,
help="if true: after first solution the allocation of reservations to vehicles" +
"does not change anymore")
ap.add_argument("-w", "--waiting-time", type = ap.time, default = 900,
help = "maximum waiting time to serve a request in s")
ap.add_argument("-w", "--waiting-time", type=ap.time, default=900,
help="maximum waiting time to serve a request in s")
return ap.parse_args()


Expand All @@ -523,10 +528,12 @@ def check_set_arguments(arguments):
raise ValueError(f"Wrong cost type '{arguments.cost_type}'. Only 'distance' and 'time' are allowed.")

if arguments.drf < 1 and arguments.drf != -1:
raise ValueError(f"Wrong value for drf '{arguments.drf}'. Value must be equal or greater than 1. -1 means no drf is used.")

raise ValueError(
f"Wrong value for drf '{arguments.drf}'. Value must be equal or greater than 1. -1 means no drf is used.")

if arguments.waiting_time < 0:
raise ValueError(f"Wrong value for waiting time '{arguments.waiting_time}'. Value must be equal or greater than 0.")
raise ValueError(
f"Wrong value for waiting time '{arguments.waiting_time}'. Value must be equal or greater than 0.")


if __name__ == "__main__":
Expand All @@ -539,5 +546,5 @@ def check_set_arguments(arguments):
# this is the normal way of using traci. sumo is started as a
# subprocess and then the python script connects and runs
traci.start([arguments.sumoBinary, "-c", arguments.sumo_config])
run(arguments.end, arguments.interval,
arguments.time_limit, arguments.cost_type, arguments.drf, arguments.waiting_time, arguments.fix_allocation, arguments.verbose)
run(arguments.end, arguments.interval, arguments.time_limit, arguments.cost_type, arguments.drf,
arguments.waiting_time, arguments.fix_allocation, arguments.verbose)
39 changes: 20 additions & 19 deletions tools/drt/ortools_pdp.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,14 +254,17 @@ def time_callback(from_index, to_index):
time_dimension = routing.GetDimensionOrDie(dimension_name)
return time_dimension


def add_time_windows_constraint(data, time_dimension, manager, verbose):
if verbose:
print(' Add time windows constraints...')

depot = data['depot']
new_requests_nodes = [node for req in data['pickups_deliveries'] for node in (req.from_node, req.to_node) if req.is_new]
new_requests_nodes = [node for req in data['pickups_deliveries']
for node in (req.from_node, req.to_node) if req.is_new]
old_requests_nodes = ([req.to_node for req in data['dropoffs']] +
[node for req in data['pickups_deliveries'] for node in (req.from_node, req.to_node) if not req.is_new])
[node for req in data['pickups_deliveries']
for node in (req.from_node, req.to_node) if not req.is_new])
# Add time window constraints for each location except depot.
for location_idx, time_window in enumerate(data['time_windows']):
# no time window for depot:
Expand All @@ -272,17 +275,16 @@ def add_time_windows_constraint(data, time_dimension, manager, verbose):
if location_idx in data['starts'] + new_requests_nodes:
if verbose:
print(f'hard time window for node {location_idx}: [{time_window[0]}, {time_window[1]}]')
time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1]) # TODO: check if set, else ignore it
time_dimension.CumulVar(index).SetRange(
time_window[0], time_window[1]) # TODO: check if set, else ignore it
# soft time window for old requests:
if location_idx in old_requests_nodes:
if verbose:
print(f'soft time window for node {location_idx}: [{time_window[0]}, {time_window[1]}]')
time_dimension.SetCumulVarSoftLowerBound(index, time_window[0], 100)
time_dimension.SetCumulVarSoftUpperBound(index, time_window[1], 100)
#time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])
# time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])



# TODO: check if the followwing is needed
# # Add time window constraints for each vehicle start node.
# depot_idx = data['depot']
Expand Down Expand Up @@ -323,14 +325,13 @@ def add_waiting_time_constraints(data, routing, manager, solver, time_dimension,
# add soft constraint for old reservations
else:
time_dimension.SetCumulVarSoftUpperBound(
pickup_index,
maximum_pickup_time,
100) # cost = coefficient * (cumulVar - maximum_pickup_time)
pickup_index,
maximum_pickup_time,
100) # cost = coefficient * (cumulVar - maximum_pickup_time)
if verbose:
print(f"reservation {request.id} has a maximum (soft) pickup time at {maximum_pickup_time}")



def solve_from_initial_solution(routing, manager, search_parameters, data, verbose):
solution_requests = data['initial_routes']
# get inital solution
Expand Down Expand Up @@ -390,20 +391,20 @@ def set_first_solution_heuristic(time_limit_seconds, verbose):
# search_parameters.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_MOST_CONSTRAINED_ARC
# search_parameters.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
search_parameters.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.AUTOMATIC

# search_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH # langsam

# GUIDED_LOCAL_SEARCH seems slow
# search_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH
# search_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GREEDY_DESCENT
search_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.AUTOMATIC

search_parameters.time_limit.FromSeconds(time_limit_seconds)

search_parameters.sat_parameters.num_search_workers = 8
# search_parameters.lns_time_limit.seconds = 7
# search_parameters.solution_limit = 100

# Switch logging on for the search
#search_parameters.log_search = True

# Switch logging on for the search
# search_parameters.log_search = True

return search_parameters

Expand All @@ -417,8 +418,8 @@ def main(data: dict, time_limit_seconds=10, verbose=False):

# Create Routing Model.
routing_parameters = pywrapcp.DefaultRoutingModelParameters()
#routing_parameters.solver_parameters.trace_propagation = True
#routing_parameters.solver_parameters.trace_search = True
# routing_parameters.solver_parameters.trace_propagation = True
# routing_parameters.solver_parameters.trace_search = True
routing = pywrapcp.RoutingModel(manager, routing_parameters)

# get solver
Expand Down Expand Up @@ -451,7 +452,7 @@ def main(data: dict, time_limit_seconds=10, verbose=False):

# Add waiting time constraints.
add_waiting_time_constraints(data, routing, manager, solver, time_dimension, verbose)

print('## Done')
# Setting first solution heuristic.
search_parameters = set_first_solution_heuristic(time_limit_seconds, verbose)
Expand Down
2 changes: 1 addition & 1 deletion tools/randomTrips.py
Original file line number Diff line number Diff line change
Expand Up @@ -922,7 +922,7 @@ def generate_one(idx, departureTime, arrivalTime, period, origin, destination, i
try:
if not main(get_options()):
print("Error: Trips couldn't be generated as requested. "
"Try the --verbose option to output more details on the failure.")
"Try the --verbose option to output more details on the failure.")
sys.exit(1)
except ValueError as e:
print("Error:", e, file=sys.stderr)
Expand Down

0 comments on commit 9621c80

Please sign in to comment.