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 *******************************************************************************/
011package com.net2plan.examples.ocnbook.onlineSim;
012
013
014import cern.colt.matrix.tdouble.DoubleFactory1D;
015import cern.colt.matrix.tdouble.DoubleFactory2D;
016import cern.colt.matrix.tdouble.DoubleMatrix1D;
017import cern.colt.matrix.tdouble.DoubleMatrix2D;
018import com.jom.OptimizationProblem;
019import com.net2plan.interfaces.networkDesign.*;
020import com.net2plan.interfaces.simulation.IEventProcessor;
021import com.net2plan.interfaces.simulation.SimEvent;
022import com.net2plan.libraries.NetworkPerformanceMetrics;
023import com.net2plan.utils.Constants.RoutingType;
024import com.net2plan.utils.*;
025
026import java.io.File;
027import java.util.List;
028import java.util.Map;
029import java.util.Random;
030import java.util.Set;
031
032/** 
033 * This module implements a distributed primal-gradient based algorithm using a barrier function, for adapting the demand injected traffic (congestion control) in the network, to maximize the network utility enforcing a fair allocation of the resources.
034 *
035 * Ths event processor is adapted to permit observing the algorithm performances under user-defined conditions, 
036 * including asynchronous distributed executions, where signaling can be affected by losses and/or delays, and/or measurement errors. 
037 * The time evolution of different metrics can be stored in output files, for later processing. 
038 * As an example, see the <a href="../../../../../../graphGeneratorFiles/fig_sec9_4_congestionControlPrimal.m">{@code fig_sec9_4_congestionControlPrimal.m}</a> MATLAB file used for generating the graph/s of the case study in the 
039 * <a href="http://eu.wiley.com/WileyCDA/WileyTitle/productCd-1119013356.html">book</a> using this algorithm.
040 * 
041 * To simulate a network with this module, use the {@code Online_evGen_doNothing} generator.
042 * 
043 * @net2plan.keywords Bandwidth assignment (BA), Distributed algorithm, Primal gradient algorithm
044 * @net2plan.ocnbooksections Section 9.4
045 * @net2plan.inputParameters 
046 * @author Pablo Pavon-Marino
047 */
048@SuppressWarnings("unchecked")
049public class Online_evProc_congestionControlPrimal extends IEventProcessor
050{
051        private InputParameter signaling_isSynchronous = new InputParameter ("signaling_isSynchronous", false , "true if all the distributed agents involved wake up synchronously to send the signaling messages");
052        private InputParameter signaling_averageInterMessageTime = new InputParameter ("signaling_averageInterMessageTime", 1.0 , "Average time between two signaling messages sent by an agent" , 0 , false , Double.MAX_VALUE , true);
053        private InputParameter signaling_maxFluctuationInterMessageTime = new InputParameter ("signaling_maxFluctuationInterMessageTime", 0.5 , "Max fluctuation in time between two signaling messages sent by an agent" , 0 , true , Double.MAX_VALUE , true);
054        private InputParameter signaling_averageDelay = new InputParameter ("signaling_averageDelay", 0.0 , "Average time between signaling message transmission by an agent and its reception by other or others" , 0 , true , Double.MAX_VALUE , true);
055        private InputParameter signaling_maxFluctuationInDelay = new InputParameter ("signaling_maxFluctuationInDelay", 0.0 , "Max fluctuation in time in the signaling delay, in absolute time values. The signaling delays are sampled from a uniform distribution within the given interval" , 0 , true , Double.MAX_VALUE , true);
056        private InputParameter signaling_signalingLossProbability = new InputParameter ("signaling_signalingLossProbability", 0.05 , "Probability that a signaling message transmitted is lost (not received by other or others involved agents)" , 0 , true , Double.MAX_VALUE , true);
057        private InputParameter update_isSynchronous = new InputParameter ("update_isSynchronous", false , "true if all the distributed agents involved wake up synchronousely to update its state");
058        private InputParameter update_averageInterUpdateTime = new InputParameter ("update_averageInterUpdateTime", 1.0 , "Average time between two updates of an agent" , 0 , false , Double.MAX_VALUE , true);
059        private InputParameter update_maxFluctuationInterUpdateTime = new InputParameter ("update_maxFluctuationInterUpdateTime", 0.5 , "Max fluctuation in time in the update interval of an agent, in absolute time values. The update intervals are sampled from a uniform distribution within the given interval" , 0 , true , Double.MAX_VALUE , true);
060        private InputParameter gradient_diagonalScaling = new InputParameter ("gradient_diagonalScaling", false , "Whether diagonal scaling is applied or not");
061        private InputParameter gradient_maxGradientAbsoluteNoise = new InputParameter ("gradient_maxGradientAbsoluteNoise", 0.0 , "Max value of the added noise to the gradient coordinate in absolute values" , 0 , true , Double.MAX_VALUE , true);
062        private InputParameter gradient_gammaStep = new InputParameter ("gradient_gammaStep", 20.0 , "Gamma step in the gradient algorithm" , 0 , false , Double.MAX_VALUE , true);
063        private InputParameter gradient_heavyBallBetaParameter = new InputParameter ("gradient_heavyBallBetaParameter", 0.0 , "Beta parameter of heavy ball, between 0 and 1. Value 0 means no heavy ball" , 0 , true , 1.0 , true);
064        private InputParameter gradient_maxGradientCoordinateChange = new InputParameter ("gradient_maxGradientCoordinateChange", 1.0 , "Maximum change in an iteration of a gradient coordinate" , 0 , false , Double.MAX_VALUE , true);
065        private InputParameter gradient_penaltyMethod = new InputParameter ("gradient_penaltyMethod", "#select# barrier exterior-penalty" , "Use a barrier (interior penalty) or an exterior penalty for enforcing link capacity constraints");
066        private InputParameter gradient_exteriorPenaltyMuFactor = new InputParameter ("gradient_exteriorPenaltyMuFactor", 1000 , "Mu factor to apply in the exterior penalty method" , 0 , true , Double.MAX_VALUE , true);
067        private InputParameter gradient_interiorPenaltyEpsilonFactor = new InputParameter ("gradient_interiorPenaltyEpsilonFactor", 0.00001 , "Factor to multiply the delay penalization function" , 0 , true , Double.MAX_VALUE , true);
068        private InputParameter simulation_maxNumberOfUpdateIntervals = new InputParameter ("simulation_maxNumberOfUpdateIntervals", 800.0 , "Maximum number of update intervals in average per agent" , 0 , false , Double.MAX_VALUE , true);
069        private InputParameter simulation_randomSeed = new InputParameter ("simulation_randomSeed", (long) 1 , "Seed of the random number generator");
070        private InputParameter simulation_outFileNameRoot = new InputParameter ("simulation_outFileNameRoot", "congestionControlPrimal" , "Root of the file name to be used in the output files. If blank, no output");
071
072        private InputParameter control_minHd = new InputParameter ("control_minHd", 0.1 , "Minimum traffic assigned to each demand" , 0 , true , Double.MAX_VALUE , true);
073        private InputParameter control_maxHd = new InputParameter ("control_maxHd", 1.0E6 , "Maximum traffic assigned to each demand" , 0 , true , Double.MAX_VALUE , true);
074        private InputParameter control_fairnessFactor = new InputParameter ("control_fairnessFactor", 2.0 , "Fairness factor in utility function of congestion control" , 0 , true , Double.MAX_VALUE , true);
075        
076        private Random rng;
077        
078        private static final int SIGNALING_WAKEUPTOSENDMESSAGE = 300;
079        private static final int SIGNALING_RECEIVEDMESSAGE = 301;
080        private static final int UPDATE_WAKEUPTOUPDATE = 302;
081
082        private NetPlan currentNetPlan;
083        
084        private double control_epsilonOrMuFactor;
085        private DoubleMatrix1D control_priceFirstOrder_e;
086        private DoubleMatrix1D control_priceSecondOrder_e;
087        private DoubleMatrix1D control_previous_h_d;
088        private DoubleMatrix2D control_mostUpdatedLinkFirstOrderPriceKnownDemand_de; 
089        private DoubleMatrix2D control_mostUpdatedLinkSecondOrderPriceKnownDemand_de; 
090        private boolean control_isBarrierMethod;
091        private int D , E;
092        
093        private TimeTrace stat_traceOf_objFunction;
094        private TimeTrace stat_traceOf_hd;
095        private TimeTrace stat_traceOf_maxLinkTraffic;
096
097        @Override
098        public String getDescription()
099        {
100                return "This module implements a distributed primal-gradient based algorithm using a barrier function, for adapting the demand injected traffic (congestion control) in the network, to maximize the network utility enforcing a fair allocation of the resources.";
101        }
102
103        @Override
104        public List<Triple<String, String, String>> getParameters()
105        {
106                /* Returns the parameter information for all the InputParameter objects defined in this object (uses Java reflection) */
107                return InputParameter.getInformationAllInputParameterFieldsOfObject(this);
108        }
109
110        @Override
111        public void initialize(NetPlan currentNetPlan, Map<String, String> algorithmParameters, Map<String, String> simulationParameters, Map<String, String> net2planParameters)
112        {
113                /* Initialize all InputParameter objects defined in this object (this uses Java reflection) */
114                InputParameter.initializeAllInputParameterFieldsOfObject(this, algorithmParameters);
115
116                this.currentNetPlan = currentNetPlan;
117                if (currentNetPlan.getNumberOfLayers() != 1) throw new Net2PlanException ("This algorithm works in single layer networks");
118
119                /* Remove all routes, and create one with the shortest path in km for each demand */
120                currentNetPlan.removeAllUnicastRoutingInformation();
121                currentNetPlan.setRoutingTypeAllDemands(RoutingType.SOURCE_ROUTING);
122                this.currentNetPlan.addRoutesFromCandidatePathList(currentNetPlan.computeUnicastCandidatePathList(currentNetPlan.getVectorLinkLengthInKm() , 1, -1, -1, -1, -1, -1, -1 , null));
123
124
125                this.control_isBarrierMethod = gradient_penaltyMethod.getString ().equals ("barrier");
126                this.control_epsilonOrMuFactor = control_isBarrierMethod? gradient_interiorPenaltyEpsilonFactor.getDouble() : gradient_exteriorPenaltyMuFactor.getDouble();
127                this.rng = new Random (simulation_randomSeed.getLong());
128                this.D = currentNetPlan.getNumberOfDemands ();
129                this.E = currentNetPlan.getNumberOfLinks ();
130                if ((E == 0) || (D == 0)) throw new Net2PlanException ("The input design should have links and demands");
131                
132                /* Initially all demands offer exactly hdMin */
133                control_previous_h_d = DoubleFactory1D.dense.make (D , control_minHd.getDouble());
134                currentNetPlan.setVectorDemandOfferedTraffic(control_previous_h_d);
135                for (Demand d : currentNetPlan.getDemands()) // carry the demand traffic
136                { 
137                        final Set<Route> routes = d.getRoutes(); 
138                        for (Route r : routes) r.setCarriedTraffic(d.getOfferedTraffic() / routes.size () , d.getOfferedTraffic() / routes.size ()); 
139                }
140                
141                /* Set the initial prices in the links */
142                this.control_priceFirstOrder_e = DoubleFactory1D.dense.make (E); for (Link e : this.currentNetPlan.getLinks ()) control_priceFirstOrder_e.set (e.getIndex () , computeFirstOrderPriceFromNetPlan(e));
143                this.control_priceSecondOrder_e = DoubleFactory1D.dense.make (E); for (Link e : this.currentNetPlan.getLinks ()) control_priceSecondOrder_e.set (e.getIndex () , computeSecondOrderPriceFromNetPlan(e));
144                
145                /* Initialize the information each demand knows of the prices of all the links */
146                this.control_mostUpdatedLinkFirstOrderPriceKnownDemand_de = DoubleFactory2D.dense.make (D,E);
147                this.control_mostUpdatedLinkSecondOrderPriceKnownDemand_de = DoubleFactory2D.dense.make (D,E);
148                for (Demand d : currentNetPlan.getDemands ())
149                {
150                        control_mostUpdatedLinkFirstOrderPriceKnownDemand_de.viewRow (d.getIndex ()).assign (control_priceFirstOrder_e);
151                        control_mostUpdatedLinkSecondOrderPriceKnownDemand_de.viewRow (d.getIndex ()).assign (control_priceSecondOrder_e);
152                }
153                
154                /* Initially all nodes receive a "wake up to transmit" event, aligned at time zero or y asynchr => randomly chosen */
155                for (Link e : currentNetPlan.getLinks())
156                {
157                        final double signalingTime = (signaling_isSynchronous.getBoolean())? signaling_averageInterMessageTime.getDouble() : Math.max(0 , signaling_averageInterMessageTime.getDouble() + signaling_maxFluctuationInterMessageTime.getDouble() * (rng.nextDouble() - 0.5));
158                        this.scheduleEvent(new SimEvent (signalingTime , SimEvent.DestinationModule.EVENT_PROCESSOR , SIGNALING_WAKEUPTOSENDMESSAGE , e));
159                }
160                for (Demand d : currentNetPlan.getDemands())
161                {
162                        final double updateTime = (update_isSynchronous.getBoolean())? update_averageInterUpdateTime.getDouble() : Math.max(0 , update_averageInterUpdateTime.getDouble() + update_maxFluctuationInterUpdateTime.getDouble() * (rng.nextDouble() - 0.5));
163                        this.scheduleEvent(new SimEvent (updateTime , SimEvent.DestinationModule.EVENT_PROCESSOR , UPDATE_WAKEUPTOUPDATE , d));
164                }
165
166                /* Intialize the traces */
167                this.stat_traceOf_hd = new TimeTrace ();
168                this.stat_traceOf_objFunction = new TimeTrace (); 
169                this.stat_traceOf_maxLinkTraffic = new TimeTrace ();
170                this.stat_traceOf_hd.add(0 , this.currentNetPlan.getVectorDemandOfferedTraffic());
171                this.stat_traceOf_objFunction.add(0 , NetworkPerformanceMetrics.alphaUtility(currentNetPlan.getVectorDemandOfferedTraffic() , control_fairnessFactor.getDouble()));
172                this.stat_traceOf_maxLinkTraffic.add(0.0, this.currentNetPlan.getVectorLinkCarriedTraffic().getMaxLocation() [0]);
173        }
174
175        @Override
176        public void processEvent(NetPlan currentNetPlan, SimEvent event)
177        {
178                final double t = event.getEventTime();
179                switch (event.getEventType())
180                {
181                case SIGNALING_RECEIVEDMESSAGE: // A node receives from an out neighbor the q_nt for any destination
182                {
183                        final Quadruple<Demand,Link,Double,Double> signalInfo = (Quadruple<Demand,Link,Double,Double>) event.getEventObject();
184                        final Demand dMe = signalInfo.getFirst();
185                        final Link e = signalInfo.getSecond ();
186                        control_mostUpdatedLinkFirstOrderPriceKnownDemand_de.set (dMe.getIndex () , e.getIndex () , signalInfo.getThird ());
187                        control_mostUpdatedLinkSecondOrderPriceKnownDemand_de.set (dMe.getIndex () , e.getIndex () , signalInfo.getFourth ());
188                        break;
189                }
190                
191                case SIGNALING_WAKEUPTOSENDMESSAGE: // A node broadcasts signaling info to its 1 hop neighbors
192                {
193                        final Link eMe = (Link) event.getEventObject();
194
195                        /* Send the events of the signaling information messages to all the nodes */
196                        if (rng.nextDouble() >= this.signaling_signalingLossProbability.getDouble()) // the signaling may be lost => lost to all demands
197                                for (Route route : eMe.getTraversingRoutes())
198                                {
199                                        final Demand d = route.getDemand();
200                                        Quadruple<Demand,Link,Double,Double> infoToSignal = Quadruple.of(d , eMe ,  this.computeFirstOrderPriceFromNetPlan(eMe) , computeSecondOrderPriceFromNetPlan(eMe));
201                                        final double signalingReceptionTime = t + Math.max(0 , signaling_averageDelay.getDouble() + signaling_maxFluctuationInDelay.getDouble() * (rng.nextDouble() - 0.5));
202                                        this.scheduleEvent(new SimEvent (signalingReceptionTime , SimEvent.DestinationModule.EVENT_PROCESSOR , SIGNALING_RECEIVEDMESSAGE , infoToSignal));
203                                }
204                        
205                        /* Re-schedule when to wake up again */
206                        final double signalingTime = signaling_isSynchronous.getBoolean()? t + signaling_averageInterMessageTime.getDouble() : Math.max(t , t + signaling_averageInterMessageTime.getDouble() + signaling_maxFluctuationInterMessageTime.getDouble() * (rng.nextDouble() - 0.5));
207                        this.scheduleEvent(new SimEvent (signalingTime , SimEvent.DestinationModule.EVENT_PROCESSOR , SIGNALING_WAKEUPTOSENDMESSAGE , eMe));
208                        break;
209                }
210
211                case UPDATE_WAKEUPTOUPDATE: 
212                {
213                        final Demand dMe = (Demand) event.getEventObject();
214                        
215                        DoubleMatrix1D infoIKnow_priceFirstOrder_e = this.control_mostUpdatedLinkFirstOrderPriceKnownDemand_de.viewRow (dMe.getIndex ());
216                        DoubleMatrix1D infoIKnow_priceSecondOrder_e = this.control_mostUpdatedLinkSecondOrderPriceKnownDemand_de.viewRow (dMe.getIndex ());
217
218                        /* compute the demand price as weighted sum in the routes of route prices  */
219                        double demandWeightedSumLinkPrices = 0;
220                        double demandWeightedSumSecondDerivativeLinkPrices = 0;
221                        double demandCarriedTraffic = 0; 
222                        for (Route r : dMe.getRoutes ())
223                        {
224                                final double h_r = r.getCarriedTraffic();
225                                demandCarriedTraffic += h_r;
226                                for (Link e : r.getSeqLinks())
227                                {
228                                        demandWeightedSumLinkPrices += h_r * infoIKnow_priceFirstOrder_e.get(e.getIndex ());
229                                        demandWeightedSumSecondDerivativeLinkPrices += h_r * infoIKnow_priceSecondOrder_e.get(e.getIndex ());
230                                }
231                        }
232                        if (Math.abs(demandCarriedTraffic - dMe.getOfferedTraffic()) > 1E-3) throw new RuntimeException ("Not all the traffic is carried. demandCarriedTraffic: " + demandCarriedTraffic);
233                        demandWeightedSumLinkPrices /= demandCarriedTraffic;
234                        demandWeightedSumSecondDerivativeLinkPrices /= demandCarriedTraffic;
235                        
236                        /* compute the new h_d */
237                        final double old_hd = dMe.getOfferedTraffic();
238                        final double gradient_d = Math.pow(old_hd, -this.control_fairnessFactor.getDouble()) - this.control_epsilonOrMuFactor * demandWeightedSumLinkPrices +  2*gradient_maxGradientAbsoluteNoise.getDouble()*(rng.nextDouble()-0.5);
239                        double seconDerivativehd2ForDiagonalScaling = (gradient_diagonalScaling.getBoolean())? Math.abs(-this.control_fairnessFactor.getDouble() * Math.pow(old_hd, -this.control_fairnessFactor.getDouble()-1)- this.control_epsilonOrMuFactor * demandWeightedSumSecondDerivativeLinkPrices) : 1;
240                        if (!Double.isFinite(seconDerivativehd2ForDiagonalScaling)) seconDerivativehd2ForDiagonalScaling = 1; 
241                        
242                        double coordinateChange =  this.gradient_gammaStep.getDouble() / seconDerivativehd2ForDiagonalScaling * gradient_d + this.gradient_heavyBallBetaParameter.getDouble() * (old_hd - this.control_previous_h_d.get(dMe.getIndex ())  );
243                        
244                        if (gradient_maxGradientCoordinateChange.getDouble() > 0) 
245                                coordinateChange = Math.signum(coordinateChange) * Math.min(gradient_maxGradientCoordinateChange.getDouble() , Math.abs(coordinateChange));  
246
247                        final double new_hd = GradientProjectionUtils.euclideanProjection_boxLike (old_hd + coordinateChange , control_minHd.getDouble() , control_maxHd.getDouble ());
248
249                        control_previous_h_d.set (dMe.getIndex (), dMe.getOfferedTraffic());
250                        dMe.setOfferedTraffic(new_hd); 
251                        final Set<Route> routes = dMe.getRoutes(); // carry the demand traffic
252                        for (Route r : routes) r.setCarriedTraffic(dMe.getOfferedTraffic() / routes.size () , dMe.getOfferedTraffic() / routes.size ());
253
254                        final double updateTime = update_isSynchronous.getBoolean()? t + update_averageInterUpdateTime.getDouble() : Math.max(t , t + update_averageInterUpdateTime.getDouble() + update_maxFluctuationInterUpdateTime.getDouble() * (rng.nextDouble() - 0.5));
255                        this.scheduleEvent(new SimEvent (updateTime , SimEvent.DestinationModule.EVENT_PROCESSOR , UPDATE_WAKEUPTOUPDATE,  dMe));
256
257                        this.stat_traceOf_hd.add(t, this.currentNetPlan.getVectorDemandOfferedTraffic());
258                        this.stat_traceOf_objFunction.add(t, NetworkPerformanceMetrics.alphaUtility(currentNetPlan.getVectorDemandOfferedTraffic() , control_fairnessFactor.getDouble()));
259                        this.stat_traceOf_maxLinkTraffic.add(t, this.currentNetPlan.getVectorLinkCarriedTraffic().getMaxLocation() [0]);
260
261                        if (t > this.simulation_maxNumberOfUpdateIntervals.getDouble() * this.update_averageInterUpdateTime.getDouble()) { this.endSimulation (); }
262                        
263                        break;
264                }
265                        
266
267                default: throw new RuntimeException ("Unexpected received event");
268                }
269                
270                
271        }
272
273        public String finish (StringBuilder st , double simTime)
274        {
275                if (simulation_outFileNameRoot.getString().equals("")) return null;
276                stat_traceOf_hd.printToFile(new File (simulation_outFileNameRoot.getString() + "_hd.txt"));
277                stat_traceOf_objFunction.printToFile(new File (simulation_outFileNameRoot.getString() + "_objFunc.txt"));
278                stat_traceOf_maxLinkTraffic.printToFile(new File (simulation_outFileNameRoot.getString() + "_maxYe.txt"));
279                Pair<DoubleMatrix1D,Double> optPair = computeOptimumSolution ();
280                TimeTrace.printToFile(new File (simulation_outFileNameRoot.getString() + "_jom_hd.txt"), optPair.getFirst());
281                TimeTrace.printToFile(new File (simulation_outFileNameRoot.getString() + "_jom_objFunc.txt"), optPair.getSecond());
282                return null;
283        }
284        
285                        
286        private Pair<DoubleMatrix1D,Double> computeOptimumSolution ()
287        {
288                OptimizationProblem op = new OptimizationProblem();
289
290                /* Add the decision variables to the problem */
291                op.addDecisionVariable("h_d", false, new int[] {1, D}, control_minHd.getDouble() , control_maxHd.getDouble());
292
293                /* Set some input parameters */
294                op.setInputParameter("u_e", currentNetPlan.getVectorLinkCapacity() , "row");
295                op.setInputParameter("alpha", this.control_fairnessFactor.getDouble());
296                op.setInputParameter("R_de", currentNetPlan.getMatrixDemand2LinkAssignment());
297
298                /* Sets the objective function */
299                if (control_fairnessFactor.getDouble() == 1)
300                    op.setObjectiveFunction("maximize", "sum(ln(h_d))");
301                else if (control_fairnessFactor.getDouble() == 0)
302                    op.setObjectiveFunction("maximize", "sum(h_d)");
303                else
304                    op.setObjectiveFunction("maximize", "(1-alpha) * sum(h_d ^ (1-alpha))");
305
306                op.addConstraint("h_d * R_de <= u_e"); // the capacity constraints (E constraints)
307
308                /* Call the solver to solve the problem */
309                op.solve("ipopt");
310
311                /* If an optimal solution was not found, quit */
312                if (!op.solutionIsOptimal()) throw new Net2PlanException("An optimal solution was not found");
313
314                /* Retrieve the optimum solutions */
315                DoubleMatrix1D h_d = op.getPrimalSolution("h_d").view1D ();
316                return Pair.of(h_d ,NetworkPerformanceMetrics.alphaUtility(h_d , control_fairnessFactor.getDouble()));
317        }
318                        
319        
320        
321        /* Computes the price, and the price for diagonal scaling */
322        private double computeFirstOrderPriceFromNetPlan (Link e)
323        {
324                final double y_e = e.getCarriedTraffic();
325                final double u_e = e.getCapacity();
326                if (u_e == 0) throw new RuntimeException ("Zero capacity in a link");
327                double price = 0;
328                if (control_isBarrierMethod)
329                {
330                        if (y_e / u_e < 1)
331                                price = u_e / Math.pow(u_e - y_e , 2);
332                        else
333                                price = Double.MAX_VALUE; 
334                }
335                else
336                        price = Math.max(0, y_e - u_e);
337                return price;
338        }
339
340        private double computeSecondOrderPriceFromNetPlan (Link e)
341        {
342                final double y_e = e.getCarriedTraffic();
343                final double u_e = e.getCapacity();
344                if (u_e == 0) throw new RuntimeException ("Zero capacity in a link");
345                double priceDiagScaling = 0;
346                if (control_isBarrierMethod)
347                {
348                        if (y_e / u_e < 1)
349                                priceDiagScaling = 2 * u_e / Math.pow(u_e - y_e , 3);
350                        else
351                                priceDiagScaling = Double.MAX_VALUE; //2 * u_e / Math.pow(u_e - 0.999999 * u_e , 3);
352                }
353                else
354                        priceDiagScaling = (y_e <= u_e)? 0 : 2;
355                return priceDiagScaling;
356        }
357
358        
359}