summaryrefslogtreecommitdiff
path: root/ns3-simulations/simulate.org
blob: 43aa253b6fddcde0af42962028f63cc1162d1da9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266



* Run simulations
  To run all the simulations, execute the following call:
  #+NAME: runSim
  #+CALL: runBW(lat=runLat(nbSens=runNbSensors(nbHop=runNbHop())))

  #+RESULTS: runSim

** Experiments
*** Bandwidth
    #+NAME: runBW
    #+BEGIN_SRC bash :noweb yes :results output
      <<singleRun>>
      simKey="BW"
      for sensorsNumber in $(seq 1 15)
      do
          for linksBandwidth in $(seq 10 20 100)
          do
              run
          done      
      done
    #+END_SRC

    #+RESULTS: runBW

    #+RESULTS:

*** Latency
    #+NAME: runLat
    #+BEGIN_SRC bash :noweb yes :results output
      <<singleRun>>
      simKey="LATENCY"
      for sensorsNumber in $(seq 1 15)
      do
          for linksLatency in $(seq 1 1 10)
          do
              run
          done      
      done
    #+END_SRC

    #+RESULTS: runLat

    #+RESULTS:
    
*** Number of sensors
    #+NAME: runNbSensors
    #+BEGIN_SRC bash :noweb yes :results output
      <<singleRun>>
      simKey="NBSENSORS"
      for sensorsNumber in $(seq 1 5)
      do
          run
      done      
    #+END_SRC

    #+RESULTS:

*** Number of Hop
    #+NAME: runNbHop
    #+BEGIN_SRC bash :noweb yes :results output
      <<singleRun>>
      simKey="NBHOP"
      for sensorsNumber in $(seq 1 15)
      do
          for nbHop in $(seq 1 10)
          do
              run
          done
      done
    #+END_SRC

    #+RESULTS: runNbHop

** Single Run

   #+NAME: singleRun
   #+BEGIN_SRC bash :eval never :noweb yes :results output
     simulator="simulator/simulator"
     parseEnergyScript="./parseEnergy.awk"
     parseDelayScript="./parseDelay.awk"
     logFolder="logs/"
     export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${NS3_PATH}/build/lib

     # Default Parameters
     sensorsSendInterval=10
     sensorsPktSize=5 # 1 byte temperature (-128 à +128 °C) and 4Byte sensorsId
     sensorsNumber=10
     nbHop=10 # Cf paper AC/Yunbo
     linksBandwidth=10
     linksLatency=2
     simKey="NOKEY"

     run () {
         logFile="${logFolder}/${simKey}_${sensorsSendInterval}SSI_${sensorsPktSize}SPS_${sensorsNumber}SN_${nbHop}NH_${linksBandwidth}LB_${linksLatency}LL.org"
         [ -f "$logFile" ] && return
         simCMD="$simulator --sensorsSendInterval=${sensorsSendInterval} --sensorsPktSize=${sensorsPktSize} --sensorsNumber=${sensorsNumber} --nbHop=${nbHop} --linksBandwidth=${linksBandwidth} --linksLatency=${linksLatency} 2>&1"
         log=$(bash -c "$simCMD")

         # Compute some metrics
         energyLog=$(echo "$log" | $parseEnergyScript)
         avgDelay=$(echo "$log" | $parseDelayScript)
         totalEnergy=$(echo "$energyLog"| awk 'BEGIN{power=0;FS=","}NR!=1{power+=$2}END{print(power)}')
         nbPacketCloud=$(echo "$log"|grep -c "CloudSwitch receive")
         nbNodes=$(echo "$log"|awk '/Simulation used/{print($3)}')
         ns3Version=$(echo "$log"|awk '/NS-3 Version/{print($3)}')

         # Save logs
         echo -e "#+TITLE: $(date) ns-3 (version ${ns3Version}) simulation\n" > $logFile
         echo "* Environment Variables" >> $logFile
         env >> $logFile
         echo "* Full Command" >> $logFile
         echo "$simCMD" >> $logFile
         echo "* Output" >> $logFile
         echo "$log" >> $logFile
         echo "* Energy CSV (negative nodeId = WIFI, 0 = AP (Wireless+Wired), positive nodeId = ECOFEN" >> $logFile
         echo "$energyLog" >> $logFile
         echo "* Metrics" >> $logFile
         echo "-METRICSLINE- sensorsSendInterval:${sensorsSendInterval} sensorsPktSize:${sensorsPktSize} sensorsNumber:${sensorsNumber} nbHop:${nbHop} linksBandwidth:${linksBandwidth} linksLatency:${linksLatency} totalEnergy:$totalEnergy nbPacketCloud:$nbPacketCloud nbNodes:$nbNodes avgDelay:${avgDelay} ns3Version:${ns3Version} simKey:${simKey}" >> $logFile

     }

   #+END_SRC

* Logs Analysis
  To Generate all the plots, please execute the following line:
  #+NAME: runAnalysis
  #+CALL: plotToPDF(plots=genAllPlots(data=logToCSV()))

  #+RESULTS: runAnalysis

