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.DoubleFactory2D;
024import cern.colt.matrix.tdouble.DoubleMatrix1D;
025import cern.colt.matrix.tdouble.DoubleMatrix2D;
026import cern.jet.math.tdouble.DoubleFunctions;
027import com.jom.OptimizationProblem;
028import com.net2plan.interfaces.networkDesign.*;
029import com.net2plan.utils.DoubleUtils;
030import com.net2plan.utils.InputParameter;
031import com.net2plan.utils.Triple;
032
033import java.util.List;
034import java.util.Map;
035
036/**
037 * Solves severals variants of routing problems in the form of destination-link formulations.
038 * @net2plan.description
039 * @net2plan.keywords JOM, Destination-link formulation, Flow assignment (FA)
040 * @net2plan.ocnbooksections Section 4.4, Section 4.6.3
041 * @net2plan.inputParameters 
042 * @author Pablo Pavon-Marino
043 */
044public class Offline_fa_xteFormulations implements IAlgorithm
045{
046        private InputParameter optimizationTarget = new InputParameter ("optimizationTarget", "#select# min-av-num-hops minimax-link-utilization maximin-link-idle-capacity min-av-network-delay min-av-network-blocking" , "Type of optimization target. Choose among minimize the average number of hops, minimize the highest link utilization, maximize the lowest link idle capacity, minimize the average end-to-end network delay including queueing (M/M/1 estimation) and propagation delays, and minimize the average network blocking assuming independent Erlang-B blocking in each link, load sharing model");
047        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");
048        private InputParameter solverLibraryName = new InputParameter ("solverLibraryName", "", "The solver library full or relative path, to be used by JOM. Leave blank to use JOM default.");
049        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)");
050        private InputParameter binaryRatePerTrafficUnit_bps = new InputParameter ("binaryRatePerTrafficUnit_bps", (double) 1E6 , "Binary rate equivalent to one traffic unit (used only in average network delay minimization formulation)." , 0 , false , Double.MAX_VALUE , true);
051        private InputParameter averagePacketLengthInBytes = new InputParameter ("averagePacketLengthInBytes", (double) 500 , "Average packet length in bytes (used only in average network delay minimization formulation)." , 0 , false , Double.MAX_VALUE , true);
052        private InputParameter nonBifurcatedRouting = new InputParameter ("nonBifurcatedRouting", false , "True if the routing is constrained to be non-bifurcated");
053
054        @Override
055        public String executeAlgorithm(NetPlan netPlan, Map<String, String> algorithmParameters, Map<String, String> net2planParameters)
056        {
057                /* Initialize all InputParameter objects defined in this object (this uses Java reflection) */
058                InputParameter.initializeAllInputParameterFieldsOfObject(this, algorithmParameters);
059                
060                /* Initialize variables */
061                final int N = netPlan.getNumberOfNodes ();
062                final int E = netPlan.getNumberOfLinks();
063                final int D = netPlan.getNumberOfDemands();
064                if (E == 0 || D == 0) throw new Net2PlanException("This algorithm requires a topology with links and a demand set");
065
066                /* Remove all routes in current netPlan object, and set routing type to SOURCE ROUTING */
067                netPlan.removeAllUnicastRoutingInformation ();
068
069                /* Create the optimization problem object (JOM library) */
070                OptimizationProblem op = new OptimizationProblem();
071
072                /* Set some input parameters to the problem */
073                op.setInputParameter("u_e", netPlan.getVectorLinkSpareCapacity(), "row"); /* for each link, its unused capacity (the one not used by any mulitcast trees) */
074                op.setInputParameter("A_ne", netPlan.getMatrixNodeLinkIncidence()); /* 1 in position (n,e) if link e starts in n, -1 if it ends in n, 0 otherwise */
075                final DoubleMatrix1D egressTraffic_t = netPlan.getVectorNodeEgressUnicastTraffic();
076                final DoubleMatrix2D trafficMatrixDiagonalNegative = netPlan.getMatrixNode2NodeOfferedTraffic();
077                trafficMatrixDiagonalNegative.assign (DoubleFactory2D.sparse.diagonal(egressTraffic_t) , DoubleFunctions.minus);
078                op.setInputParameter("TM", trafficMatrixDiagonalNegative);
079                
080                /* Write the problem formulations */
081                if (optimizationTarget.getString ().equals ("min-av-num-hops")) 
082                {
083                        op.addDecisionVariable("x_te", false , new int[] { N, E }, 0, Double.MAX_VALUE); /* the amount of traffic targeted to node t, that is carried by link e */
084                        if (nonBifurcatedRouting.getBoolean()) op.addDecisionVariable("f_te", true, new int [] {N,E} , 0 , 1);
085                        op.setObjectiveFunction("minimize", "sum (x_te)"); /* sum of the traffic in the links, proportional to the average number of hops  */
086                        op.addConstraint("A_ne * (x_te') == TM"); /* the flow-conservation constraints (NxD constraints) */
087                        op.addConstraint("sum(x_te,1) <= u_e"); /* the capacity constraints (E constraints) */
088                }
089                else if (optimizationTarget.getString ().equals ("minimax-link-utilization")) 
090                {
091                        op.setInputParameter ("EPSILON" , getMinimumNonZeroTrafficOrCapacityValue (netPlan) / 1000);
092                        op.addDecisionVariable("x_te", false , new int[] { N, E }, 0, Double.MAX_VALUE); /* the amount of traffic targeted to node t, that is carried by link e */
093                        op.addDecisionVariable("rho", false, new int[] { 1, 1 }, 0, 1); /* worse case link utilization */
094                        if (nonBifurcatedRouting.getBoolean()) op.addDecisionVariable("f_te", true, new int [] {N,E} , 0 , 1);
095                        op.setObjectiveFunction("minimize", "rho + EPSILON * sum(x_te)"); // to avoid loops, we sum EPSILON by the traffic carried (EPSILON very small number)
096                        op.addConstraint("A_ne * (x_te') == TM"); /* the flow-conservation constraints (NxD constraints) */
097                        op.addConstraint("sum(x_te,1) <= rho * u_e"); /* the traffic in each link cannot exceed its capacity. sets rho as the worse case utilization */
098                }
099                else if (optimizationTarget.getString ().equals ("maximin-link-idle-capacity"))
100                {
101                        op.setInputParameter ("EPSILON" , getMinimumNonZeroTrafficOrCapacityValue (netPlan) / 1000);
102                        op.addDecisionVariable("x_te", false , new int[] { N, E }, 0, Double.MAX_VALUE); /* the amount of traffic targeted to node t, that is carried by link e */
103                        op.addDecisionVariable("u", false, new int[] { 1, 1 }, 0, Double.MAX_VALUE); /* worse case link idle capacity */
104                        if (nonBifurcatedRouting.getBoolean()) op.addDecisionVariable("f_te", true, new int [] {N,E} , 0 , 1);
105                        op.setObjectiveFunction("maximize", "u - EPSILON * sum(x_te)"); // to avoid loops, we sum EPSILON by the traffic carried (EPSILON very small number)
106                        op.addConstraint("A_ne * (x_te') == TM"); /* the flow-conservation constraints (NxD constraints) */
107                        op.addConstraint("sum(x_te,1) <= -u + u_e"); /* the traffic in each link cannot exceed its capacity. sets u as the worse case idle capacity */
108                }
109                else if (optimizationTarget.getString ().equals ("min-av-network-delay"))
110                {
111                        op.setInputParameter("d_e_secs", netPlan.getVectorLinkPropagationDelayInMiliseconds().assign (DoubleFunctions.mult (0.001)) , "row");
112                        op.setInputParameter("L", averagePacketLengthInBytes.getDouble() * 8); /* average packet length in bits */
113                        op.setInputParameter("R", binaryRatePerTrafficUnit_bps.getDouble()); /* binary rate per traffic unit */
114                        op.addDecisionVariable("x_te", false , new int[] { N, E }, 0, Double.MAX_VALUE); /* the amount of traffic targeted to node t, that is carried by link e */
115                        op.addDecisionVariable("y_e", false, new int[] { 1, E }, DoubleUtils.zeros(E), netPlan.getVectorLinkCapacity().toArray()); /* traffic in the links (already limited to the link capacity) */
116                        if (nonBifurcatedRouting.getBoolean()) op.addDecisionVariable("f_te", true, new int [] {N,E} , 0 , 1);
117                        op.setObjectiveFunction("minimize", "sum( y_e .* (d_e_secs + (L./R) * (1 ./ (u_e - y_e)))  )");
118                        op.addConstraint("A_ne * (x_te') == TM"); /* the flow-conservation constraints (NxD constraints) */
119                        op.addConstraint("sum(x_te,1) == y_e"); /* sets y_e as the total traffic in each link */
120                }
121                else if (optimizationTarget.getString ().equals ("min-av-network-blocking"))
122                {
123                        op.addDecisionVariable("x_te", false , new int[] { N, E }, 0, Double.MAX_VALUE); /* the amount of traffic targeted to node t, that is carried by link e */
124                        op.addDecisionVariable("y_e", false, new int[] { 1, E }, DoubleUtils.zeros(E), netPlan.getVectorLinkCapacity().toArray()); /* traffic in the links (already limited to the link capacity) */
125                        if (nonBifurcatedRouting.getBoolean()) op.addDecisionVariable("f_te", true, new int [] {N,E} , 0 , 1);
126                        op.setObjectiveFunction("minimize", "sum(y_e .* erlangB(y_e, u_e))");
127                        op.addConstraint("A_ne * (x_te') == TM"); /* the flow-conservation constraints (NxD constraints) */
128                        op.addConstraint("sum(x_te,1) == y_e"); /* sets y_e as the total traffic in each link */
129                }
130                else throw new Net2PlanException ("Unknown optimization target " + optimizationTarget.getString());
131
132                /* Constraints for non-bifurcated traffic */
133                if (nonBifurcatedRouting.getBoolean())
134                {
135                        DoubleMatrix2D maxNumOutLinksCarryingTraffic_nt = DoubleFactory2D.dense.make(N,N,1.0);
136                        for (int n = 0 ; n < N ; n ++) maxNumOutLinksCarryingTraffic_nt.set(n, n, 0);
137                        op.setInputParameter("U", netPlan.getVectorLinkCapacity().getMaxLocation() [0]);
138                        op.setInputParameter("Aout_ne", netPlan.getMatrixNodeLinkOutgoingIncidence());
139                        op.setInputParameter("outMax_nt", maxNumOutLinksCarryingTraffic_nt);
140                        op.addConstraint("x_te <= U * f_te"); /* f_te takes value 1 for non zero x_te */
141                        op.addConstraint ("Aout_ne * f_te' <= outMax_nt"); /* number of out links of node n carrying traffic to t is always below 1, and if n=t, it is zero */
142                }
143
144                op.solve(solverName.getString (), "solverLibraryName", solverLibraryName.getString () , "maxSolverTimeInSeconds" , maxSolverTimeInSeconds.getDouble ());
145
146                /* If no solution is found, quit */
147                if (op.feasibleSolutionDoesNotExist()) throw new Net2PlanException("The problem has no feasible solution");
148                if (!op.solutionIsFeasible()) throw new Net2PlanException("A feasible solution was not found");
149                
150                /* Save the solution found in the netPlan object */
151                final DoubleMatrix2D x_te = op.getPrimalSolution("x_te").view2D();
152                netPlan.setRoutingFromDestinationLinkCarriedTraffic(x_te , true); // remove the cycles if any
153
154                return "Ok!: The solution found is guaranteed to be optimal: " + op.solutionIsOptimal();
155        }
156
157        @Override
158        public String getDescription()
159        {
160                return "Given a network topology, the capacities in the links, and a set unicast traffic demands, this algorithm permits computing the optimum destination-based routing of the traffic solving destination-link formulations (x_{te} variables). Recall that in destination-based routing, the nodes can only forward the traffic depending on its destination node, whatever its demand is (e.g. a node routes all the demands with the same egress node in the same form, whatever its ingress node is). Through a set of input parameters, the user can choose among different optimization targets and constraints.";
161        }
162
163        
164        @Override
165        public List<Triple<String, String, String>> getParameters()
166        {
167                /* Returns the parameter information for all the InputParameter objects defined in this object (uses Java reflection) */
168                return InputParameter.getInformationAllInputParameterFieldsOfObject(this);
169        }
170
171        private double getMinimumNonZeroTrafficOrCapacityValue (NetPlan netPlan)
172        {
173                double res = Double.MAX_VALUE;
174                for (Demand d : netPlan.getDemands ()) if (d.getOfferedTraffic() > 0) res = Math.min (res , d.getOfferedTraffic());
175                for (Link e : netPlan.getLinks ()) if (e.getCapacity() > 0) res = Math.min (res , e.getCapacity());
176                if (res == Double.MAX_VALUE) throw new Net2PlanException ("Too large offered traffics and link capacities");
177                return res;
178        }
179}