https://mooseframework.inl.gov
CSV.C
Go to the documentation of this file.
1 //* This file is part of the MOOSE framework
2 //* https://mooseframework.inl.gov
3 //*
4 //* All rights reserved, see COPYRIGHT for full restrictions
5 //* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6 //*
7 //* Licensed under LGPL 2.1, please see LICENSE for details
8 //* https://www.gnu.org/licenses/lgpl-2.1.html
9 
10 // Moose includes
11 #include "CSV.h"
12 #include "FEProblem.h"
13 #include "MooseApp.h"
14 
15 registerMooseObject("MooseApp", CSV);
16 
19 {
20  // Get the parameters from the parent object
22  params.addClassDescription("Output for postprocessors, vector postprocessors, and scalar "
23  "variables using comma seperated values (CSV).");
24 
25  addMultiAppFixedPointIterationEndExecFlag(params, "execute_on");
26  addMultiAppFixedPointIterationEndExecFlag(params, "execute_postprocessors_on");
27  addMultiAppFixedPointIterationEndExecFlag(params, "execute_scalars_on");
28 
29  params.addParam<bool>("sort_columns", false, "Toggle the sorting of columns alphabetically.");
30 
31  // Options for aligning csv output with whitespace padding
32  params.addParam<bool>(
33  "align",
34  false,
35  "Align the outputted csv data by padding the numbers with trailing whitespace");
36  params.addParam<std::string>("delimiter", ",", "Assign the delimiter (default is ','");
37  params.addParam<unsigned int>("precision", 14, "Set the output precision");
38  params.addParam<bool>(
39  "scientific_notation", false, "Output floating point values in scientific notation.");
40  params.addParam<bool>("create_final_symlink",
41  false,
42  "Enable/disable the creation of a _FINAL symlink for vector postprocessor "
43  "data with 'execute_on' includes 'FINAL'.");
44  params.addParam<bool>(
45  "create_latest_symlink",
46  false,
47  "Enable/disable the creation of a _LATEST symlink for vector postprocessor data.");
48 
49  params.addParamNamesToGroup("sort_columns align delimiter precision scientific_notation",
50  "Table formatting");
51  params.addParamNamesToGroup("create_latest_symlink create_final_symlink", "Symbolic links");
52  // Suppress unused parameters
53  params.suppressParameter<unsigned int>("padding");
54 
55  // Done
56  return params;
57 }
58 
59 CSV::CSV(const InputParameters & parameters)
60  : TableOutput(parameters),
61  _align(getParam<bool>("align")),
62  _precision(getParam<unsigned int>("precision")),
63  _scientific_notation(getParam<bool>("scientific_notation")),
64  _delimiter(getParam<std::string>("delimiter")),
65  _write_all_table(false),
66  _write_vector_table(false),
67  _sort_columns(getParam<bool>("sort_columns")),
68  _recovering(_app.isRecovering()),
69  _create_final_symlink(getParam<bool>("create_final_symlink")),
70  _create_latest_symlink(getParam<bool>("create_latest_symlink"))
71 {
72 }
73 
74 void
76 {
77  // Call the base class method
79 
80  // Set the delimiter
82 
83  // Set the precision
86 
87  if (_recovering)
88  _all_data_table.append(true);
89 
90  // Clear any existing symbolic links to LATEST and/or FINAL
91  if (processor_id() == 0)
92  {
93  const std::set<std::string> & out = getVectorPostprocessorOutput();
94  for (const auto & vpp_name : out)
95  {
96  std::string short_name = MooseUtils::shortName(vpp_name);
97  std::string out_latest = _file_base + "_" + short_name + "_LATEST.csv";
98  std::string out_final = _file_base + "_" + short_name + "_FINAL.csv";
99  MooseUtils::clearSymlink(out_latest);
100  MooseUtils::clearSymlink(out_final);
101  }
102  }
103 
104  // See https://github.com/idaholab/moose/issues/25211.
105  mooseAssert(advancedExecuteOn().contains("postprocessors"),
106  "Missing expected postprocessors key");
107  mooseAssert(advancedExecuteOn().contains("scalars"), "Missing expected scalars key");
108  mooseAssert(advancedExecuteOn().contains("reporters"), "Missing expected reporters key");
109  const auto pp_execute_on = advancedExecuteOn().find("postprocessors")->second;
110  const auto scalar_execute_on = advancedExecuteOn().find("scalars")->second;
111  const auto reporter_execute_on = advancedExecuteOn().find("reporters")->second;
112  const auto n_pps = getPostprocessorOutput().size();
113  const auto n_scalars = getScalarOutput().size();
114  const auto n_reporters = getReporterOutput().size();
115  const bool pp_active = n_pps > 0 && !pp_execute_on.isValueSet(EXEC_NONE);
116  const bool scalar_active = n_scalars > 0 && !scalar_execute_on.isValueSet(EXEC_NONE);
117  const bool reporter_active = n_reporters > 0 && !reporter_execute_on.isValueSet(EXEC_NONE);
118  if ((pp_execute_on != scalar_execute_on && pp_active && scalar_active) ||
119  (pp_execute_on != reporter_execute_on && pp_active && reporter_active))
120  mooseError("The parameters 'execute_postprocessors_on', 'execute_scalars_on', and "
121  "'execute_reporters_on' must be the same for CSV output.");
122 }
123 
124 std::string
126 {
127  return _file_base + ".csv";
128 }
129 
130 void
132 {
134  _write_all_table = true;
135 }
136 
137 void
139 {
141  _write_all_table = true;
142 }
143 
144 void
146 {
148  _write_vector_table = true;
149 }
150 
151 void
153 {
155  _write_all_table = true;
156  _write_vector_table = true;
157 }
158 
159 std::string
160 CSV::getVectorPostprocessorFileName(const std::string & vpp_name,
161  bool include_time_step,
162  bool is_distributed)
163 {
164  std::ostringstream file_name;
165  file_name << _file_base;
166 
167  auto short_name = MooseUtils::shortName(vpp_name);
168  if (short_name.size())
169  file_name << '_' << short_name;
170 
171  if (include_time_step)
172  {
173  file_name << '_' << std::setw(_padding) << std::setprecision(0) << std::setfill('0')
174  << std::right << timeStep();
175 
177  {
178  file_name << '_' << std::setw(_padding) << std::setprecision(0) << std::setfill('0')
179  << std::right << _nonlinear_iter;
180  }
182  {
183  file_name << '_' << std::setw(_padding) << std::setprecision(0) << std::setfill('0')
184  << std::right << _linear_iter;
185  }
186  }
187 
188  file_name << ".csv";
189 
190  if (is_distributed)
191  {
192  int digits = MooseUtils::numDigits(n_processors());
193  file_name << "." << std::setw(digits) << std::setfill('0') << processor_id();
194  }
195  return file_name.str();
196 }
197 
198 void
200 {
201  // Call the base class output (populates tables)
203 
204  // Print the table containing all the data to a file
206  {
207  if (_sort_columns)
210  }
211 
212  // Output each VectorPostprocessor's data to a file
214  {
215  // The VPP table will not write the same data twice, so to get the symlinks correct
216  // for EXEC_FINAL (when other flags exist) whenever files are written the names must
217  // be stored. These stored names are then used outside of this loop when the EXEC_FINAL call is
218  // made.
219  _latest_vpp_filenames.clear();
220 
221  for (auto & it : _vector_postprocessor_tables)
222  {
223  const auto & vpp_name = it.first;
224  it.second.setDelimiter(_delimiter);
225  it.second.setPrecision(_precision);
226  it.second.setUseScientificNotation(_scientific_notation);
227  if (_sort_columns)
228  it.second.sortColumns();
229 
230  bool include_time_suffix = true;
231  bool is_distributed = _reporter_data.hasReporterWithMode(vpp_name, REPORTER_MODE_DISTRIBUTED);
232  if (hasVectorPostprocessorByName(vpp_name))
233  {
234  const VectorPostprocessor & vpp_obj =
236  include_time_suffix = !vpp_obj.containsCompleteHistory();
237  }
238 
239  if (is_distributed || processor_id() == 0)
240  {
241  std::string fname =
242  getVectorPostprocessorFileName(vpp_name, include_time_suffix, is_distributed);
243  std::string fprefix = getVectorPostprocessorFilePrefix(vpp_name);
244 
245  _latest_vpp_filenames.emplace_back(fname, fprefix, is_distributed);
246 
247  it.second.printCSV(fname, 1, _align);
248 
250  {
251  std::ostringstream out_latest;
252  out_latest << fprefix << "_LATEST.csv";
253  if (is_distributed)
254  {
255  int digits = MooseUtils::numDigits(n_processors());
256  out_latest << "." << std::setw(digits) << std::setfill('0') << processor_id();
257  }
258  MooseUtils::createSymlink(fname, out_latest.str());
259  }
260 
261  if (_time_data)
262  {
263  _vector_postprocessor_time_tables[vpp_name].setUseScientificNotation(
265  _vector_postprocessor_time_tables[vpp_name].printCSV(fprefix + "_time.csv");
266  }
267  }
268  }
269  }
270 
272  {
273  for (const auto & name_tuple : _latest_vpp_filenames)
274  {
275  std::ostringstream out_final;
276  out_final << std::get<1>(name_tuple) << "_FINAL.csv";
277  if (std::get<2>(name_tuple))
278  {
279  int digits = MooseUtils::numDigits(n_processors());
280  out_final << "." << std::setw(digits) << std::setfill('0') << processor_id();
281  MooseUtils::createSymlink(std::get<0>(name_tuple), out_final.str());
282  }
283  else if (processor_id() == 0)
284  MooseUtils::createSymlink(std::get<0>(name_tuple), out_final.str());
285  }
286  }
287 
288  // Re-set write flags
289  _write_all_table = false;
290  _write_vector_table = false;
291 }
292 
293 std::string
294 CSV::getVectorPostprocessorFilePrefix(const std::string & vpp_name)
295 {
296  return _file_base + "_" + MooseUtils::shortName(vpp_name);
297 }
const std::set< std::string > & getPostprocessorOutput()
The list of postprocessor names that are set for output.
unsigned int _precision
Decimal digits per number in the CSV file.
Definition: CSV.h:88
bool _scientific_notation
Flag for writing floating point values in scientific notation.
Definition: CSV.h:91
void printCSV(const std::string &file_name, int interval=1, bool align=false)
Method for dumping the table to a csv file - opening and closing the file handle is handled...
const ExecFlagType EXEC_NONE
Definition: Moose.C:29
bool _write_all_table
Flag for writing scalar and/or postprocessor data.
Definition: CSV.h:97
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system...
virtual std::string filename() override
The filename for the output file.
Definition: CSV.C:125
std::string _file_base
The base filename from the input paramaters.
Definition: FileOutput.h:89
void setPrecision(unsigned int precision)
By default printCSV prints output to a precision of 14, this allows this to be changed.
virtual void output()
A single call to this function should output all the necessary data for a single timestep.
std::vector< std::tuple< std::string, std::string, bool > > _latest_vpp_filenames
Current list of VPP filenames for creating _LATEST/_FINAL symlinks.
Definition: CSV.h:117
void setUseScientificNotation(bool use_scientific_notation)
Set whether printCSV uses scientific notation for floating point values.
bool empty() const
Returns a boolean value based on whether the FormattedTable contains data or not. ...
static void addMultiAppFixedPointIterationEndExecFlag(InputParameters &params, const std::string &param)
Adds the exec flag MULTIAPP_FIXED_POINT_ITERATION_END to a parameter.
Definition: TableOutput.C:71
virtual void outputReporters() override
Sets the write flag and calls TableOutput::outputVectorPostprocessors()
Definition: CSV.C:152
const std::set< std::string > & getVectorPostprocessorOutput()
The list of VectorPostprocessor names that are set for output.
std::string shortName(const std::string &name)
Definition: MooseUtils.C:612
void suppressParameter(const std::string &name)
This method suppresses an inherited parameter so that it isn&#39;t required or valid in the derived class...
virtual void outputVectorPostprocessors() override
Populates the tables with VectorPostprocessor values.
Definition: TableOutput.C:191
const OutputOnWarehouse & advancedExecuteOn() const
Get the current advanced &#39;execute_on&#39; selections for display.
unsigned int _padding
Number of digits to pad the extensions.
Definition: FileOutput.h:83
const std::set< std::string > & getReporterOutput()
The list of Reporter names that are set for output.
bool _write_vector_table
Flag for writing vector postprocessor data.
Definition: CSV.h:100
processor_id_type n_processors() const
void append(bool append_existing_file)
Sets append mode which means an existing file is not truncated on opening.
virtual void outputPostprocessors() override
Sets the write flag and calls TableOutput::outputPostprocessors()
Definition: CSV.C:138
PetscInt _linear_iter
Current linear iteration returned from PETSc.
Definition: PetscOutput.h:87
bool containsCompleteHistory() const
Return whether or not this VectorPostprocessor contains complete history.
static InputParameters validParams()
Definition: CSV.C:18
const std::set< std::string > & getScalarOutput()
The list of scalar variables names that are set for output.
bool _align
Flag for aligning data in .csv file.
Definition: CSV.h:85
Based class for adding basic filename support to output base class.
Definition: CSV.h:20
ExecFlagType _current_execute_flag
Current execute on flag.
Definition: Output.h:211
bool _recovering
Flag indicating MOOSE is recovering via –recover command-line option.
Definition: CSV.h:106
FEProblemBase * _problem_ptr
Pointer the the FEProblemBase object for output object (use this)
Definition: Output.h:185
virtual void outputReporters() override
Populates the tables with Reporter values.
Definition: TableOutput.C:160
std::string _delimiter
The delimiter used when writing the CSV file.
Definition: CSV.h:94
const VectorPostprocessor & getVectorPostprocessorObjectByName(const std::string &object_name, const THREAD_ID tid=0) const
Return the VPP object given the name.
virtual void outputVectorPostprocessors() override
Sets the write flag and calls TableOutput::outputVectorPostprocessors()
Definition: CSV.C:145
const ReporterMode REPORTER_MODE_DISTRIBUTED
bool contains(std::string_view superstring, std::string_view substring)
const ExecFlagType EXEC_LINEAR
Definition: Moose.C:31
const bool _time_data
Enable/disable VecptorPostprocessor time data file.
Definition: TableOutput.h:113
virtual void outputScalarVariables() override
Sets the write flag and calls TableOutput::outputScalarVariables()
Definition: CSV.C:131
virtual void outputPostprocessors() override
Populates the tables with postprocessor values.
Definition: TableOutput.C:109
const ReporterData & _reporter_data
Storage for Reporter values.
FormattedTable & _all_data_table
Table containing postprocessor values, scalar aux variables, and Real Reporters.
Definition: TableOutput.h:104
void clearSymlink(const std::string &link)
Definition: MooseUtils.C:1073
const ExecFlagType EXEC_NONLINEAR
Definition: Moose.C:33
void createSymlink(const std::string &target, const std::string &link)
Definition: MooseUtils.C:1060
bool hasVectorPostprocessorByName(const VectorPostprocessorName &name, const std::string &vector_name) const
Determine if the VectorPostprocessor data exists by name.
virtual void initialSetup()
Call init() method on setup.
std::string getVectorPostprocessorFilePrefix(const std::string &vpp_name)
Returns the filename without the time/timestep information.
Definition: CSV.C:294
OStreamProxy out
void mooseError(Args &&... args) const
Emits an error prefixed with object name and type and optionally a file path to the top-level block p...
Definition: MooseBase.h:281
const bool _sort_columns
Flag for sorting column names.
Definition: CSV.h:103
Base class for scalar variables and postprocessors output objects.
Definition: TableOutput.h:28
std::string getVectorPostprocessorFileName(const std::string &vpp_name, bool include_time_step, bool is_distributed)
Generates a filename pattern for Vectorpostprocessors filebase + VPP name + time step + "...
Definition: CSV.C:160
void addClassDescription(const std::string &doc_string)
This method adds a description of the class that will be displayed in the input file syntax dump...
registerMooseObject("MooseApp", CSV)
void addParam(const std::string &name, const S &value, const std::string &doc_string)
These methods add an optional parameter and a documentation string to the InputParameters object...
virtual void output() override
Output the table to a *.csv file.
Definition: CSV.C:199
void sortColumns()
Sorts columns alphabetically.
bool hasReporterWithMode(const std::string &obj_name, const ReporterMode &mode) const
Return true if the supplied mode exists in the produced Reporter values.
Definition: ReporterData.C:187
bool _create_latest_symlink
Flag for creating a _LATEST symlink.
Definition: CSV.h:112
bool _create_final_symlink
Flag for creating a _FINAL symlink.
Definition: CSV.h:109
virtual int timeStep()
Get the current time step.
Definition: Output.C:383
CSV(const InputParameters &parameters)
Class constructor.
Definition: CSV.C:59
processor_id_type processor_id() const
Base class for Postprocessors that produce a vector of values.
std::map< std::string, T >::iterator find(const std::string &name)
void setDelimiter(std::string delimiter)
By default printCSV places "," between each entry, this allows this to be changed.
const ExecFlagType EXEC_FINAL
Definition: Moose.C:48
std::map< std::string, FormattedTable > _vector_postprocessor_tables
Formatted tables for outputting vector postprocessor data. One per VectorPostprocessor.
Definition: TableOutput.h:92
void ErrorVector unsigned int
virtual void outputScalarVariables() override
Populates the tables with scalar aux variables.
Definition: TableOutput.C:222
PetscInt _nonlinear_iter
Current non-linear iteration returned from PETSc.
Definition: PetscOutput.h:84
void addParamNamesToGroup(const std::string &space_delim_names, const std::string group_name)
This method takes a space delimited list of parameter names and adds them to the specified group name...
void initialSetup() override
Setup the CSV output If restarting and the append_restart flag is false, then the output data is clea...
Definition: CSV.C:75
std::map< std::string, FormattedTable > & _vector_postprocessor_time_tables
Table for vector postprocessor time data.
Definition: TableOutput.h:95
static InputParameters validParams()
Definition: TableOutput.C:26