** R Scripts
*** Generate all plots script
    Available variables:
    |---------------------|
    | Name                |
    |---------------------|
    | sensorsSendInterval |
    | sensorsPktSize      |
    | sensorsNumber       |
    | nbHop               |
    | linksBandwidth      |
    | linksLatency        |
    | totalEnergy         |
    | nbPacketCloud       |
    | nbNodes             |
    | avgDelay            |
    | simKey              |
    |---------------------|

    #+NAME: genAllPlots
    #+BEGIN_SRC R :noweb yes :results output
      <<RUtils>>
      easyPlotGroup("linksLatency","totalEnergy", "LATENCY","sensorsNumber")
      easyPlotGroup("linksBandwidth","totalEnergy", "BW","sensorsNumber")
      easyPlot("sensorsNumber","totalEnergy", "NBSENSORS")
      easyPlotGroup("nbHop","totalEnergy", "NBHOP","sensorsNumber")
    #+END_SRC

    #+RESULTS: genAllPlots

*** R Utils
    RUtils is intended to load logs (data.csv) and providing
    simple plot function for them.

    #+NAME: RUtils
    #+BEGIN_SRC R :eval never
      library("tidyverse")

      # Fell free to update the following
      labels=c(nbNodes="Number of nodes",sensorsNumber="Number of sensors",totalEnergy="Total Energy (J)",
        nbHop="Number of hop (AP to Cloud)", linksBandwidth="Links Bandwidth (Mbps)",
        linksLatency="Links Latency (ms)")

      # Load Data
      data=read_csv("logs/data.csv")

      # Get label according to varName
      getLabel=function(varName){
        if(is.na(labels[varName])){
          return(varName)
        }
        return(labels[varName])
      }

      easyPlot=function(X,Y,KEY){
        curData=data%>%filter(simKey==KEY)
        stopifnot(NROW(curData)>0)
        ggplot(curData,aes_string(x=X,y=Y))+geom_point()+geom_line()+xlab(getLabel(X))+ylab(getLabel(Y))
        ggsave(paste0("plots/",KEY,"-",X,"_",Y,".png"))
      }

      easyPlotGroup=function(X,Y,KEY,GRP){
        curData=data%>%filter(simKey==KEY) %>% mutate(!!GRP:=as.character(UQ(rlang::sym(GRP)))) # %>%mutate(sensorsNumber=as.character(sensorsNumber))
        stopifnot(NROW(curData)>0)
        ggplot(curData,aes_string(x=X,y=Y,color=GRP,group=GRP))+geom_point()+geom_line()+xlab(getLabel(X))+ylab(getLabel(Y)) + labs(color = getLabel(GRP))
        ggsave(paste0("plots/",KEY,"-",X,"_",Y,".png"))
      }
    #+END_SRC

** Plots -> PDF
   Merge all plots in plots/ folder into a pdf file.
   #+NAME: plotToPDF
   #+BEGIN_SRC bash :results output :noweb yes
     orgFile="plots/plots.org"
     <<singleRun>> # To get all default arguments

     # Write helper function
     function write {
         echo "$1" >> $orgFile
     }

     echo "#+TITLE: Analysis" > $orgFile
     write "#+LATEX_HEADER: \usepackage{fullpage}"
     write "#+OPTIONS: toc:nil"
     # Default arguments
     write '\begin{center}'
     write '\begin{tabular}{lr}'
     write 'Parameters & Values\\'
     write '\hline'
     write "sensorsPktSize & ${sensorsPktSize} bytes\\\\"
     write "sensorsSendInterval & ${sensorsSendInterval}s\\\\"
     write "sensorsNumber & ${sensorsNumber}\\\\"
     write "nbHop & ${nbHop}\\\\"
     write "linksBandwidth & ${linksBandwidth}Mbps\\\\"
     write "linksLatency & ${linksLatency}ms\\\\"
     write '\end{tabular}'
     write '\newline'
     write '\end{center}'

     for plot in $(find plots/ -type f -name "*.png")
     do
         write "\includegraphics[width=0.5\linewidth]{$(basename ${plot})}"
     done

     # Export to pdf
     emacs $orgFile --batch -f org-latex-export-to-pdf --kill  
   #+END_SRC

   #+RESULTS:

** Log -> CSV
   logToCSV extract usefull data from logs and put them into logs/data.csv.

   #+NAME: logToCSV
   #+BEGIN_SRC bash :results none
     csvOutput="logs/data.csv"

     # First save csv header line
     aLog=$(find logs/ -type f -name "*.org"|head -n 1)
     metrics=$(cat $aLog|grep "\-METRICSLINE\-"|sed "s/-METRICSLINE-//g")
     echo $metrics | awk '{for(i=1;i<=NF;i++){split($i,elem,":");printf(elem[1]);if(i<NF)printf(",");else{print("")}}}' > $csvOutput

     # Second save all values
     for logFile in $(find logs/ -type f -name "*.org")
     do
         metrics=$(cat $logFile|grep "\-METRICSLINE\-"|sed "s/-METRICSLINE-//g")
         echo $metrics | awk '{for(i=1;i<=NF;i++){split($i,elem,":");printf(elem[2]);if(i<NF)printf(",");else{print("")}}}' >> $csvOutput
     done
   #+END_SRC