CoDiPack  3.0.0
A Code Differentiation Package
SciComp TU Kaiserslautern
Loading...
Searching...
No Matches
primalTextReaderWriter.hpp
1/*
2 * CoDiPack, a Code Differentiation Package
3 *
4 * Copyright (C) 2015-2025 Chair for Scientific Computing (SciComp), University of Kaiserslautern-Landau
5 * Homepage: http://scicomp.rptu.de
6 * Contact: Prof. Nicolas R. Gauger (codi@scicomp.uni-kl.de)
7 *
8 * Lead developers: Max Sagebaum, Johannes Blühdorn (SciComp, University of Kaiserslautern-Landau)
9 *
10 * This file is part of CoDiPack (http://scicomp.rptu.de/software/codi).
11 *
12 * CoDiPack is free software: you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, either version 3 of the
15 * License, or (at your option) any later version.
16 *
17 * CoDiPack is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty
19 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20 *
21 * See the GNU General Public License for more details.
22 * You should have received a copy of the GNU
23 * General Public License along with CoDiPack.
24 * If not, see <http://www.gnu.org/licenses/>.
25 *
26 * For other licensing options please contact us.
27 *
28 * Authors:
29 * - SciComp, University of Kaiserslautern-Landau:
30 * - Max Sagebaum
31 * - Johannes Blühdorn
32 * - Former members:
33 * - Tim Albring
34 */
35#pragma once
36
37#include "../../config.h"
38#include "primalBaseReaderWriter.hpp"
39
41namespace codi {
62 template<typename T_Type>
64 using Type = CODI_DD(T_Type, CODI_DEFAULT_LHS_EXPRESSION);
65 using Tape = typename Type::Tape;
66
67 using Identifier = typename Type::Identifier;
68 using Real = typename Type::Real;
69 using EvalHandle = typename Tape::EvalHandle;
70
71 FILE* fileHandleTxt = nullptr;
72
73 bool printIO;
75
77 PrimalTextTapeWriter(std::string const& name, std::vector<Identifier> const& in,
78 std::vector<Identifier> const& out, bool ifIO, bool ifColumnNames)
79 : PrimalBaseTapeWriter<T_Type>(name, in, out), printIO(ifIO), printColumnNames(ifColumnNames) {}
80
82 void start(Tape& tape) {
83 if (Tape::TapeTypes::IsStaticIndexHandler) {
84 printPrimals(tape);
85 }
86
87 if (printIO) {
88 this->printIoText(tape);
89 }
90
91 this->openFile(fileHandleTxt, this->fileName, "w");
92
93 if (printColumnNames) {
94 fprintf(fileHandleTxt,
95 "| # of LHS Args | LHS Indices | Primal Values | # of Passive Args | # of Active Args | RHS Indices "
96 "| RHS Primal Values | # of Constants | Constants | Statement Key |");
97 }
98 }
99
105 void writeStatement(WriteInfo const& info, Identifier const* lhsIdentifiers, Real const* primalValues,
106 Config::ArgumentSize const& nPassiveValues, Identifier const* const rhsIdentifiers,
107 Real const* const passiveValues, Real const* const constantValues,
108 EvalHandle stmtEvalHandle) {
109 // nOutputArguments
110 fprintf(fileHandleTxt, "\n%hhu [", static_cast<Config::ArgumentSize>(info.numberOfOutputArguments));
111
112 // Lhs Identifiers.
113 for (size_t lhsCount = 0; lhsCount < info.numberOfOutputArguments; lhsCount++) {
114 fprintf(fileHandleTxt, " %d ", lhsIdentifiers[lhsCount]);
115 }
116 fprintf(fileHandleTxt, "] [");
117
118 // Lhs primal values.
119 for (size_t lhsCount = 0; lhsCount < info.numberOfOutputArguments; lhsCount++) {
120 fprintf(fileHandleTxt, " %0.12e ", primalValues[lhsCount]);
121 }
122 fprintf(fileHandleTxt, "] ");
123
124 // nPassiveValues
125 fprintf(fileHandleTxt, "%hhu ", static_cast<Config::ArgumentSize>(nPassiveValues));
126
127 if (nPassiveValues == Config::StatementInputTag) CODI_Unlikely {
128 // Do nothing.
129 } else CODI_Likely {
130 // nActiveValues.
131 fprintf(fileHandleTxt, " %hhu [", static_cast<Config::ArgumentSize>(info.numberOfActiveArguments));
132
133 // Rhs Identifiers.
134 for (size_t rhsCount = 0; rhsCount < info.numberOfActiveArguments; rhsCount++) {
135 fprintf(fileHandleTxt, " %d ", rhsIdentifiers[rhsCount]);
136 }
137 fprintf(fileHandleTxt, "] [");
138
139 // Rhs Passive Primal Values.
140 for (size_t passiveCount = 0; passiveCount < nPassiveValues; passiveCount++) {
141 fprintf(fileHandleTxt, " %0.12e ", passiveValues[passiveCount]);
142 }
143
144 // nConstants.
145 fprintf(fileHandleTxt, "] %hhu [", static_cast<Config::ArgumentSize>(info.numberOfConstantArguments));
146
147 // Rhs Constants.
148 for (size_t constantCount = 0; constantCount < info.numberOfConstantArguments; constantCount++) {
149 fprintf(fileHandleTxt, " %0.12e ", constantValues[constantCount]);
150 }
151
152 fprintf(fileHandleTxt, "]");
153 }
154
155 size_t evalHandleIndex = this->getEvalHandleIndex(stmtEvalHandle, info.stmtExpression);
156
157 // Stmt handle.
158 fprintf(fileHandleTxt, " [ %zu ]", evalHandleIndex);
159 }
160
162 void printPrimals(Tape& tape) {
163 FILE* filePrimalTxt = nullptr;
164 size_t nPrimals = tape.getParameter(TapeParameters::PrimalSize);
165
166 std::string fileNamePrimals = this->modifyFileName("Primals.txt");
167
168 this->openFile(filePrimalTxt, fileNamePrimals, "w");
169
170 // Print out the primals in a sparse vector representation.
171 fprintf(filePrimalTxt, "%zu\n", nPrimals);
172 for (size_t indexCounter = 0; indexCounter < nPrimals; indexCounter++) {
173 Real const curPrimal = tape.getPrimal(indexCounter);
174 if (curPrimal != 0) {
175 fprintf(filePrimalTxt, "%zu ", indexCounter);
176 fprintf(filePrimalTxt, "%0.12e\n", curPrimal);
177 }
178 }
179
180 fclose(filePrimalTxt);
181 }
182
184 void finish() {
186 fclose(fileHandleTxt);
187 }
188 };
189
212 template<typename T_Type>
213 struct PrimalTextTapeReader : public CommonBaseTapeReader<T_Type> {
214 using Type = CODI_DD(T_Type, CODI_DEFAULT_LHS_EXPRESSION);
215 using Tape = typename Type::Tape;
216 using Identifier = typename Type::Identifier;
217 using Real = typename Type::Real;
218
219 std::vector<typename Tape::EvalHandle> evalHandles;
220
221 PrimalTextTapeReader(std::vector<typename Tape::EvalHandle> const& handles)
222 : CommonBaseTapeReader<T_Type>(), evalHandles(handles) {}
223
225 void readFile(std::string const& name) {
226 FILE* fileHandleReadTxt = nullptr;
227
228 Config::ArgumentSize nOutputValues;
229 std::vector<Identifier> lhsIdentifiers(Config::MaxArgumentSize, 0);
230 std::vector<Real> primalValues(Config::MaxArgumentSize, 0.0);
231 Config::ArgumentSize nPassiveValues;
232 Config::ArgumentSize nActiveValues;
233 std::vector<Identifier> rhsIdentifiers(Config::MaxArgumentSize, 0);
234 std::vector<Real> rhsPrimalValues(Config::MaxArgumentSize, 0);
235 Config::ArgumentSize nConstants;
236 std::vector<Real> constants(Config::MaxArgumentSize, 0);
237
238 EvalHandleKey evalHandleKey;
239 this->fileName = name;
240
241 // Restore IO and Primals
242 this->restoreIoText();
243 this->tape.getIndexManager().updateLargestCreatedIndex(this->largestIndex);
244
245 if (Tape::TapeTypes::IsStaticIndexHandler) {
247 }
248 this->openFile(fileHandleReadTxt, this->fileName, "r+");
249
250 // Read and discard column titles
251 fscanf(fileHandleReadTxt,
252 "| # of LHS Args | LHS Indices | Primal Values | # of Passive Args | # of Active Args | RHS Indices "
253 "| RHS Primal Values | # of Constants | Constants | Statement Key |");
254 // Read Statements
255 while (fscanf(fileHandleReadTxt, "\n%hhu [", &nOutputValues) == 1) {
256 // Lhs identifiers
257 for (size_t argumentCount = 0; argumentCount < nOutputValues; argumentCount++) {
258 fscanf(fileHandleReadTxt, " %d ", &lhsIdentifiers[argumentCount]);
259 }
260 fscanf(fileHandleReadTxt, "] [");
261
262 // Lhs primal values
263 for (size_t argumentCount = 0; argumentCount < nOutputValues; argumentCount++) {
264 fscanf(fileHandleReadTxt, " %lf ", &primalValues[argumentCount]);
265 }
266
267 // nPassive values
268 fscanf(fileHandleReadTxt, "] %hhu ", &nPassiveValues);
269
271 // TODO.
272 } else if (nPassiveValues == Config::StatementInputTag) CODI_Unlikely {
273 // Do nothing.
274 } else CODI_Likely {
275 fscanf(fileHandleReadTxt, " %hhu [", &nActiveValues);
276
277 // Rhs identifiers
278 for (size_t argumentCount = 0; argumentCount < nActiveValues; argumentCount++) {
279 fscanf(fileHandleReadTxt, " %d ", &rhsIdentifiers[argumentCount]);
280 }
281 fscanf(fileHandleReadTxt, "] [");
282 // Rhs primals
283 for (size_t argumentCount = 0; argumentCount < nPassiveValues; argumentCount++) {
284 fscanf(fileHandleReadTxt, " %lf ", &rhsPrimalValues[argumentCount]);
285 }
286 fscanf(fileHandleReadTxt, "] %hhu [", &nConstants);
287 // Constants
288 for (size_t argumentCount = 0; argumentCount < nConstants; argumentCount++) {
289 fscanf(fileHandleReadTxt, " %lf ", &constants[argumentCount]);
290 }
291 fscanf(fileHandleReadTxt, "]");
292 }
293 // EvalHandleKey
294 fscanf(fileHandleReadTxt, " [ %zu ]", &evalHandleKey);
295 this->tape.createStatementManual(nOutputValues, lhsIdentifiers.data(), primalValues.data(), nActiveValues,
296 rhsIdentifiers.data(), nPassiveValues, rhsPrimalValues.data(), nConstants,
297 constants.data(), evalHandles[evalHandleKey]);
298 }
299
300 fclose(fileHandleReadTxt);
301 }
302
305 FILE* filePrimalTxt = nullptr;
306
307 size_t nPrimals;
308 Identifier curIdentifier;
309 Real curPrimal;
310
311 this->openFile(filePrimalTxt, this->modifyFileName("Primals.txt"), "r+");
312
313 // Restore the primal vector from a sparse vector.
314 fscanf(filePrimalTxt, "%zu\n", &nPrimals);
315
316 // Resize the primal vector.
317 this->tape.setParameter(TapeParameters::PrimalSize, nPrimals);
318
319 while (fscanf(filePrimalTxt, "%d ", &curIdentifier) == 1) {
320 fscanf(filePrimalTxt, "%lf\n", &curPrimal);
321 this->tape.setPrimal(curIdentifier, curPrimal);
322 }
323 }
324 };
325}
#define CODI_Unlikely
Declare unlikely evaluation of an execution path.
Definition config.h:408
#define CODI_Likely
Declare likely evaluation of an execution path.
Definition config.h:406
#define CODI_DD(Type, Default)
Abbreviation for CODI_DECLARE_DEFAULT.
Definition macros.hpp:96
size_t constexpr StatementLowLevelFunctionTag
Statement tag for low level functions.
Definition config.h:126
size_t constexpr MaxArgumentSize
Maximum number of arguments in a statement.
Definition config.h:120
uint8_t ArgumentSize
Type for the number of arguments in statements.
Definition config.h:117
size_t constexpr StatementInputTag
Tag for statements that are inputs. Used in linear index management context.
Definition config.h:123
CoDiPack - Code Differentiation Package.
Definition codi.hpp:94
@ PrimalSize
[A: RW] Number of primal vector entries in primal value tapes.
Definition tapeParameters.hpp:63
size_t EvalHandleKey
Key for the evalHandle lookup.
Definition tapeReaderWriterInterface.hpp:44
void restoreIoText()
Constructor.
Definition commonReaderWriterBase.hpp:161
Tape tape
The newly resorted tape.
Definition commonReaderWriterBase.hpp:153
Identifier largestIndex
The largest index on the stored tape.
Definition commonReaderWriterBase.hpp:155
void printIoText(Tape &tape)
Generate the IO file in a text format.
Definition commonReaderWriterBase.hpp:100
std::string fileName
The base file name provided by the user.
Definition commonReaderWriterBase.hpp:51
std::string modifyFileName(std::string const &suffix)
Remove the file extension and replace it with a new suffix.
Definition commonReaderWriterBase.hpp:59
void openFile(FILE *&fileHandle, std::string const &name, std::string const &mode)
Definition commonReaderWriterBase.hpp:67
void generateHandleCreatorFile()
This method is used to generate an .hpp file which creates the necessary EvalHandles in the reading p...
Definition primalBaseReaderWriter.hpp:78
PrimalBaseTapeWriter(std::string const &name, std::vector< Identifier > const &in, std::vector< Identifier > const &out)
Constructor.
Definition primalBaseReaderWriter.hpp:68
size_t getEvalHandleIndex(EvalHandle const evalHandle, std::string const &evalStatement)
Get the index for an evalHandle.
Definition primalBaseReaderWriter.hpp:118
typename Type::Identifier Identifier
See TapeReaderInterface.
Definition primalTextReaderWriter.hpp:216
PrimalTextTapeReader(std::vector< typename Tape::EvalHandle > const &handles)
Constructor.
Definition primalTextReaderWriter.hpp:221
typename Type::Real Real
See TapeReaderInterface.
Definition primalTextReaderWriter.hpp:217
void restorePrimals()
Read and record the primal values from the sparse primal vector stored in "filename"Primals....
Definition primalTextReaderWriter.hpp:304
void readFile(std::string const &name)
This method uses the the fileName to reproduce a valid tape.
Definition primalTextReaderWriter.hpp:225
std::vector< typename Tape::EvalHandle > evalHandles
Contains the unique evalHandles.
Definition primalTextReaderWriter.hpp:219
typename Type::Tape Tape
See TapeReaderInterface.
Definition primalTextReaderWriter.hpp:215
T_Type Type
See TapeWriterInterface.
Definition primalTextReaderWriter.hpp:214
bool printColumnNames
Flag to enable column names.
Definition primalTextReaderWriter.hpp:74
PrimalTextTapeWriter(std::string const &name, std::vector< Identifier > const &in, std::vector< Identifier > const &out, bool ifIO, bool ifColumnNames)
Constructor.
Definition primalTextReaderWriter.hpp:77
typename Type::Tape Tape
See TapeWriterInterface.
Definition primalTextReaderWriter.hpp:65
bool printIO
Flag to enable the writing of the IO file.
Definition primalTextReaderWriter.hpp:73
FILE * fileHandleTxt
File handle.
Definition primalTextReaderWriter.hpp:71
T_Type Type
See TapeWriterInterface.
Definition primalTextReaderWriter.hpp:64
void finish()
After all the statements have been written, the finish method finalizes the writing process.
Definition primalTextReaderWriter.hpp:184
void writeStatement(WriteInfo const &info, Identifier const *lhsIdentifiers, Real const *primalValues, Config::ArgumentSize const &nPassiveValues, Identifier const *const rhsIdentifiers, Real const *const passiveValues, Real const *const constantValues, EvalHandle stmtEvalHandle)
Called for each statement. The method writes the current statement to the file. This overload is used...
Definition primalTextReaderWriter.hpp:105
typename Tape::EvalHandle EvalHandle
See TapeWriterInterface.
Definition primalTextReaderWriter.hpp:69
typename Type::Identifier Identifier
See TapeWriterInterface.
Definition primalTextReaderWriter.hpp:67
void printPrimals(Tape &tape)
Print the primal vector in sparse vector representation.
Definition primalTextReaderWriter.hpp:162
void start(Tape &tape)
Destructor.
Definition primalTextReaderWriter.hpp:82
typename Type::Real Real
See TapeWriterInterface.
Definition primalTextReaderWriter.hpp:68
This class is used during the writing process of a primal value tape. The WriteInfo is returned by St...
Definition tapeReaderWriterInterface.hpp:69
size_t numberOfActiveArguments
Number of active arguments.
Definition tapeReaderWriterInterface.hpp:71
std::string stmtExpression
Used to generate a .hpp file for reading back a primal value tape.
Definition tapeReaderWriterInterface.hpp:73
size_t numberOfOutputArguments
Number of output arguments.
Definition tapeReaderWriterInterface.hpp:70
size_t numberOfConstantArguments
Number of constant arguments.
Definition tapeReaderWriterInterface.hpp:72