Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parallelize runJsprit #3229

Merged
merged 2 commits into from
Apr 24, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@
import javax.management.InvalidAttributeValueException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -192,7 +194,7 @@ public static void runJsprit(Scenario scenario) throws ExecutionException, Inter
// Fill carrierActivityCounterMap -> basis for sorting the carriers by number of activities before solving in parallel
for (Carrier carrier : carriers.getCarriers().values()) {
carrierActivityCounterMap.put(carrier.getId(), carrierActivityCounterMap.getOrDefault(carrier.getId(), 0) + carrier.getServices().size());
carrierActivityCounterMap.put(carrier.getId(), carrierActivityCounterMap.getOrDefault(carrier.getId(), 0) + carrier.getShipments().size());
carrierActivityCounterMap.put(carrier.getId(), carrierActivityCounterMap.getOrDefault(carrier.getId(), 0) + 2*carrier.getShipments().size());
}

HashMap<Id<Carrier>, Integer> sortedMap = carrierActivityCounterMap.entrySet().stream()
Expand All @@ -203,53 +205,73 @@ public static void runJsprit(Scenario scenario) throws ExecutionException, Inter
AtomicInteger solvedVRPCounter = new AtomicInteger(0);

ArrayList<Id<Carrier>> tempList = new ArrayList<>(sortedMap.keySet());
ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
forkJoinPool.submit(() -> tempList.parallelStream().forEach(carrierId -> {
Carrier carrier = carriers.getCarriers().get(carrierId);

double start = System.currentTimeMillis();
if (!carrier.getServices().isEmpty())
log.info("Start tour planning for {} which has {} services", carrier.getId(), carrier.getServices().size());
else if (!carrier.getShipments().isEmpty())
log.info("Start tour planning for {} which has {} shipments", carrier.getId(), carrier.getShipments().size());

startedVRPCounter.incrementAndGet();
log.info("started VRP solving for carrier number {} out of {} carriers.", startedVRPCounter.get(), carriers.getCarriers().size());

VehicleRoutingProblem problem = MatsimJspritFactory.createRoutingProblemBuilder(carrier, scenario.getNetwork()).setRoutingCost(netBasedCosts).build();
VehicleRoutingAlgorithm algorithm = MatsimJspritFactory.loadOrCreateVehicleRoutingAlgorithm(scenario, freightCarriersConfigGroup, netBasedCosts, problem);

algorithm.getAlgorithmListeners().addListener(new StopWatch(), VehicleRoutingAlgorithmListeners.Priority.HIGH);
int jspritIterations = getJspritIterations(carrier);
try {
if (jspritIterations > 0) {
algorithm.setMaxIterations(jspritIterations);
} else {
throw new InvalidAttributeValueException(
"Carrier has invalid number of jsprit iterations. They must be positive! Carrier id: "
+ carrier.getId().toString());}
} catch (Exception e) {
throw new RuntimeException(e);
// e.printStackTrace();
}

VehicleRoutingProblemSolution solution = Solutions.bestOf(algorithm.searchSolutions());
int nThreads = Runtime.getRuntime().availableProcessors();
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
List<List<Id<Carrier>>> splitList = splitListAlternating(nThreads, tempList);
for (List<Id<Carrier>> subList : splitList) {
executorService.submit(() -> subList.forEach(carrierId -> {
Carrier carrier = carriers.getCarriers().get(carrierId);

double start = System.currentTimeMillis();
if (!carrier.getServices().isEmpty())
log.info("Start tour planning for {} which has {} services", carrier.getId(), carrier.getServices().size());
else if (!carrier.getShipments().isEmpty())
log.info("Start tour planning for {} which has {} shipments", carrier.getId(), carrier.getShipments().size());

startedVRPCounter.incrementAndGet();
log.info("started VRP solving for carrier number {} out of {} carriers.", startedVRPCounter.get(), carriers.getCarriers().size());

VehicleRoutingProblem problem = MatsimJspritFactory.createRoutingProblemBuilder(carrier, scenario.getNetwork()).setRoutingCost(netBasedCosts).build();
VehicleRoutingAlgorithm algorithm = MatsimJspritFactory.loadOrCreateVehicleRoutingAlgorithm(scenario, freightCarriersConfigGroup, netBasedCosts, problem);

algorithm.getAlgorithmListeners().addListener(new StopWatch(), VehicleRoutingAlgorithmListeners.Priority.HIGH);
int jspritIterations = getJspritIterations(carrier);
try {
if (jspritIterations > 0) {
algorithm.setMaxIterations(jspritIterations);
} else {
throw new InvalidAttributeValueException(
"Carrier has invalid number of jsprit iterations. They must be positive! Carrier id: "
+ carrier.getId().toString());}
} catch (Exception e) {
throw new RuntimeException(e);
// e.printStackTrace();
}

VehicleRoutingProblemSolution solution = Solutions.bestOf(algorithm.searchSolutions());

log.info("tour planning for carrier {} took {} seconds.", carrier.getId(), (System.currentTimeMillis() - start) / 1000);

log.info("tour planning for carrier {} took {} seconds.", carrier.getId(), (System.currentTimeMillis() - start) / 1000);
CarrierPlan newPlan = MatsimJspritFactory.createPlan(carrier, solution);
// yy In principle, the carrier should know the vehicle types that it can deploy.

CarrierPlan newPlan = MatsimJspritFactory.createPlan(carrier, solution);
// yy In principle, the carrier should know the vehicle types that it can deploy.
log.info("routing plan for carrier {}", carrier.getId());
NetworkRouter.routePlan(newPlan, netBasedCosts);
solvedVRPCounter.incrementAndGet();
log.info("routing for carrier {} finished. Tour planning plus routing took {} seconds.", carrier.getId(),
(System.currentTimeMillis() - start) / 1000);
log.info("solved {} out of {} carriers.", solvedVRPCounter.get(), carriers.getCarriers().size());

log.info("routing plan for carrier {}", carrier.getId());
NetworkRouter.routePlan(newPlan, netBasedCosts);
solvedVRPCounter.incrementAndGet();
log.info("routing for carrier {} finished. Tour planning plus routing took {} seconds.", carrier.getId(),
(System.currentTimeMillis() - start) / 1000);
log.info("solved {} out of {} carriers.", solvedVRPCounter.get(), carriers.getCarriers().size());
carrier.setSelectedPlan(newPlan);
})).get();
}
}

carrier.setSelectedPlan(newPlan);
})).get();
// split tempList in nThreads parts such that it is split to 1,2,...,n,1,2,..
private static List<List<Id<Carrier>>> splitListAlternating(int nThreads, ArrayList<Id<Carrier>> tempList) {
List<List<Id<Carrier>>> splitList = new ArrayList<>();
for (int i = 0; i < nThreads; i++) {
List<Id<Carrier>> subList = new ArrayList<>();
for (int j = i; j < tempList.size(); j += nThreads) {
subList.add(tempList.get(j));
}
splitList.add(subList);
}

assert splitList.size() == nThreads;
assert splitList.stream().mapToInt(List::size).sum() == tempList.size();
return splitList;
}

/**
Expand Down