RcsPySim
A robot control and simulation library
DataLogger.cpp
Go to the documentation of this file.
1 /*******************************************************************************
2  Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
3  Technical University of Darmstadt.
4  All rights reserved.
5 
6  Redistribution and use in source and binary forms, with or without
7  modification, are permitted provided that the following conditions are met:
8  1. Redistributions of source code must retain the above copyright
9  notice, this list of conditions and the following disclaimer.
10  2. Redistributions in binary form must reproduce the above copyright
11  notice, this list of conditions and the following disclaimer in the
12  documentation and/or other materials provided with the distribution.
13  3. Neither the name of Fabio Muratore, Honda Research Institute Europe GmbH,
14  or Technical University of Darmstadt, nor the names of its contributors may
15  be used to endorse or promote products derived from this software without
16  specific prior written permission.
17 
18  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  DISCLAIMED. IN NO EVENT SHALL FABIO MURATORE, HONDA RESEARCH INSTITUTE EUROPE GMBH,
22  OR TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
25  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
26  IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  POSSIBILITY OF SUCH DAMAGE.
29 *******************************************************************************/
30 
31 #include "DataLogger.h"
32 
33 #include <Rcs_macros.h>
34 #include <Rcs_VecNd.h>
35 
36 #include <ctime>
37 #include <sstream>
38 #include <iostream>
39 #include <iomanip>
40 
41 namespace Rcs
42 {
43 
45  fileCounter(0),
46  running(false),
47  buffer(nullptr),
48  currentStep(0)
49 {
50  // Nothing else to do
51 }
52 
54 {
55  // Make sure we stopped
56  stop();
57 }
58 
59 void DataLogger::start(const BoxSpace* observationSpace, const BoxSpace* actionSpace, unsigned int maxStepCount)
60 {
61  // Guard against concurrency
62  std::unique_lock<std::recursive_mutex> lock(mutex);
63  if (running) {
64  RLOG(1, "Already running!");
65  return;
66  }
67  running = true;
68  // Determine filename
69  std::string fname;
70  std::time_t t = std::time(nullptr); // get time now
71  std::tm* now = std::localtime(&t);
72  std::ostringstream os;
73  os << (now->tm_year + 1900) << '-' << std::setfill('0') << std::setw(2) << (now->tm_mon + 1) << '-' <<
74  std::setfill('0') << std::setw(2) << now->tm_mday << '_' << (fileCounter++) << ".csv";
75  fname = os.str();
76 
77  // Open output file
78  output.open(fname);
79 
80  // Write header (column names)
81  output << R"("steps)";
82  for (auto& name : observationSpace->getNames()) {
83  output << "\",\"" << name;
84  }
85  for (auto& name : actionSpace->getNames()) {
86  output << "\",\"" << name;
87  }
88  output << "\"" << std::endl;
89 
90  // Allocate buffer. Use maxStepCount + 1 to also count the final observation
91  buffer = MatNd_create(maxStepCount + 1, observationSpace->getNames().size() + actionSpace->getNames().size());
92  currentStep = 0;
93 
94  std::cout << "Logging started!" << std::endl;;
95 }
96 
98 {
99  // Guard against concurrency
100  std::unique_lock<std::recursive_mutex> lock(mutex);
101  if (!running) {
102  return;
103  }
104  running = false;
105 
106  // Write buffer contents to csv
107  for (unsigned int row = 0; row <= currentStep; ++row) { // <= to also write the last row
108  // Write step number
109  output << row;
110 
111  // Write elements
112  for (unsigned int col = 0; col < buffer->n; ++col) {
113  output << "," << MatNd_get2(buffer, row, col);
114  }
115  output << std::endl;
116  }
117 
118  // Close file
119  output.flush();
120  output.close();
121  output.clear();
122 
123  // Delete buffer
124  MatNd_destroy(buffer);
125 
126  std::cout << "Logging stopped!" << std::endl;;
127 }
128 
129 void DataLogger::record(const MatNd* observation, const MatNd* action)
130 {
131  // Try to obtain lock. If it's blocked, it's blocked by start or stop, so we don't want to lock anyways.
132  std::unique_lock<std::recursive_mutex> lock(mutex, std::try_to_lock);
133  if (!lock.owns_lock() || !running) {
134  return;
135  }
136 
137  // Check if the logging is over. The very last step is index by m
138  if (currentStep >= buffer->m - 1) {
139  // Add final observations and dummy actions (to later filter them out) to the buffer
140  double* lineBuffer = MatNd_getRowPtr(buffer, currentStep);
141  VecNd_copy(&lineBuffer[0], observation->ele, observation->m);
142  double nanAction[action->m];
143  for (unsigned int i = 0; i < action->m; i++) {
144  nanAction[i] = NAN;
145  }
146  VecNd_copy(&lineBuffer[observation->m], nanAction, action->m);
147 
148  stop();
149  return;
150  }
151 
152  // Add a line to the buffer
153  double* lineBuffer = MatNd_getRowPtr(buffer, currentStep++);
154  VecNd_copy(&lineBuffer[0], observation->ele, observation->m);
155  VecNd_copy(&lineBuffer[observation->m], action->ele, action->m);
156 }
157 
158 } /* namespace Rcs */
unsigned int currentStep
Step counter in current logging run.
Definition: DataLogger.h:101
std::recursive_mutex mutex
Definition: DataLogger.h:89
void start(const BoxSpace *observationSpace, const BoxSpace *actionSpace, unsigned int maxStepCount)
Definition: DataLogger.cpp:59
MatNd * buffer
Buffer to avoid writing on realtime main thread.
Definition: DataLogger.h:98
unsigned int fileCounter
Automatic log file naming.
Definition: DataLogger.h:92
virtual ~DataLogger()
Definition: DataLogger.cpp:53
std::ofstream output
Current output stream.
Definition: DataLogger.h:104
volatile bool running
Flag if the logger is currently recording.
Definition: DataLogger.h:95
void record(const MatNd *observation, const MatNd *action)
Definition: DataLogger.cpp:129
const std::vector< std::string > & getNames() const
Definition: BoxSpace.h:147