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 cern.jet.math.tdouble.DoubleFunctions; 019import com.net2plan.examples.ocnbook.offline.Offline_ca_wirelessTransmissionPower; 020import com.net2plan.interfaces.networkDesign.Link; 021import com.net2plan.interfaces.networkDesign.Net2PlanException; 022import com.net2plan.interfaces.networkDesign.NetPlan; 023import com.net2plan.interfaces.simulation.IEventProcessor; 024import com.net2plan.interfaces.simulation.SimEvent; 025import com.net2plan.libraries.NetworkPerformanceMetrics; 026import com.net2plan.libraries.WirelessUtils; 027import com.net2plan.utils.*; 028 029import java.io.File; 030import java.util.HashMap; 031import java.util.List; 032import java.util.Map; 033import java.util.Random; 034 035/** 036 * This module implements a distributed primal-gradient based algorithm for adjusting the transmission power of the links in a wireless network subject to interferences, to maximize the network utility enforcing a fair allocation of the resources. 037 * 038 * Ths event processor is adapted to permit observing the algorithm performances under user-defined conditions, 039 * including asynchronous distributed executions, where signaling can be affected by losses and/or delays, and/or measurement errors. 040 * The time evolution of different metrics can be stored in output files, for later processing. 041 * As an example, see the <a href="../../../../../../graphGeneratorFiles/fig_sec9_6_powerAssignmentPrimal.m">{@code fig_sec9_6_powerAssignmentPrimal.m}</a> MATLAB file used for generating the graph/s of the case study in the 042 * <a href="http://eu.wiley.com/WileyCDA/WileyTitle/productCd-1119013356.html">book</a> using this algorithm. 043 * 044 * To simulate a network with this module, use the {@code Online_evGen_doNothing} generator. 045 * 046 * @net2plan.keywords Transmission power optimization, Wireless, Distributed algorithm, Primal gradient algorithm, Capacity assignment (CA) 047 * @net2plan.ocnbooksections Section 9.6 048 * @net2plan.inputParameters 049 * @author Pablo Pavon-Marino 050 */ 051@SuppressWarnings("unchecked") 052public class Online_evProc_powerAssignmentPrimal extends IEventProcessor 053{ 054 private InputParameter signaling_isSynchronous = new InputParameter ("signaling_isSynchronous", false , "true if all the distributed agents involved wake up synchronously to send the signaling messages"); 055 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); 056 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); 057 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); 058 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); 059 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); 060 private InputParameter update_isSynchronous = new InputParameter ("update_isSynchronous", false , "true if all the distributed agents involved wake up synchronousely to update its state"); 061 private InputParameter update_averageInterUpdateTime = new InputParameter ("update_averageInterUpdateTime", 1.0 , "Average time between two updates of an agent" , 0 , false , Double.MAX_VALUE , true); 062 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); 063 064 private InputParameter gradient_maxGradientAbsoluteNoise = new InputParameter ("gradient_maxGradientAbsoluteNoise", 0.01 , "Max value of the added noise to the gradient coordinate in absolute values" , 0 , true , Double.MAX_VALUE , true); 065 private InputParameter gradient_gammaStep = new InputParameter ("gradient_gammaStep", 10.0 , "Gamma step in the gradient algorithm" , 0 , false , Double.MAX_VALUE , true); 066 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); 067 private InputParameter gradient_maxGradientCoordinateChange = new InputParameter ("gradient_maxGradientCoordinateChange", 1000.0 , "Maximum change in an iteration of a gradient coordinate" , 0 , false , Double.MAX_VALUE , true); 068 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", "powerTransmissionAsignmentPrimal" , "Root of the file name to be used in the output files. If blank, no output"); 071 private InputParameter simulation_maxNumberOfUpdateIntervals = new InputParameter ("simulation_maxNumberOfUpdateIntervals", 100.0 , "Maximum number of update intervals in average per agent" , 0 , false , Double.MAX_VALUE , true); 072 073 private InputParameter control_pathLossExponent = new InputParameter ("control_pathLossExponent", 3.0 , "Exponent in the model for propagation losses" , 0 , true , Double.MAX_VALUE , true); 074 private InputParameter control_worseRiseOverThermal_nu = new InputParameter ("control_worseRiseOverThermal_nu", 10.0 , "Worse case ratio between interference power and thermal power at any receiver. Used to set the common thermal power in the receivers" , 0 , true , Double.MAX_VALUE , true); 075 private InputParameter control_interferenceAttenuationFactor_nu = new InputParameter ("control_interferenceAttenuationFactor_nu", 1.0e6 , "The interference power received in natural units is divided by this to reduce its effect" , 1 , true , Double.MAX_VALUE , true); 076 private InputParameter control_maxTransmissionPower_logu = new InputParameter ("control_maxTransmissionPower_logu", 3.0 , "The maximum link transmission power in logarithmic units (e.g. dBm)"); 077 private InputParameter control_minTransmissionPower_logu = new InputParameter ("control_minTransmissionPower_logu", 0.0 , "The minimum link transmission power in logarithmic units (e.g. dBm)"); 078 private InputParameter control_fairnessFactor = new InputParameter ("control_fairnessFactor", 2.0 , "Fairness factor in utility function of link capacities" , 0 , true , Double.MAX_VALUE , true); 079 080 private static final int SIGNALING_WAKEUPTOSENDMESSAGE = 300; 081 private static final int SIGNALING_RECEIVEDMESSAGE = 301; 082 private static final int UPDATE_WAKEUPTOUPDATE = 302; 083 084 private Random rng; 085 private int E , N; 086 private DoubleMatrix2D mac_g_nu_ee; 087 private DoubleMatrix1D mac_transmissionPower_logu_e; 088 private DoubleMatrix1D mac_previousTransmissionPower_logu_e; 089 private double mac_receptionThermalNoise_nu; 090 091 private DoubleMatrix2D control_mostUpdatedMe2ValueKnownByLink1_e1e2; 092 093 private TimeTrace stat_traceOf_u_e; 094 private TimeTrace stat_traceOf_p_e; 095 private TimeTrace stat_traceOf_objFunction; 096 097 private NetPlan currentNetPlan , copyInitialNetPlan; 098 099 @Override 100 public String getDescription() 101 { 102 return "This module implements a distributed primal-gradient based algorithm for adjusting the transmission power of the links in a wireless network subject to interferences, to maximize the network utility enforcing a fair allocation of the resources."; 103 } 104 105 @Override 106 public List<Triple<String, String, String>> getParameters() 107 { 108 /* Returns the parameter information for all the InputParameter objects defined in this object (uses Java reflection) */ 109 return InputParameter.getInformationAllInputParameterFieldsOfObject(this); 110 } 111 112 @Override 113 public void initialize(NetPlan currentNp, Map<String, String> algorithmParameters, Map<String, String> simulationParameters, Map<String, String> net2planParameters) 114 { 115 /* Initialize all InputParameter objects defined in this object (this uses Java reflection) */ 116 InputParameter.initializeAllInputParameterFieldsOfObject(this, algorithmParameters); 117 118 this.currentNetPlan = currentNp; 119 this.copyInitialNetPlan = currentNp.copy (); 120 this.E = currentNp.getNumberOfLinks (); 121 this.N = currentNp.getNumberOfNodes (); 122 if (E == 0) throw new Net2PlanException ("The input design should have links"); 123 124 if (currentNp.getNumberOfLayers() != 1) throw new Net2PlanException ("This algorithm works in single layer networks"); 125 126 this.rng = new Random (simulation_randomSeed.getLong ()); 127 128 /* Initialize the gains between links, normalizing them so that the maximum gain is one */ 129 this.mac_g_nu_ee = WirelessUtils.computeInterferenceMatrixNaturalUnits (currentNetPlan.getLinks () , control_interferenceAttenuationFactor_nu.getDouble() , control_pathLossExponent.getDouble()); 130 //System.out.println("NOT normalized Gnu_ee: " + Gnu_ee); 131 final double maxGainValue = mac_g_nu_ee.getMaxLocation() [0]; 132 mac_g_nu_ee.assign (DoubleFunctions.div(maxGainValue)); 133 //System.out.println("normalized mac_g_nu_ee: " + mac_g_nu_ee); 134 135 /* Initialize the thermal noise at the receivers, to have a worse case ROT (rise over thermal) */ 136 double worseInterferenceReceivedAtMaxPower_nu = WirelessUtils.computeWorseReceiverInterferencePower_nu (control_maxTransmissionPower_logu.getDouble() , mac_g_nu_ee); 137 138 /* Adjust the thermal noise in the receivers so that we have a given ROT */ 139 this.mac_receptionThermalNoise_nu = worseInterferenceReceivedAtMaxPower_nu / control_worseRiseOverThermal_nu.getDouble(); 140 141 /* Initialize the transmission power variables */ 142 this.mac_transmissionPower_logu_e = DoubleFactory1D.dense.make (E , control_minTransmissionPower_logu.getDouble()); 143 this.mac_previousTransmissionPower_logu_e = DoubleFactory1D.dense.make (E , control_minTransmissionPower_logu.getDouble()); 144 145 /* Update the netplan object with the resulting capacities */ 146 for (Link e : currentNp.getLinks()) 147 e.setCapacity(Math.log(computeSINR_e (e))); 148 149 this.control_mostUpdatedMe2ValueKnownByLink1_e1e2 = DoubleFactory2D.dense.make (E,E); 150 for (Link e1 : currentNp.getLinks()) 151 { 152 for (Link otherLink : currentNp.getLinks()) 153 if (e1 != otherLink) 154 control_mostUpdatedMe2ValueKnownByLink1_e1e2.set(e1.getIndex () , otherLink.getIndex(), computeMeFactor_e (otherLink)); 155 } 156 157 /* Initially all links receive a "wake up to transmit" event, aligned at time zero or y asynchr => randomly chosen */ 158 for (Link e : currentNp.getLinks()) 159 { 160 final double signalingTime = (signaling_isSynchronous.getBoolean())? signaling_averageInterMessageTime.getDouble() : Math.max(0 , signaling_averageInterMessageTime.getDouble() + signaling_maxFluctuationInterMessageTime.getDouble() * (rng.nextDouble() - 0.5)); 161 this.scheduleEvent(new SimEvent (signalingTime , SimEvent.DestinationModule.EVENT_PROCESSOR , SIGNALING_WAKEUPTOSENDMESSAGE , e)); 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 , e)); 164 } 165 166 /* Intialize the traces */ 167 this.stat_traceOf_u_e = new TimeTrace (); 168 this.stat_traceOf_p_e = new TimeTrace (); 169 this.stat_traceOf_objFunction = new TimeTrace (); 170 this.stat_traceOf_u_e.add(0.0, this.currentNetPlan.getVectorLinkCapacity()); 171 this.stat_traceOf_p_e.add(0.0, this.mac_transmissionPower_logu_e.copy ()); 172 this.stat_traceOf_objFunction.add(0.0 , NetworkPerformanceMetrics.alphaUtility(currentNetPlan.getVectorLinkCapacity() , control_fairnessFactor.getDouble())); 173 174 /* */ 175// System.out.println("Initialize control_mostUpdatedMe2ValueKnownByLink1_e1e2: " + this.control_mostUpdatedMe2ValueKnownByLink1_e1e2); 176// System.out.println("mac_g_nu_ee: " + this.mac_g_nu_ee); 177 } 178 179 @Override 180 public void processEvent(NetPlan currentNetPlan, SimEvent event) 181 { 182 final double t = event.getEventTime(); 183 switch (event.getEventType()) 184 { 185 case SIGNALING_RECEIVEDMESSAGE: // a link receives the signaling informatio 186 { 187 final Pair<Link,Pair<Link,Double>> signalInfo = (Pair<Link,Pair<Link,Double>>) event.getEventObject(); 188 final Link eMe = signalInfo.getFirst(); 189 final Link otherLink = signalInfo.getSecond().getFirst(); 190 final double otherLink_me = signalInfo.getSecond().getSecond(); 191 control_mostUpdatedMe2ValueKnownByLink1_e1e2.set (eMe.getIndex () , otherLink.getIndex () , otherLink_me); 192 break; 193 } 194 195 case SIGNALING_WAKEUPTOSENDMESSAGE: // A link sends signaling information 196 { 197 final Link eMe = (Link) event.getEventObject(); 198 199 Pair<Link,Double> infoToSignal = Pair.of(eMe , this.computeMeFactor_e(eMe)); 200 if (rng.nextDouble() >= this.signaling_signalingLossProbability.getDouble()) // the signaling may be lost => lost to all nodes 201 for (Link otherLink : currentNetPlan.getLinks ()) 202 if (otherLink != eMe) 203 { 204 final double signalingReceptionTime = t + Math.max(0 , signaling_averageDelay.getDouble() + signaling_maxFluctuationInDelay.getDouble() * (rng.nextDouble() - 0.5)); 205 this.scheduleEvent(new SimEvent (signalingReceptionTime , SimEvent.DestinationModule.EVENT_PROCESSOR , SIGNALING_RECEIVEDMESSAGE , Pair.of(otherLink , infoToSignal))); 206 } 207 208 /* Re-schedule when to wake up again */ 209 final double signalingTime = signaling_isSynchronous.getBoolean()? t + signaling_averageInterMessageTime.getDouble() : Math.max(t , t + signaling_averageInterMessageTime.getDouble() + signaling_maxFluctuationInterMessageTime.getDouble() * (rng.nextDouble() - 0.5)); 210 this.scheduleEvent(new SimEvent (signalingTime , SimEvent.DestinationModule.EVENT_PROCESSOR , SIGNALING_WAKEUPTOSENDMESSAGE , eMe)); 211 break; 212 } 213 214 case UPDATE_WAKEUPTOUPDATE: // a link updates its power 215 { 216 final Link eMe = (Link) event.getEventObject(); 217 218 final double currentTransmissionPower_logu = this.mac_transmissionPower_logu_e.get(eMe.getIndex ()); 219 double gradientThisLink = computeGradient (eMe) + 2*gradient_maxGradientAbsoluteNoise.getDouble()*(rng.nextDouble()-0.5); 220 double nextTransmissionPower_logu = currentTransmissionPower_logu + this.gradient_gammaStep.getDouble() * gradientThisLink; 221 222 /* heavy ball */ 223 nextTransmissionPower_logu += this.gradient_heavyBallBetaParameter.getDouble() * (currentTransmissionPower_logu - mac_previousTransmissionPower_logu_e.get(eMe.getIndex ())); 224 /* projection */ 225 nextTransmissionPower_logu = GradientProjectionUtils.euclideanProjection_boxLike(nextTransmissionPower_logu, this.control_minTransmissionPower_logu.getDouble(), this.control_maxTransmissionPower_logu.getDouble()); 226 227 if (gradient_maxGradientCoordinateChange.getDouble() > 0) 228 nextTransmissionPower_logu = GradientProjectionUtils.scaleDown_maxAbsoluteCoordinateChange (currentTransmissionPower_logu , nextTransmissionPower_logu , gradient_maxGradientCoordinateChange.getDouble()); 229 230 this.mac_previousTransmissionPower_logu_e.set(eMe.getIndex (), this.mac_transmissionPower_logu_e.get(eMe.getIndex ())); 231 this.mac_transmissionPower_logu_e.set(eMe.getIndex (), nextTransmissionPower_logu); 232 233 //System.out.println("Link " + eIdMe + ": mac_transmissionPower_logu_e values Before: " + currentTransmissionPower_logu + ", after: " + nextTransmissionPower_logu); 234 235 /* Send event next recomputing time */ 236 final double updateTime = update_isSynchronous.getBoolean()? t + update_averageInterUpdateTime.getDouble() : Math.max(t , t + update_averageInterUpdateTime.getDouble() + update_maxFluctuationInterUpdateTime.getDouble() * (rng.nextDouble() - 0.5)); 237 this.scheduleEvent(new SimEvent (updateTime , SimEvent.DestinationModule.EVENT_PROCESSOR , UPDATE_WAKEUPTOUPDATE, eMe)); 238 239 /* Update in currentNetPlan the capacity values */ 240 for (Link e : this.currentNetPlan.getLinks()) 241 e.setCapacity(Math.log(computeSINR_e (e))); 242 243 this.stat_traceOf_u_e.add(t, this.currentNetPlan.getVectorLinkCapacity()); 244 this.stat_traceOf_p_e.add(t, this.mac_transmissionPower_logu_e.copy ()); 245 this.stat_traceOf_objFunction.add(t , NetworkPerformanceMetrics.alphaUtility(currentNetPlan.getVectorLinkCapacity() , control_fairnessFactor.getDouble())); 246 247 if (t > this.simulation_maxNumberOfUpdateIntervals.getDouble() * this.update_averageInterUpdateTime.getDouble()) { this.endSimulation (); } 248 249 break; 250 } 251 252 default: throw new RuntimeException ("Unexpected received event"); 253 } 254 255 256 } 257 258 public String finish (StringBuilder st , double simTime) 259 { 260 if (simulation_outFileNameRoot.getString().equals("")) return null; 261 stat_traceOf_u_e.printToFile(new File (simulation_outFileNameRoot.getString() + "_ue.txt")); 262 stat_traceOf_objFunction.printToFile(new File (simulation_outFileNameRoot.getString() + "_objFunc.txt")); 263 stat_traceOf_p_e.printToFile(new File (simulation_outFileNameRoot.getString() + "_pe.txt")); 264 /* compute optimum solution */ 265 Map<String,String> param = new HashMap<String,String> (); 266 param.put("solverName", "ipopt"); 267 param.put("solverLibraryName", ""); 268 param.put("maxSolverTimeInSeconds", "-1"); 269 param.put("alphaFairnessFactor", "" + this.control_fairnessFactor.getDouble()); 270 param.put("pathLossExponent", "" + this.control_pathLossExponent.getDouble()); 271 param.put("worseRiseOverThermal_nu", "" + this.control_worseRiseOverThermal_nu.getDouble()); 272 param.put("interferenceAttenuationFactor_nu", "" + this.control_interferenceAttenuationFactor_nu.getDouble()); 273 param.put("maxTransmissionPower_logu", "" + this.control_maxTransmissionPower_logu.getDouble()); 274 param.put("minTransmissionPower_logu", "" + this.control_minTransmissionPower_logu.getDouble()); 275 new Offline_ca_wirelessTransmissionPower ().executeAlgorithm(copyInitialNetPlan , param , null); 276 final double optimumNetUtilityJOM = NetworkPerformanceMetrics.alphaUtility(copyInitialNetPlan.getVectorLinkCapacity() , control_fairnessFactor.getDouble()); 277 DoubleMatrix1D optimum_ue = copyInitialNetPlan.getVectorLinkCapacity(); 278 DoubleMatrix1D optimum_pe = DoubleFactory1D.dense.make (E); 279 for (Link e : copyInitialNetPlan.getLinks ()) optimum_pe.set (e.getIndex () , Double.parseDouble (e.getAttribute("p_e"))); 280 TimeTrace.printToFile(new File (simulation_outFileNameRoot.getString() + "_jom_ue.txt"), optimum_ue); 281 TimeTrace.printToFile(new File (simulation_outFileNameRoot.getString() + "_jom_pe.txt"), optimum_pe); 282 TimeTrace.printToFile(new File (simulation_outFileNameRoot.getString() + "_jom_objFunc.txt"), optimumNetUtilityJOM); 283 return null; 284 } 285 286 287 private double computeGradient (Link thisLink) 288 { 289 final double u_e = thisLink.getCapacity(); 290 final DoubleMatrix1D infoIKnow_me = control_mostUpdatedMe2ValueKnownByLink1_e1e2.viewRow(thisLink.getIndex ()); 291 292 double gradient = Math.pow(u_e, -this.control_fairnessFactor.getDouble()); 293 double accumFactor = 0; 294 for (Link epp : this.currentNetPlan.getLinks()) 295 if (epp != thisLink) 296 accumFactor += this.mac_g_nu_ee.get(thisLink.getIndex (),epp.getIndex ()) * infoIKnow_me.get(epp.getIndex ()); 297 accumFactor *= Math.exp(this.mac_transmissionPower_logu_e.get(thisLink.getIndex ())); 298 //System.out.println("Gradient: positive factor: " + gradient + ", negative factor: " + accumFactor); 299 gradient -= accumFactor; 300 return gradient; 301 } 302 303 private double computeMeFactor_e (Link e) 304 { 305 final double u_e = e.getCapacity(); 306 final double snr_e = Math.exp(u_e); 307 return Math.pow(u_e,-this.control_fairnessFactor.getDouble()) * snr_e / (Math.exp(this.mac_transmissionPower_logu_e.get(e.getIndex ())) * this.mac_g_nu_ee.get(e.getIndex (),e.getIndex ())); 308 } 309 310 private double computeSINR_e (Link e) 311 { 312 final double receivedPower_nu = Math.exp(this.mac_transmissionPower_logu_e.get(e.getIndex ())) * this.mac_g_nu_ee.get(e.getIndex (),e.getIndex ()); 313 double interferencePower_nu = this.mac_receptionThermalNoise_nu; 314 for (Link eInt : this.currentNetPlan.getLinks ()) 315 if (eInt != e) interferencePower_nu += Math.exp(this.mac_transmissionPower_logu_e.get(eInt.getIndex ())) * this.mac_g_nu_ee.get(eInt.getIndex (),e.getIndex ()); 316// System.out.println ("SINR link " + e + ": " + receivedPower_nu / interferencePower_nu); 317// System.out.println ("receiver power link " + e + ": " + receivedPower_nu + ", total interf power: " + interferencePower_nu + "thermal noise: " + mac_receptionThermalNoise_nu); 318 return receivedPower_nu / interferencePower_nu; 319 } 320 321}