001/******************************************************************************* 002 * Copyright (c) 2017 Pablo Pavon Marino and others. 003 * All rights reserved. This program and the accompanying materials 004 * are made available under the terms of the 2-clause BSD License 005 * which accompanies this distribution, and is available at 006 * https://opensource.org/licenses/BSD-2-Clause 007 * 008 * Contributors: 009 * Pablo Pavon Marino and others - initial API and implementation 010 *******************************************************************************/ 011 012 013 014 015 016 017 018 019 020 021package com.net2plan.examples.ocnbook.offline; 022 023import cern.colt.matrix.tdouble.*; 024import cern.jet.math.tdouble.DoubleFunctions; 025import com.jom.DoubleMatrixND; 026import com.jom.OptimizationProblem; 027import com.net2plan.interfaces.networkDesign.*; 028import com.net2plan.utils.Constants.RoutingType; 029import com.net2plan.utils.InputParameter; 030import com.net2plan.utils.StringUtils; 031import com.net2plan.utils.Triple; 032 033import java.io.File; 034import java.util.ArrayList; 035import java.util.List; 036import java.util.Map; 037 038/** 039 * Finds the multiperiod (e.g. subsequent years) routing and capacity acquisitions with a MILP formulation 040 * @net2plan.description 041 * @net2plan.keywords Capacity assignment (CA), Modular capacities, Flow assignment (FA), Multiperiod optimization, JOM 042 * @net2plan.ocnbooksections Section 5.2.3 043 * @net2plan.inputParameters 044 * @author Pablo Pavon-Marino 045 */ 046public class Offline_cfa_xpMultiperiodModularCapacities implements IAlgorithm 047{ 048 private InputParameter rootOfNameOfInputTrafficFiles = new InputParameter ("rootOfNameOfInputTrafficFiles", "multiPeriodModularCapacities", "Root of the names of the traffic files. If the root is \"XXX\", the files are XXX_tm0.n2p, XXX_tm1.n2p, ..."); 049 private InputParameter rootOfNameOfOutputFiles = new InputParameter ("rootOfNameOfOutputFiles", "multiPeriodModularCapacities", "Root of the names of the output files. One per input traffic file. If the root is \"XXX\", the files are XXX_res_tm0.n2p, XXX_res_tm1.n2p, ..."); 050 private InputParameter k = new InputParameter ("k", (int) 5 , "Maximum number of admissible paths per demand" , 1 , Integer.MAX_VALUE); 051 private InputParameter shortestPathType = new InputParameter ("shortestPathType", "#select# hops km" , "Criteria to compute the shortest path. Valid values: 'hops' or 'km'"); 052 private InputParameter nonBifurcatedRouting = new InputParameter ("nonBifurcatedRouting", false , "True if the routing is constrained to be non-bifurcated"); 053 private InputParameter maxLengthInKm = new InputParameter ("maxLengthInKm", (double) 2000 , "Paths longer than this are considered not admissible. A non-positive number means this limit does not exist"); 054 private InputParameter solverName = new InputParameter ("solverName", "#select# glpk ipopt xpress cplex", "The solver name to be used by JOM. GLPK and IPOPT are free, XPRESS and CPLEX commercial. GLPK, XPRESS and CPLEX solve linear problems w/w.o integer contraints. IPOPT is can solve nonlinear problems (if convex, returns global optimum), but cannot handle integer constraints"); 055 private InputParameter solverLibraryName = new InputParameter ("solverLibraryName", "" , "The solver library full or relative path, to be used by JOM. Leave blank to use JOM default."); 056 private InputParameter maxSolverTimeInSeconds = new InputParameter ("maxSolverTimeInSeconds", (double) -1 , "Maximum time granted to the solver to solve the problem. If this time expires, the solver returns the best solution found so far (if a feasible solution is found)"); 057 private InputParameter costPerCapacityModuleType = new InputParameter ("costPerCapacityModuleType", "1 3 6", "The cost of each module of the given type"); 058 private InputParameter capacityOfEachCapacityModuleType = new InputParameter ("capacityOfEachCapacityModuleType", "10 40 100", "The capacity of each module of the given type"); 059 private InputParameter costReductionFactor = new InputParameter ("costReductionFactor", (double) 1 , "The cost of each element at period t is the cost at the previous period multiplied by this. Typically below one since things tend to decrease its price because of improvement in manufacturing" , 0 , true , Double.MAX_VALUE , true); 060 061 @Override 062 public String executeAlgorithm(NetPlan netPlan, Map<String, String> algorithmParameters, Map<String, String> net2planParameters) 063 { 064 /* Initialize all InputParameter objects defined in this object (this uses Java reflection) */ 065 InputParameter.initializeAllInputParameterFieldsOfObject(this, algorithmParameters); 066 if (!shortestPathType.getString().equalsIgnoreCase("km") && !shortestPathType.getString().equalsIgnoreCase("hops")) 067 throw new Net2PlanException("Wrong shortestPathType parameter"); 068 final DoubleMatrix1D u_k = DoubleFactory1D.dense.make (StringUtils.toDoubleArray(StringUtils.split(capacityOfEachCapacityModuleType.getString()))); 069 final DoubleMatrix1D c_k0 = DoubleFactory1D.dense.make (StringUtils.toDoubleArray(StringUtils.split(costPerCapacityModuleType.getString()))); 070 final int K = (int) u_k.size (); // number of types of capacity modules 071 if (K == 0) throw new Net2PlanException ("No capacity modules defined"); 072 if (c_k0.size() != K) throw new Net2PlanException ("The number of costs should be equal to the number of types of capacity modules"); 073 if (u_k.getMinLocation() [0] < 0) throw new Net2PlanException ("Capacities of the modules cannot be negative"); 074 if (c_k0.getMinLocation() [0] < 0) throw new Net2PlanException ("Costs of the modules cannot be negative"); 075 076 /* Initialize variables */ 077 final int N = netPlan.getNumberOfNodes (); 078 final int E = netPlan.getNumberOfLinks (); 079 final double PRECISION_FACTOR = Double.parseDouble(net2planParameters.get("precisionFactor")); 080 if (E == 0) throw new Net2PlanException("This algorithm requires a topology with links"); 081 082 /* Remove all unicast routed traffic. Any multicast routed traffic is kept */ 083 netPlan.removeAllUnicastRoutingInformation(); 084 netPlan.setRoutingTypeAllDemands(RoutingType.SOURCE_ROUTING); 085 netPlan.setTrafficMatrix(DoubleFactory2D.dense.make (N,N,1.0) , RoutingType.SOURCE_ROUTING); // just to create the demands 086 087 /* Add all the k-shortest candidate routes to the netPlan object carrying no traffic */ 088 final DoubleMatrix1D linkCostVectorForCandidatePathList = shortestPathType.getString().equalsIgnoreCase("hops")? DoubleFactory1D.dense.make (E , 1.0) : netPlan.getVectorLinkLengthInKm(); 089 netPlan.addRoutesFromCandidatePathList(netPlan.computeUnicastCandidatePathList(linkCostVectorForCandidatePathList , k.getInt(), maxLengthInKm.getDouble(), -1, -1, -1, -1, -1 , null)); 090 091 final int P = netPlan.getNumberOfRoutes(); 092 093 /* Create the netPlan files, one per interval */ 094 ArrayList<NetPlan> netPlanFiles = new ArrayList<NetPlan> (); 095 while (true) 096 { 097 try 098 { 099 DoubleMatrix2D thisIntervalTrafficMatrix = new NetPlan(new File (rootOfNameOfInputTrafficFiles.getString() + "_tm" + netPlanFiles.size () + ".n2p")).getMatrixNode2NodeOfferedTraffic(); 100 if (thisIntervalTrafficMatrix.rows () != N) throw new Net2PlanException ("The number of nodes in traffic matrix: " + rootOfNameOfInputTrafficFiles.getString() + "_tm" + netPlanFiles.size () + ".n2p (" + thisIntervalTrafficMatrix.rows() + ") is not correct (" + N + ")"); 101 NetPlan netPlanToAdd = netPlan.copy (); 102 for (Demand d : netPlanToAdd.getDemands()) d.setOfferedTraffic(thisIntervalTrafficMatrix.get (d.getIngressNode().getIndex() , d.getEgressNode().getIndex())); 103 netPlanFiles.add (netPlanToAdd); 104 } catch (Exception e) { break; } 105 } 106 final int T = netPlanFiles.size(); 107 108 /* Compute the costs */ 109 final DoubleMatrix2D c_kt = DoubleFactory2D.dense.make (K,T); 110 c_kt.viewColumn(0).assign (c_k0); 111 for (int t = 1 ; t < T ; t ++) 112 c_kt.viewColumn(t).assign (c_kt.viewColumn (t-1).copy ()).assign(DoubleFunctions.mult(costReductionFactor.getDouble())); 113 114 /* Create the optimization problem object (JOM library) */ 115 OptimizationProblem op = new OptimizationProblem(); 116 117 /* Set some input parameters to the problem */ 118 op.setInputParameter("A_dp", netPlan.getMatrixDemand2RouteAssignment()); /* 1 in position (d,p) if demand d is served by path p, 0 otherwise */ 119 op.setInputParameter("A_ep", netPlan.getMatrixLink2RouteAssignment()); /* 1 in position (e,p) if link e is traversed by path p, 0 otherwise */ 120 DoubleMatrix2D h_dt = DoubleFactory2D.dense.make (N*(N-1),T); 121 DoubleMatrix2D h_pt = DoubleFactory2D.dense.make (P,T); 122 for (int t = 0; t < T ; t ++) 123 { 124 h_dt.viewColumn(t).assign (netPlanFiles.get(t).getVectorDemandOfferedTraffic()); 125 h_pt.viewColumn(t).assign (netPlanFiles.get(t).getVectorRouteOfferedTrafficOfAssociatedDemand()); 126 } 127 op.setInputParameter("h_dt", h_dt); /* for each demand and time interval , its offered traffic */ 128 op.setInputParameter("h_pt", h_pt); /* for each path and time interval , the offered traffic of its demand */ 129 op.setInputParameter("u_k", u_k , "row"); /* The capacity of each module of type k */ 130 op.setInputParameter("c_kt", c_kt); /* The cost of a module of type k, acquired to be used starting in interval t */ 131 op.setInputParameter("onesT", DoubleFactory1D.dense.make (T,1.0) , "row"); /* a vector of ones of size T */ 132 DoubleMatrix2D timeAccumulationMatrix = DoubleFactory2D.dense.make (T,T); for (int t1 = 0 ; t1 < T; t1 ++) for (int t2 = t1 ; t2 < T ; t2++) timeAccumulationMatrix.set(t1,t2,1.0); 133 op.setInputParameter("T_tt", timeAccumulationMatrix); /* 1 if column >= row: if the time of acquisition (row) is equal or higher than the time if observation (t2) */ 134 135 op.addDecisionVariable("xx_pt", nonBifurcatedRouting.getBoolean() , new int[] { P , T }, 0, 1); /* the FRACTION of traffic of demand d(p) that is carried by p in each time interval */ 136 op.addDecisionVariable("a_ket", true , new int[] { K , E , T }, 0, 1); /* the number of elements of type k, acquired at time t, and placed at link e (in t and all intervals after t) */ 137 138 op.setObjectiveFunction("minimize", "sum (c_kt .* sum(a_ket,2)) "); /* sum of the cost of all the elements acquired, at the moment of acquisition */ 139 op.addConstraint("A_dp * xx_pt == 1"); /* for each demand, the 100% of the traffic is carried (summing the associated paths) in any time period */ 140 op.addConstraint("A_ep * (xx_pt .* h_pt) <= sum(u_k * a_ket,1) * T_tt"); /* the traffic in each link cannot exceed its capacity in any time period */ 141 142 op.solve(solverName.getString (), "solverLibraryName", solverLibraryName.getString () , "maxSolverTimeInSeconds" , maxSolverTimeInSeconds.getDouble ()); 143 144 /* If no solution is found, quit */ 145 if (op.feasibleSolutionDoesNotExist()) throw new Net2PlanException("The problem has no feasible solution"); 146 if (!op.solutionIsFeasible()) throw new Net2PlanException("A feasible solution was not found"); 147 148 /* Save the solution found in the netPlan object */ 149 final DoubleMatrix2D xx_pt = op.getPrimalSolution("xx_pt").view2D (); 150 final DoubleMatrix3D a_ket = op.getPrimalSolution("a_ket").view3D("sparse"); 151 152 for (int t = 0 ; t < T ; t ++) 153 { 154 NetPlan thisNp = netPlanFiles.get(t); 155 final DoubleMatrix1D h_p = thisNp.getVectorRouteOfferedTrafficOfAssociatedDemand(); 156 final DoubleMatrix1D x_p = xx_pt.viewColumn(t).copy().assign (h_p , DoubleFunctions.mult); 157 //System.out.println ("h_p: " + h_p); 158 thisNp.setVectorRouteCarriedTrafficAndOccupiedLinkCapacities(x_p , x_p); 159 for (Link link : thisNp.getLinks ()) 160 { 161 final int e = link.getIndex (); 162 double linkCapacityAccumulatingPreviosModules = 0; for (int t1 = 0; t1 <= t ; t1 ++) for (int k = 0 ; k < K ; k ++) linkCapacityAccumulatingPreviosModules += u_k.get(k) * a_ket.get(k,e,t1); 163 link.setCapacity(linkCapacityAccumulatingPreviosModules); 164 for (int k = 0 ; k < K ; k ++) link.setAttribute ("numNewModulesType_" + k , "" + a_ket.get (k,e,t)); 165 } 166 thisNp.removeAllRoutesUnused(PRECISION_FACTOR); // routes with zero traffic (or close to zero, with PRECISION_FACTOR tolerance) 167 thisNp.saveToFile(new File (rootOfNameOfOutputFiles.getString() + "_res_tm" + netPlanFiles.size () + ".n2p")); 168 if (t == 0) netPlan.assignFrom (thisNp); 169 if (thisNp.getVectorLinkOversubscribedTraffic().zSum () > PRECISION_FACTOR) throw new RuntimeException ("Bad: " + thisNp.getVectorLinkOversubscribedTraffic().zSum ()); 170 if (thisNp.getVectorDemandBlockedTraffic().zSum() > PRECISION_FACTOR) throw new RuntimeException ("Bad: " + thisNp.getVectorDemandBlockedTraffic().zSum()); 171 } 172 173 return "Ok!: The solution found is guaranteed to be optimal: " + op.solutionIsOptimal() + ". Total cost = " + op.parseExpression("sum (c_kt .* sum(a_ket,2))").evaluate("a_ket" , new DoubleMatrixND (a_ket)); 174 } 175 176 @Override 177 public String getDescription() 178 { 179 return "Given a network with a set of given nodes, and links, and a given a sequence of offered traffic matrices in the network, corresponding to the (typically increasing) traffic of successive periods (e.g. each for one year). The link capacities are constrained to be modular: selectable among a set of user-defined capacity modules. Each capacity module type is characterized by its capacity and its cost. We assume that the costs of the capacity modules decrease along time, according to a cost reduction factor. Then, the algorithm should find for each of the successive periods: (i) the routing of the traffic in each period, (ii) how many NEW modules of capacity are installed in each link. Once a capacity module is installed in a link, we assume that it is never moved. The optimization target is minimizing the total cost along all the periods. This algorithm optimizes the problem solving a flow-path formulation using JOM."; 180 } 181 182 183 @Override 184 public List<Triple<String, String, String>> getParameters() 185 { 186 /* Returns the parameter information for all the InputParameter objects defined in this object (uses Java reflection) */ 187 return InputParameter.getInformationAllInputParameterFieldsOfObject(this); 188 } 189}