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-2020 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>
46 #include "TrajectoriesHandler.h"
47 
48 
49 // ===========================================================================
50 // functions
51 // ===========================================================================
52 
53 
54 /* -------------------------------------------------------------------------
55  * main
56  * ----------------------------------------------------------------------- */
57 int
58 main(int argc, char** argv) {
59  // build options
61  // give some application descriptions
62  oc.setApplicationDescription("Computes emissions by driving a time line using SUMO's emission models.");
63  oc.setApplicationName("emissionsDrivingCycle", "Eclipse SUMO emissionsDrivingCycle Version " VERSION_STRING);
64  // add options
65 
67  oc.addOptionSubTopic("Input");
68  oc.doRegister("timeline-file", 't', new Option_FileName());
69  oc.addSynonyme("timeline", "timeline-file");
70  oc.addDescription("timeline-file", "Input", "Defines the file to read the driving cycle from.");
71 
72  oc.doRegister("timeline-file.skip", new Option_Integer(0));
73  oc.addSynonyme("timeline.skip", "timeline-file.skip");
74  oc.addDescription("timeline-file.skip", "Input", "Skips the firs NUM lines.");
75 
76  oc.doRegister("timeline-file.separator", new Option_String(";"));
77  oc.addSynonyme("timeline.separator", "timeline-file.separator");
78  oc.addDescription("timeline-file.separator", "Input", "Defines the entry separator.");
79 
80  oc.doRegister("netstate-file", 'n', new Option_FileName());
81  oc.addSynonyme("netstate", "netstate-file");
82  oc.addSynonyme("amitran", "netstate-file");
83  oc.addDescription("netstate-file", "Input", "Defines the netstate, route and trajectory files to read the driving cycles from.");
84 
85  oc.doRegister("emission-class", 'e', new Option_String("unknown"));
86  oc.addDescription("emission-class", "Input", "Defines for which emission class the emissions shall be generated. ");
87 
88 
89  oc.addOptionSubTopic("Processing");
90  oc.doRegister("compute-a", 'a', new Option_Bool(false));
91  oc.addDescription("compute-a", "Processing", "If set, the acceleration is computed instead of being read from the file. ");
92 
93  oc.doRegister("compute-a.forward", new Option_Bool(false));
94  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). ");
95 
96  oc.doRegister("compute-a.zero-correction", new Option_Bool(false));
97  oc.addDescription("compute-a.zero-correction", "Processing", "If set, the acceleration for time t is set to 0 if the speed is 0. ");
98 
99  oc.doRegister("skip-first", 's', new Option_Bool(false));
100  oc.addDescription("skip-first", "Processing", "If set, the first line of the read file is skipped.");
101 
102  oc.doRegister("kmh", new Option_Bool(false));
103  oc.addDescription("kmh", "Processing", "If set, the given speed is interpreted as being given in km/h.");
104 
105  oc.doRegister("have-slope", new Option_Bool(false));
106  oc.addDescription("have-slope", "Processing", "If set, the fourth column is read and used as slope (in deg).");
107 
108  oc.doRegister("slope", new Option_Float(0));
109  oc.addDescription("slope", "Processing", "Sets a global slope (in deg) that is used if the file does not contain slope information.");
110 
111  oc.addOptionSubTopic("Output");
112  oc.doRegister("output-file", 'o', new Option_String());
113  oc.addSynonyme("output", "output-file");
114  oc.addDescription("output", "Output", "Defines the file to write the emission cycle results into. ");
115 
116  oc.doRegister("emission-output", new Option_FileName());
117  oc.addDescription("emission-output", "Output", "Save the emission values of each vehicle in XML");
118 
119  oc.doRegister("sum-output", new Option_FileName());
120  oc.addSynonyme("sum", "sum-output");
121  oc.addDescription("sum-output", "Output", "Save the aggregated and normed emission values of each vehicle in CSV");
122 
123  oc.addOptionSubTopic("Emissions");
124  oc.doRegister("phemlight-path", new Option_FileName(StringVector({ "./PHEMlight/" })));
125  oc.addDescription("phemlight-path", "Emissions", "Determines where to load PHEMlight definitions from.");
126 
128  oc.doRegister("quiet", 'q', new Option_Bool(false));
129  oc.addDescription("quiet", "Report", "Not writing anything.");
130 
131  // run
132  int ret = 0;
133  bool quiet = false;
134  try {
135  // initialise the application system (messaging, xml, options)
136  XMLSubSys::init();
137  OptionsIO::setArgs(argc, argv);
139  if (oc.processMetaOptions(argc < 2)) {
141  return 0;
142  }
143 
144  quiet = oc.getBool("quiet");
145  if (!oc.isSet("timeline-file") && !oc.isSet("netstate-file")) {
146  throw ProcessError("Either a timeline or a netstate / amitran file must be given.");
147  }
148  if (!oc.isSet("output-file") && (oc.isSet("timeline-file") || !oc.isSet("emission-output"))) {
149  throw ProcessError("The output file must be given.");
150  }
151  std::ostream* out = nullptr;
152  if (oc.isSet("output-file")) {
153  out = new std::ofstream(oc.getString("output-file").c_str());
154  }
155  OutputDevice::createDeviceByOption("emission-output", "emission-export", "emission_file.xsd");
156  OutputDevice* xmlOut = nullptr;
157  if (oc.isSet("emission-output")) {
158  xmlOut = &OutputDevice::getDeviceByOption("emission-output");
159  } else if (out == nullptr) {
160  out = &std::cout;
161  }
162  std::ostream* sumOut = nullptr;
163  if (oc.isSet("sum-output")) {
164  sumOut = new std::ofstream(oc.getString("sum-output").c_str());
165  (*sumOut) << "Vehicle,Cycle,Time,Speed,Gradient,Acceleration,FC,FCel,CO2,NOx,CO,HC,PM" << std::endl;
166  }
167 
168  const SUMOEmissionClass defaultClass = PollutantsInterface::getClassByName(oc.getString("emission-class"));
169  const bool computeA = oc.getBool("compute-a") || oc.getBool("compute-a.forward");
170  TrajectoriesHandler handler(computeA, oc.getBool("compute-a.forward"), oc.getBool("compute-a.zero-correction"), defaultClass, oc.getFloat("slope"), out, xmlOut);
171 
172  if (oc.isSet("timeline-file")) {
173  int skip = oc.getBool("skip-first") ? 1 : oc.getInt("timeline-file.skip");
174  const bool inKMH = oc.getBool("kmh");
175  const bool haveSlope = oc.getBool("have-slope");
176  double l = 0;
177  double totalA = 0;
178  double totalS = 0;
179  int time = 0;
180 
181  LineReader lr(oc.getString("timeline-file"));
182  while (lr.hasMore()) {
183  std::string line = lr.readLine();
184  if (skip > 0) {
185  skip--;
186  continue;
187  }
188  StringTokenizer st(StringUtils::prune(line), oc.getString("timeline-file.separator"));
189  if (st.hasNext()) {
190  try {
191  double t = StringUtils::toDouble(st.next());
192  double v = 0;
193  if (st.hasNext()) {
194  v = StringUtils::toDouble(st.next());
195  } else {
196  v = t;
197  t = time;
198  }
199  if (inKMH) {
200  v /= 3.6;
201  }
202  double a = !computeA && st.hasNext() ? StringUtils::toDouble(st.next()) : TrajectoriesHandler::INVALID_VALUE;
203  double s = haveSlope && st.hasNext() ? StringUtils::toDouble(st.next()) : TrajectoriesHandler::INVALID_VALUE;
204  if (handler.writeEmissions(*out, "", defaultClass, t, v, a, s)) {
205  l += v;
206  totalA += a;
207  totalS += s;
208  time++;
209  }
210  } catch (EmptyData&) {
211  throw ProcessError("Missing an entry in line '" + line + "'.");
212  } catch (NumberFormatException&) {
213  throw ProcessError("Not numeric entry in line '" + line + "'.");
214  }
215  }
216  }
217  if (!quiet) {
218  std::cout << "sums" << std::endl
219  << "length:" << l << std::endl;
220  }
221  if (sumOut != nullptr) {
222  (*sumOut) << oc.getString("emission-class") << "," << lr.getFileName() << "," << time << ","
223  << (l / time * 3.6) << "," << (totalS / time) << "," << (totalA / time) << ",";
224  handler.writeNormedSums(*sumOut, "", l);
225  }
226  }
227  if (oc.isSet("netstate-file")) {
228  XMLSubSys::runParser(handler, oc.getString("netstate-file"));
229  }
230  if (!quiet) {
231  handler.writeSums(std::cout, "");
232  }
233  delete sumOut;
234  } catch (InvalidArgument& e) {
236  MsgHandler::getErrorInstance()->inform("Quitting (on error).", false);
237  ret = 1;
238  } catch (ProcessError& e) {
239  if (std::string(e.what()) != std::string("Process Error") && std::string(e.what()) != std::string("")) {
241  }
242  MsgHandler::getErrorInstance()->inform("Quitting (on error).", false);
243  ret = 1;
244 #ifndef _DEBUG
245  } catch (...) {
246  MsgHandler::getErrorInstance()->inform("Quitting (on unknown error).", false);
247  ret = 1;
248 #endif
249  }
251  if (ret == 0 && !quiet) {
252  std::cout << "Success." << std::endl;
253  }
254  return ret;
255 }
256 
257 
258 /****************************************************************************/
std::vector< std::string > StringVector
Definition of a vector of strings.
Definition: Option.h:43
int SUMOEmissionClass
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)
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.
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:79
Static storage of an output device and its base (abstract) implementation.
Definition: OutputDevice.h:60
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:47
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, double t, double &v, double &a, double &s)
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:148
int main(int argc, char **argv)