Eclipse SUMO - Simulation of Urban MObility
emissionsDrivingCycle_main.cpp
Go to the documentation of this file.
1 /****************************************************************************/
2 // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
3 // Copyright (C) 2013-2022 German Aerospace Center (DLR) and others.
4 // This program and the accompanying materials are made available under the
5 // terms of the Eclipse Public License 2.0 which is available at
6 // https://www.eclipse.org/legal/epl-2.0/
7 // This Source Code may also be made available under the following Secondary
8 // Licenses when the conditions for such availability set forth in the Eclipse
9 // Public License 2.0 are satisfied: GNU General Public License, version 2
10 // or later which is available at
11 // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12 // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13 /****************************************************************************/
19 // Main for an emissions calculator
20 /****************************************************************************/
21 #include <config.h>
22 
23 #ifdef HAVE_VERSION_H
24 #include <version.h>
25 #endif
26 
28 #include <iostream>
29 #include <string>
30 #include <ctime>
32 #include <utils/options/Option.h>
37 #include <utils/common/ToString.h>
38 #include <utils/xml/XMLSubSys.h>
47 #include "TrajectoriesHandler.h"
48 #include "VTypesHandler.h"
49 
50 
51 // ===========================================================================
52 // functions
53 // ===========================================================================
54 
55 
56 /* -------------------------------------------------------------------------
57  * main
58  * ----------------------------------------------------------------------- */
59 int
60 main(int argc, char** argv) {
61  // build options
63  // give some application descriptions
64  oc.setApplicationDescription("Computes emissions by driving a time line using SUMO's emission models.");
65  oc.setApplicationName("emissionsDrivingCycle", "Eclipse SUMO emissionsDrivingCycle Version " VERSION_STRING);
66  // add options
67 
69  oc.addOptionSubTopic("Input");
70  oc.doRegister("timeline-file", 't', new Option_FileName());
71  oc.addSynonyme("timeline", "timeline-file");
72  oc.addDescription("timeline-file", "Input", "Defines the file to read the driving cycle from.");
73 
74  oc.doRegister("timeline-file.skip", new Option_Integer(0));
75  oc.addSynonyme("timeline.skip", "timeline-file.skip");
76  oc.addDescription("timeline-file.skip", "Input", "Skips the firs NUM lines.");
77 
78  oc.doRegister("timeline-file.separator", new Option_String(";"));
79  oc.addSynonyme("timeline.separator", "timeline-file.separator");
80  oc.addDescription("timeline-file.separator", "Input", "Defines the entry separator.");
81 
82  oc.doRegister("netstate-file", 'n', new Option_FileName());
83  oc.addSynonyme("netstate", "netstate-file");
84  oc.addSynonyme("amitran", "netstate-file");
85  oc.addDescription("netstate-file", "Input", "Defines the netstate, route and trajectory files to read the driving cycles from.");
86 
87  oc.doRegister("additional-files", new Option_FileName());
88  oc.addDescription("additional-files", "Input", "Load emission parameters (vTypes) from FILE(s)");
89 
90  oc.doRegister("emission-class", 'e', new Option_String("unknown"));
91  oc.addDescription("emission-class", "Input", "Defines for which emission class the emissions shall be generated. ");
92 
93  oc.doRegister("vtype", new Option_String());
94  oc.addDescription("vtype", "Input", "Defines the vehicle type to use for emission parameters.");
95 
96  oc.addOptionSubTopic("Processing");
97  oc.doRegister("compute-a", 'a', new Option_Bool(false));
98  oc.addDescription("compute-a", "Processing", "If set, the acceleration is computed instead of being read from the file. ");
99 
100  oc.doRegister("compute-a.forward", new Option_Bool(false));
101  oc.addDescription("compute-a.forward", "Processing", "If set, the acceleration for time t is computed from v(t+1) - v(t) instead of v(t) - v(t-1). ");
102 
103  oc.doRegister("compute-a.zero-correction", new Option_Bool(false));
104  oc.addDescription("compute-a.zero-correction", "Processing", "If set, the acceleration for time t is set to 0 if the speed is 0. ");
105 
106  oc.doRegister("skip-first", 's', new Option_Bool(false));
107  oc.addDescription("skip-first", "Processing", "If set, the first line of the read file is skipped.");
108 
109  oc.doRegister("kmh", new Option_Bool(false));
110  oc.addDescription("kmh", "Processing", "If set, the given speed is interpreted as being given in km/h.");
111 
112  oc.doRegister("have-slope", new Option_Bool(false));
113  oc.addDescription("have-slope", "Processing", "If set, the fourth column is read and used as slope (in deg).");
114 
115  oc.doRegister("slope", new Option_Float(0));
116  oc.addDescription("slope", "Processing", "Sets a global slope (in deg) that is used if the file does not contain slope information.");
117 
118  oc.addOptionSubTopic("Output");
119  oc.doRegister("output-file", 'o', new Option_String());
120  oc.addSynonyme("output", "output-file");
121  oc.addDescription("output", "Output", "Defines the file to write the emission cycle results into. ");
122 
123  oc.doRegister("emission-output", new Option_FileName());
124  oc.addDescription("emission-output", "Output", "Save the emission values of each vehicle in XML");
125 
126  oc.doRegister("sum-output", new Option_FileName());
127  oc.addSynonyme("sum", "sum-output");
128  oc.addDescription("sum-output", "Output", "Save the aggregated and normed emission values of each vehicle in CSV");
129 
130  oc.addOptionSubTopic("Emissions");
131  oc.doRegister("phemlight-path", new Option_FileName(StringVector({ "./PHEMlight/" })));
132  oc.addDescription("phemlight-path", "Emissions", "Determines where to load PHEMlight definitions from.");
133 
134  oc.doRegister("begin", new Option_String("0", "TIME"));
135  oc.addDescription("begin", "Processing", "Defines the begin time in seconds;");
136 
137  oc.doRegister("end", new Option_String("-1", "TIME"));
138  oc.addDescription("end", "Processing", "Defines the end time in seconds;");
139 
141  oc.doRegister("quiet", 'q', new Option_Bool(false));
142  oc.addDescription("quiet", "Report", "Not writing anything.");
143 
144  // run
145  int ret = 0;
146  bool quiet = false;
147  try {
148  // initialise the application system (messaging, xml, options)
149  XMLSubSys::init();
150  OptionsIO::setArgs(argc, argv);
152  if (oc.processMetaOptions(argc < 2)) {
154  return 0;
155  }
156 
157  quiet = oc.getBool("quiet");
158  if (!oc.isSet("timeline-file") && !oc.isSet("netstate-file")) {
159  throw ProcessError("Either a timeline or a netstate / amitran file must be given.");
160  }
161  if (!oc.isSet("output-file") && (oc.isSet("timeline-file") || !oc.isSet("emission-output"))) {
162  throw ProcessError("The output file must be given.");
163  }
164  std::ostream* out = nullptr;
165  if (oc.isSet("output-file")) {
166  out = new std::ofstream(oc.getString("output-file").c_str());
167  }
168  OutputDevice::createDeviceByOption("emission-output", "emission-export", "emission_file.xsd");
169  OutputDevice* xmlOut = nullptr;
170  if (oc.isSet("emission-output")) {
171  xmlOut = &OutputDevice::getDeviceByOption("emission-output");
172  } else if (out == nullptr) {
173  out = &std::cout;
174  }
175  std::ostream* sumOut = nullptr;
176  if (oc.isSet("sum-output")) {
177  sumOut = new std::ofstream(oc.getString("sum-output").c_str());
178  (*sumOut) << "Vehicle,Cycle,Time,Speed,Gradient,Acceleration,FC,FCel,CO2,NOx,CO,HC,PM" << std::endl;
179  }
180 
181  EnergyParams energyParams;
182  std::map<std::string, SUMOVTypeParameter*> vTypes;
183  if (oc.isSet("vtype")) {
184  if (!oc.isSet("additional-files")) {
185  throw ProcessError("Option --vtype requires option --additional-files for loading vehicle types");
186  }
187  if (!oc.isUsableFileList("additional-files")) {
188  throw ProcessError();
189  }
190  for (auto file : oc.getStringVector("additional-files")) {
191  VTypesHandler typesHandler(file, vTypes);
192  if (!XMLSubSys::runParser(typesHandler, file)) {
193  throw ProcessError("Loading of " + file + " failed.");
194  }
195  }
196  if (vTypes.count(oc.getString("vtype")) == 0) {
197  throw ProcessError("Vehicle type '" + oc.getString("vtype") + "' is not defined");
198  }
199  energyParams = EnergyParams(vTypes[oc.getString("vtype")]);
200  }
201 
202  const SUMOEmissionClass defaultClass = PollutantsInterface::getClassByName(oc.getString("emission-class"));
203  const bool computeA = oc.getBool("compute-a") || oc.getBool("compute-a.forward");
204  TrajectoriesHandler handler(computeA, oc.getBool("compute-a.forward"), oc.getBool("compute-a.zero-correction"), defaultClass, &energyParams, oc.getFloat("slope"), out, xmlOut);
205 
206  if (oc.isSet("timeline-file")) {
207  int skip = oc.getBool("skip-first") ? 1 : oc.getInt("timeline-file.skip");
208  const bool inKMH = oc.getBool("kmh");
209  const bool haveSlope = oc.getBool("have-slope");
210  double l = 0;
211  double totalA = 0;
212  double totalS = 0;
213  int time = 0;
214 
215  LineReader lr(oc.getString("timeline-file"));
216  while (lr.hasMore()) {
217  std::string line = lr.readLine();
218  if (skip > 0) {
219  skip--;
220  continue;
221  }
222  StringTokenizer st(StringUtils::prune(line), oc.getString("timeline-file.separator"));
223  if (st.hasNext()) {
224  try {
225  double t = StringUtils::toDouble(st.next());
226  double v = 0;
227  if (st.hasNext()) {
228  v = StringUtils::toDouble(st.next());
229  } else {
230  v = t;
231  t = time;
232  }
233  if (inKMH) {
234  v /= 3.6;
235  }
236  double a = !computeA && st.hasNext() ? StringUtils::toDouble(st.next()) : TrajectoriesHandler::INVALID_VALUE;
237  double s = haveSlope && st.hasNext() ? StringUtils::toDouble(st.next()) : TrajectoriesHandler::INVALID_VALUE;
238  if (handler.writeEmissions(*out, "", defaultClass, &energyParams, t, v, a, s)) {
239  l += v;
240  totalA += a;
241  totalS += s;
242  time++;
243  }
244  } catch (EmptyData&) {
245  throw ProcessError("Missing an entry in line '" + line + "'.");
246  } catch (NumberFormatException&) {
247  throw ProcessError("Not numeric entry in line '" + line + "'.");
248  }
249  }
250  }
251  if (!quiet) {
252  std::cout << "sums" << std::endl
253  << "length:" << l << std::endl;
254  }
255  if (sumOut != nullptr) {
256  (*sumOut) << oc.getString("emission-class") << "," << lr.getFileName() << "," << time << ","
257  << (l / time * 3.6) << "," << (totalS / time) << "," << (totalA / time) << ",";
258  handler.writeNormedSums(*sumOut, "", l);
259  }
260  }
261  if (oc.isSet("netstate-file")) {
262  XMLSubSys::runParser(handler, oc.getString("netstate-file"));
263  }
264  if (!quiet) {
265  handler.writeSums(std::cout, "");
266  }
267  delete sumOut;
268 
269  } catch (InvalidArgument& e) {
271  MsgHandler::getErrorInstance()->inform("Quitting (on error).", false);
272  ret = 1;
273  } catch (ProcessError& e) {
274  if (std::string(e.what()) != std::string("Process Error") && std::string(e.what()) != std::string("")) {
276  }
277  MsgHandler::getErrorInstance()->inform("Quitting (on error).", false);
278  ret = 1;
279 #ifndef _DEBUG
280  } catch (...) {
281  MsgHandler::getErrorInstance()->inform("Quitting (on unknown error).", false);
282  ret = 1;
283 #endif
284  }
286  if (ret == 0 && !quiet) {
287  std::cout << "Success." << std::endl;
288  }
289  return ret;
290 }
291 
292 
293 /****************************************************************************/
std::vector< std::string > StringVector
Definition of a vector of strings.
Definition: Option.h:43
int SUMOEmissionClass
An upper class for objects with additional parameters.
Definition: EnergyParams.h:41
Retrieves a file linewise and reports the lines to a handler.
Definition: LineReader.h:48
bool readLine(LineHandler &lh)
Reads a single (the next) line from the file and reports it to the given LineHandler.
Definition: LineReader.cpp:67
bool hasMore() const
Returns whether another line may be read (the file was not read completely)
Definition: LineReader.cpp:51
std::string getFileName() const
Returns the name of the used file.
Definition: LineReader.cpp:173
static MsgHandler * getErrorInstance()
Returns the instance to add errors to.
Definition: MsgHandler.cpp:80
virtual void inform(std::string msg, bool addType=true)
adds a new error to the list
Definition: MsgHandler.cpp:117
An integer-option.
Definition: Option.h:329
A storage for options typed value containers)
Definition: OptionsCont.h:89
void addDescription(const std::string &name, const std::string &subtopic, const std::string &description)
Adds a description for an option.
void doRegister(const std::string &name, Option *v)
Adds an option under the given name.
Definition: OptionsCont.cpp:75
bool isSet(const std::string &name, bool failOnNonExistant=true) const
Returns the information whether the named option is set.
double getFloat(const std::string &name) const
Returns the double-value of the named option (only for Option_Float)
int getInt(const std::string &name) const
Returns the int-value of the named option (only for Option_Integer)
void setApplicationName(const std::string &appName, const std::string &fullName)
Sets the application name.
std::string getString(const std::string &name) const
Returns the string-value of the named option (only for Option_String)
void addSynonyme(const std::string &name1, const std::string &name2, bool isDeprecated=false)
Adds a synonyme for an options name (any order)
Definition: OptionsCont.cpp:96
void setApplicationDescription(const std::string &appDesc)
Sets the application description.
void addOptionSubTopic(const std::string &topic)
Adds an option subtopic.
bool getBool(const std::string &name) const
Returns the boolean-value of the named option (only for Option_Bool)
const StringVector & getStringVector(const std::string &name) const
Returns the list of string-value of the named option (only for Option_StringVector)
static OptionsCont & getOptions()
Retrieves the options.
Definition: OptionsCont.cpp:58
bool processMetaOptions(bool missingOptions)
Checks for help and configuration output, returns whether we should exit.
bool isUsableFileList(const std::string &name) const
Checks whether the named option is usable as a file list (with at least a single file)
static void setArgs(int argc, char **argv)
Stores the command line arguments for later parsing.
Definition: OptionsIO.cpp:58
static void getOptions(const bool commandLineOnly=false)
Parses the command line arguments and loads the configuration.
Definition: OptionsIO.cpp:85
Static storage of an output device and its base (abstract) implementation.
Definition: OutputDevice.h:61
static bool createDeviceByOption(const std::string &optionName, const std::string &rootElement="", const std::string &schemaFile="")
Creates the device using the output definition stored in the named option.
static OutputDevice & getDeviceByOption(const std::string &name)
Returns the device described by the option.
static SUMOEmissionClass getClassByName(const std::string &eClass, const SUMOVehicleClass vc=SVC_IGNORING)
Checks whether the string describes a known vehicle class.
bool hasNext()
returns the information whether further substrings exist
std::string next()
returns the next substring when it exists. Otherwise the behaviour is undefined
static double toDouble(const std::string &sData)
converts a string into the double value described by it by calling the char-type converter
static std::string prune(const std::string &str)
Removes trailing and leading whitechars.
Definition: StringUtils.cpp:48
static void close()
Closes all of an applications subsystems.
static void addConfigurationOptions(OptionsCont &oc)
Adds configuration options to the given container.
Definition: SystemFrame.cpp:38
static void addReportOptions(OptionsCont &oc)
Adds reporting options to the given container.
Definition: SystemFrame.cpp:63
An XML-Handler for amitran and netstate trajectories.
void writeNormedSums(std::ostream &o, const std::string id, const double factor)
void writeSums(std::ostream &o, const std::string id)
static const int INVALID_VALUE
bool writeEmissions(std::ostream &o, const std::string id, const SUMOEmissionClass c, EnergyParams *params, double t, double &v, double &a, double &s)
An XML-Handler for amitran and netstate trajectories.
Definition: VTypesHandler.h:38
static void init()
Initialises the xml-subsystem.
Definition: XMLSubSys.cpp:54
static bool runParser(GenericSAXHandler &handler, const std::string &file, const bool isNet=false, const bool isRoute=false)
Runs the given handler on the given file; returns if everything's ok.
Definition: XMLSubSys.cpp:149
int main(int argc, char **argv)