could you help adapt below code to use CP-SAT? @Slf4j public class NetOptSolver {…
- User
could you help adapt below code to use CP-SAT? @Slf4j public class NetOptSolver { private final Set activeLineIds; private final Set restLineIds; private final List allItems; private final List lineRoads; private final List stopStopDists; private final List odList;
public TransNetData getObj() { return obj; } private TransNetData obj; private Map<String, List<LineDist>> stopPairLineDistMap; private Int2ObjectMap<IntSet> odDirectCoverMap; private Int2ObjectMap<IntSet> odTransCoverMap; private Int2ObjectMap<Set<String>> odTwoTransCoverMap; public NetOptSolver(Set<Integer> activeLineIds, Set<Integer> restLineIds, List<LinePoolItem> allItems, List<LineRoad> lineRoads, List<StopStopDist> stopStopDists, List<LineNetOd> odList) { this.activeLineIds = activeLineIds; this.restLineIds = restLineIds; this.allItems = allItems; this.lineRoads = lineRoads; this.stopStopDists = stopStopDists; this.odList = odList; } public Int2ObjectMap<IntSet> getOdDirectCoverMap() { return odDirectCoverMap; } public Int2ObjectMap<IntSet> getOdTransCoverMap() { return odTransCoverMap; } public Int2ObjectMap<Set<String>> getOdTwoTransCoverMap() { return odTwoTransCoverMap; } public SolverOutput solve(boolean twoTrans, boolean coverOnly) { obj = prepareTransNetData(allItems, lineRoads, stopStopDists); stopPairLineDistMap = buildStopPairLineDistMap(obj.getPathLines()); odDirectCoverMap = calculateOdDirectCoverMap(odList, stopPairLineDistMap); odTransCoverMap = calculateOdTransCoverMap(odList, obj.getStopOnLinesMap(), obj.getStopNeighbourMap(), stopPairLineDistMap, odDirectCoverMap); if (twoTrans) { odTwoTransCoverMap = calculateOdTwoTransCoverMap(odList, obj.getStopOnLinesMap(), obj.getStopNeighbourMap(), stopPairLineDistMap, odDirectCoverMap); } else { odTwoTransCoverMap = new Int2ObjectOpenHashMap<>(); } boolean feasible = true; for (LineNetOd od : odList) { if (!odDirectCoverMap.containsKey(od.getOdId()) && !odTransCoverMap.containsKey(od.getOdId()) && !odTwoTransCoverMap.containsKey(od.getOdId())) { log.info("Not feasible: " + od.getOdId()); feasible = false; } } if (!feasible) { return new SolverOutput(false, false, null); } if (coverOnly) { return new SolverOutput(true, false, null); } // 7. Solve integer programming problem. return solveIntegerProgrammingProblem(activeLineIds, restLineIds); } public SolverOutput solveIntegerProgrammingProblem(Set<Integer> activeLineIds, Set<Integer> restLineIds) { MPSolver solver = MPSolver.createSolver("SCIP"); solver.setSolverSpecificParametersAsString("limits/time=3600\n" + "limits/gap=0.1\n" + "randomization/randomseedshift=42\n"); solver.enableOutput(); // 1. Decision variable x: which line will be chosen. Map<Integer, MPVariable> xLid = new HashMap<>(activeLineIds.size()); activeLineIds.forEach(lid -> xLid.put(lid, solver.makeBoolVar("x_" + lid))); // 3. Objective: minimize total miles MPObjective objective = solver.objective(); for (Map.Entry<Integer, MPVariable> entry : xLid.entrySet()) { int lid = entry.getKey(); MPVariable var = entry.getValue(); objective.setCoefficient(var, obj.getLineLengthMap().get(lid)); } objective.setMinimization(); // 4. Cover all the ods. for (LineNetOd od : odList) { int odId = od.getOdId(); MPConstraint ct = solver.makeConstraint(1, Double.POSITIVE_INFINITY, "cov_" + odId); // 1) Direct cover. Set<Integer> lineIds = odDirectCoverMap.get(odId); if (lineIds != null) { for (Integer lineId : lineIds) { if (activeLineIds.contains(lineId)) { ct.setCoefficient(xLid.get(lineId), 1); } } } // 2) One trans cover. Set<Integer> transStops = odTransCoverMap.get(odId); if (transStops != null) { for (Integer transStop : transStops) { handleOneTransStop(od, solver, xLid, ct, transStop, activeLineIds, restLineIds); } } // 3) Two trans cover. Set<String> transStopPairs = odTwoTransCoverMap.get(odId); if (transStopPairs != null) { for (String transStopPair : transStopPairs) { handleOneTransStopPair(od, solver, xLid, ct, transStopPair, activeLineIds, restLineIds); } } } // 4. Solve. log.info("Number of variables: " + solver.numVariables()); log.info("Number of constraints: " + solver.numConstraints()); MPSolver.ResultStatus status = solver.solve(); if (status != MPSolver.ResultStatus.OPTIMAL && status != MPSolver.ResultStatus.FEASIBLE) { if (status == MPSolver.ResultStatus.INFEASIBLE) { System.out.println("Problem is infeasible"); } else if (status == MPSolver.ResultStatus.UNBOUNDED) { System.out.println("Problem is unbounded"); } else { System.out.println("Solver stopped with status: " + status); } return new SolverOutput(false, false, null); } double objectiveValue = solver.objective().value(); log.info("Final objective value: " + objectiveValue); // 5. Retrieve result. List<Integer> lineIds = new ArrayList<>(); for (Map.Entry<Integer, MPVariable> entry : xLid.entrySet()) { if (entry.getValue().solutionValue() > 0.5) { lineIds.add(entry.getKey()); } } solver.delete(); return new SolverOutput(true, status == MPSolver.ResultStatus.OPTIMAL, lineIds); } private void handleOneTransStop(LineNetOd od, MPSolver solver, Map<Integer, MPVariable> xLid, MPConstraint ct, int transStop, Set<Integer> activeLineIds, Set<Integer> restLineIds) { int odId = od.getOdId(); String stopPair = od.getNodeId1() + "->" + transStop; List<LineDist> lineDistList = stopPairLineDistMap.get(stopPair); Set<Integer> originLineIds = lineDistList.stream().map(o -> o.getPathLine().getLineId()).collect(Collectors.toSet()); if (originLineIds.size() == 0) { return; } // Add z variable String transferKey = odId + "-" + transStop; MPVariable zVar; zVar = solver.makeBoolVar("z_" + transferKey); ct.setCoefficient(zVar, 1); // 4. Constraint: in case trans cover is chosen, related origin line has to be chosen. addTransferCoverageConstraint(solver, "orig_" + transferKey, xLid, zVar, originLineIds, activeLineIds, restLineIds); // 5. Constraint: in case trans cover is chosen, related destination line has to be chosen. List<WalkNeighbourStop> neighbourStops = obj.getStopNeighbourMap().get(transStop); if (neighbourContainsDestinationStop(neighbourStops, od.getNodeId2())) { return; } Set<Integer> destLineIds = getCoverLineIds(transStop, od.getNodeId2(), neighbourStops); addTransferCoverageConstraint(solver, "dest_" + transferKey, xLid, zVar, destLineIds, activeLineIds, restLineIds); } private void handleOneTransStopPair(LineNetOd od, MPSolver solver, Map<Integer, MPVariable> xLid, MPConstraint ct, String transStopPair, Set<Integer> activeLineIds, Set<Integer> restLineIds) { int odId = od.getOdId(); String[] stopPairStrings = transStopPair.split("-"); int transStop1 = Integer.parseInt(stopPairStrings[0]); int transStop2 = Integer.parseInt(stopPairStrings[1]); String stopPair = od.getNodeId1() + "->" + transStop1; List<LineDist> lineDistList = stopPairLineDistMap.get(stopPair); Set<Integer> originLineIds = lineDistList.stream().map(o -> o.getPathLine().getLineId()).collect(Collectors.toSet()); if (originLineIds.size() == 0) { return; } // Add y variable String transferKey = odId + "_" + transStopPair; MPVariable yVar; yVar = solver.makeBoolVar("y_" + transferKey); ct.setCoefficient(yVar, 1); // 4. Constraint: in case trans cover is chosen, related origin line has to be chosen. addTransferCoverageConstraint(solver, "orig2_" + transferKey, xLid, yVar, originLineIds, activeLineIds, restLineIds); // 5. Constraint: in case trans cover is chosen, related middle line has to be chosen. List<WalkNeighbourStop> neighbourStops = obj.getStopNeighbourMap().get(transStop1); Set<Integer> midLineIds = getCoverLineIds(transStop1, transStop2, neighbourStops); addTransferCoverageConstraint(solver, "mid_" + transferKey, xLid, yVar, midLineIds, activeLineIds, restLineIds); // 6. Constraint: in case trans cover is chosen, related destination line has to be chosen. List<WalkNeighbourStop> neighbourStops2 = obj.getStopNeighbourMap().get(transStop2); if (neighbourContainsDestinationStop(neighbourStops2, od.getNodeId2())) { return; } Set<Integer> destLineIds = getCoverLineIds(transStop2, od.getNodeId2(), neighbourStops2); addTransferCoverageConstraint(solver, "dest2_" + transferKey, xLid, yVar, destLineIds, activeLineIds, restLineIds); } private void addTransferCoverageConstraint(MPSolver solver, String ctName, Map<Integer, MPVariable> xLid, MPVariable xyVar, Set<Integer> coverLineIds, Set<Integer> activeLineIds, Set<Integer> restLineIds) { Set<Integer> restLineIdsCp = new HashSet<>(restLineIds); restLineIdsCp.retainAll(coverLineIds); if (restLineIdsCp.size() == 0) { MPConstraint ctDest = solver.makeConstraint(0, Double.POSITIVE_INFINITY, ctName); for (int lineId : coverLineIds) { if (activeLineIds.contains(lineId)) { ctDest.setCoefficient(xLid.get(lineId), 1); } } ctDest.setCoefficient(xyVar, -1); } } private Set<Integer> getCoverLineIds(int nodeId1, int nodeId2, List<WalkNeighbourStop> node1neighbours) { Set<Integer> coverLineIds = new HashSet<>(); List<LineDist> lineDists = stopPairLineDistMap.get(nodeId1 + "->" + nodeId2); if (lineDists != null) { coverLineIds.addAll(lineDists.stream().map(o -> o.getPathLine().getLineId()).collect(Collectors.toList())); } if (node1neighbours != null) { for (WalkNeighbourStop neighbour : node1neighbours) { lineDists = stopPairLineDistMap.get(neighbour.getStopId() + "->" + nodeId2); if (lineDists != null) { coverLineIds.addAll(lineDists.stream().map(o -> o.getPathLine().getLineId()).collect(Collectors.toList())); } } } return coverLineIds; } private boolean neighbourContainsDestinationStop(List<WalkNeighbourStop> neighbourStops, int destinationStopId) { if (neighbourStops != null) { for (WalkNeighbourStop neighbourStop : neighbourStops) { if (neighbourStop.getStopId() == destinationStopId) { return true; } } } return false; } private Map<String, List<LineDist>> buildStopPairLineDistMap(List<PathLine> pathLines) { Map<String, List<LineDist>> stopPairLineDistMap = new ConcurrentHashMap<>(); pathLines.parallelStream().forEach(pathLine -> { List<Integer> stops = pathLine.getStops(); List<Integer> accLens = pathLine.getAccLens(); for (int i = 0; i < stops.size() - 1; i++) { for (int j = i + 1; j < stops.size(); j++) { String key = stops.get(i) + "->" + stops.get(j); int dist = accLens.get(j) - accLens.get(i); stopPairLineDistMap.computeIfAbsent(key, k -> Collections.synchronizedList(new ArrayList<>())) .add(new LineDist(pathLine, dist)); } } }); // 6. After parallel population in calculateLineTransferKeys: stopPairLineDistMap.replaceAll((k, v) -> new ArrayList<>(v)); return stopPairLineDistMap; } private Int2ObjectMap<IntSet> calculateOdDirectCoverMap(List<LineNetOd> odList, Map<String, List<LineDist>> stopPairLineDistMap) { Int2ObjectMap<IntSet> odDirectLineMap = new Int2ObjectOpenHashMap<>(odList.size()); odList.parallelStream().forEach(od -> { String key = od.getNodeId1() + "->" + od.getNodeId2(); List<LineDist> lineDistList = stopPairLineDistMap.get(key); if (lineDistList == null) { return; } Set<Integer> lineIds = lineDistList.stream().filter(o -> o.getDistance() <= od.getDistance2()).map(o -> o.getPathLine().getLineId()).collect(Collectors.toSet()); synchronized (odDirectLineMap) { odDirectLineMap.put(od.getOdId(), new IntOpenHashSet(lineIds)); } }); return odDirectLineMap; } private Int2ObjectMap<IntSet> calculateOdTransCoverMap(List<LineNetOd> odList, Map<Integer, List<PathLine>> stopOnLinesMap, Map<Integer, List<WalkNeighbourStop>> stopNeighbourMap, Map<String, List<LineDist>> stopPairLineDistMap, Int2ObjectMap<IntSet> odDirectCoverMap) { ConcurrentMap<Integer, IntSet> resultMap = new ConcurrentHashMap<>(); odList.parallelStream().forEach(od -> { Int2ObjectMap<IntSet> threadLocalMap = new Int2ObjectOpenHashMap<>(); List<PathLine> originLines = stopOnLinesMap.get(od.getNodeId1()); if (originLines == null) return; for (PathLine pathLine : originLines) { if (odDirectCoverMap.containsKey(od.getOdId()) && odDirectCoverMap.get(od.getOdId()).contains(pathLine.getLineId())) { continue; } int idx = pathLine.getStopIndices().get(od.getNodeId1()); for (int i = idx + 1; i < pathLine.getStops().size(); i++) { int transStop = pathLine.getStops().get(i); if (transStop == od.getNodeId2()) break; int accDist = pathLine.getAccLens().get(i) - pathLine.getAccLens().get(idx); boolean match = checkTransferStop(od, new WalkNeighbourStop(transStop, 0), pathLine, accDist, stopPairLineDistMap, odDirectCoverMap); if (match) { threadLocalMap.computeIfAbsent(od.getOdId(), k -> new IntOpenHashSet()).add(transStop); continue; } List<WalkNeighbourStop> neighbourStops = stopNeighbourMap.get(transStop); if (neighbourStops == null) continue; for (WalkNeighbourStop neighbourStop : neighbourStops) { match = checkTransferStop(od, neighbourStop, pathLine, accDist, stopPairLineDistMap, odDirectCoverMap); if (match) { threadLocalMap.computeIfAbsent(od.getOdId(), k -> new IntOpenHashSet()).add(transStop); break; } } } } // Merge thread-local results into the global map threadLocalMap.forEach((odId, transStops) -> resultMap.merge(odId, transStops, (existingSet, newSet) -> { existingSet.addAll(newSet); return existingSet; })); }); return new Int2ObjectOpenHashMap<>(resultMap); } private Int2ObjectMap<Set<String>> calculateOdTwoTransCoverMap(List<LineNetOd> odList, Map<Integer, List<PathLine>> stopOnLinesMap, Map<Integer, List<WalkNeighbourStop>> stopNeighbourMap, Map<String, List<LineDist>> stopPairLineDistMap, Int2ObjectMap<IntSet> odDirectCoverMap) { ConcurrentMap<Integer, Set<String>> resultMap = new ConcurrentHashMap<>(); odList.parallelStream().forEach(od -> { Int2ObjectMap<Set<String>> threadLocalMap = new Int2ObjectOpenHashMap<>(); List<PathLine> originLines = stopOnLinesMap.get(od.getNodeId1()); if (originLines == null) { return; } for (PathLine originLine : originLines) { if (odDirectCoverMap.containsKey(od.getOdId()) && odDirectCoverMap.get(od.getOdId()).contains(originLine.getLineId())) { // If the line can directly cover the od, then transfer is not the option. continue; } int idx = originLine.getStopIndices().get(od.getNodeId1()); for (int i = idx + 1; i < originLine.getStops().size(); i++) { int transStop = originLine.getStops().get(i); int accDist = originLine.getAccLens().get(i) - originLine.getAccLens().get(idx); // Handle one transStop. handleFirstTransStop(threadLocalMap, od, originLine, transStop, accDist, stopOnLinesMap, stopNeighbourMap, stopPairLineDistMap, odDirectCoverMap); } } // Merge thread-local results into the global map threadLocalMap.forEach((odId, transStops) -> resultMap.merge(odId, transStops, (existingSet, newSet) -> { existingSet.addAll(newSet); return existingSet; })); }); return new Int2ObjectOpenHashMap<>(resultMap); } private boolean checkTransferStop(LineNetOd od, WalkNeighbourStop neighbourStop, PathLine originPathLine, int accDist, Map<String, List<LineDist>> stopPairLineDistMap, Int2ObjectMap<IntSet> odDirectCoverMap) { if (neighbourStop.getStopId() == od.getNodeId2()) { return neighbourStop.getDistance() + accDist <= od.getDistance2(); } List<LineDist> lineDistList = stopPairLineDistMap.get(neighbourStop.getStopId() + "->" + od.getNodeId2()); if (lineDistList == null) { return false; } for (LineDist lineDist : lineDistList) { if (lineDist.getPathLine() == originPathLine) { continue; } if (odDirectCoverMap.containsKey(od.getOdId()) && odDirectCoverMap.get(od.getOdId()).contains(lineDist.getPathLine().getLineId())) { continue; } if (lineDist.getDistance() + accDist + neighbourStop.getDistance() <= od.getDistance2()) { return true; } } return false; } private void handleFirstTransStop(Int2ObjectMap<Set<String>> threadLocalMap, LineNetOd od, PathLine originLine, int transStop, int accDist, Map<Integer, List<PathLine>> stopOnLinesMap, Map<Integer, List<WalkNeighbourStop>> stopNeighbourMap, Map<String, List<LineDist>> stopPairLineDistMap, Int2ObjectMap<IntSet> odDirectCoverMap) { List<PathLine> midLines = stopOnLinesMap.get(transStop); for (PathLine midLine: midLines) { handleFirstTransStopOneMidLine(midLine, threadLocalMap, od, originLine, transStop, transStop, accDist, stopNeighbourMap, stopPairLineDistMap, odDirectCoverMap); } List<WalkNeighbourStop> neighbourStops = stopNeighbourMap.get(transStop); if (neighbourStops == null) { return; } for (WalkNeighbourStop neighbourStop : neighbourStops) { int dist = accDist + neighbourStop.getDistance(); List<PathLine> lines = stopOnLinesMap.get(neighbourStop.getStopId()); if (lines == null) { continue; } for (PathLine midLine: lines) { handleFirstTransStopOneMidLine(midLine, threadLocalMap, od, originLine, transStop, neighbourStop.getStopId(), dist, stopNeighbourMap, stopPairLineDistMap, odDirectCoverMap); } } } private void handleFirstTransStopOneMidLine(PathLine midLine, Int2ObjectMap<Set<String>> threadLocalMap, LineNetOd od, PathLine originLine, int transStop, int curStop, int accDist, Map<Integer, List<WalkNeighbourStop>> stopNeighbourMap, Map<String, List<LineDist>> stopPairLineDistMap, Int2ObjectMap<IntSet> odDirectCoverMap) { if (midLine.getLineId() == originLine.getLineId()) { // Has to transfer. return; } if (odDirectCoverMap.containsKey(od.getOdId()) && odDirectCoverMap.get(od.getOdId()).contains(originLine.getLineId())) { // If the line can directly cover the od, then transfer is not the option. return; } int idx2 = midLine.getStopIndices().get(curStop); for (int j = idx2 + 1; j < midLine.getStops().size(); j++) { int transStop2 = midLine.getStops().get(j); accDist += midLine.getAccLens().get(j) - midLine.getAccLens().get(idx2); boolean match = checkTransferStop(od, new WalkNeighbourStop(transStop2, 0), midLine, accDist, stopPairLineDistMap, odDirectCoverMap); if (match) { threadLocalMap.computeIfAbsent(od.getOdId(), k -> new HashSet<>()).add(transStop + "-" + transStop2); continue; } List<WalkNeighbourStop> neighbourStops = stopNeighbourMap.get(transStop2); if (neighbourStops == null) { continue; } for (WalkNeighbourStop neighbourStop : neighbourStops) { match = checkTransferStop(od, neighbourStop, midLine, accDist, stopPairLineDistMap, odDirectCoverMap); if (match) { threadLocalMap.computeIfAbsent(od.getOdId(), k -> new HashSet<>()).add(transStop + "-" + transStop2); break; } } } } Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.