• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

cyclus / cyclus / 16384544356

19 Jul 2025 03:38AM UTC coverage: 36.53% (-4.7%) from 41.231%
16384544356

push

github

web-flow
Merge pull request #1881 from dean-krueger/clang-format

Clang Format Cyclus src

1517 of 26176 new or added lines in 94 files covered. (5.8%)

309 existing lines in 19 files now uncovered.

51830 of 141883 relevant lines covered (36.53%)

14764.59 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.63
/src/context.h
1
#ifndef CYCLUS_SRC_CONTEXT_H_
2
#define CYCLUS_SRC_CONTEXT_H_
3

4
#include <map>
5
#include <set>
6
#include <string>
7
#include <stdint.h>
8

9
#ifndef CYCPP
10
// The cyclus preprocessor cannot handle this file since there are two
11
// unmatch open braces '{' inside of strings that don't have cooresponding
12
// closed braces '}'
13
#include <boost/uuid/uuid_generators.hpp>
14
#endif
15

16
#include "composition.h"
17
#include "agent.h"
18
#include "greedy_solver.h"
19
#include "pyhooks.h"
20
#include "recorder.h"
21
#include "package.h"
22

23
// Defined as 4 seconds longer than a Gaussian year (to make division by 12
24
// a round number)
25
const uint64_t cyclusYear = 31558200;
26

27
const uint64_t kDefaultTimeStepDur = cyclusYear / 12;
28

29
const uint64_t kDefaultSeed = 20160212;
30

31
const uint64_t kDefaultStride = 10000;
32

33
class SimInitTest;
34

35
namespace cyclus {
36

37
class Datum;
38
class ExchangeSolver;
39
class Recorder;
40
class Trader;
41
class Timer;
42
class TimeListener;
43
class SimInit;
44
class DynamicModule;
45
class RandomNumberGenerator;
46

47
/// Container for a static simulation-global parameters that both describe
48
/// the simulation and affect its behavior.
49
class SimInfo {
50
 public:
51
  /// @brief constructs a SimInfo instance with default variables
52
  /// @return a SimInfo instance
53
  SimInfo();
54

55
  /// @brief constructs a SimInfo instance using some default variables
56
  /// @param dur simulation duration in number of timesteps
57
  /// @param y0 start year for the simulation
58
  /// @param m0 start month for the simulation
59
  /// @param handle is this simulation's unique simulation handle
60
  /// @return a SimInfo instance
61
  SimInfo(int dur, int y0 = 2010, int m0 = 1, std::string handle = "");
62

63
  /// @brief constructs a SimInfo instance using no default variables
64
  /// @param dur simulation duration in number of timesteps
65
  /// @param y0 start year for the simulation
66
  /// @param m0 start month for the simulation
67
  /// @param handle is this simulation's unique simulation handle
68
  /// @param d the decay data member, "never" for no decay. "manual" otherwise
69
  /// @return a SimInfo instance
70
  SimInfo(int dur, int y0, int m0, std::string handle, std::string d);
71

72
  /// @brief constructs a SimInfo instance
73
  /// @param dur simulation duration in number of timesteps
74
  /// @param parent_sim the uuid of the parent simulation
75
  /// @param branch_time
76
  /// @param parent_type a string indicating the type of the parent simulation
77
  /// @param handle is this simulation's unique simulation handle
78
  /// @return a SimInfo instance
79
  SimInfo(int dur, boost::uuids::uuid parent_sim, int branch_time,
80
          std::string parent_type, std::string handle = "");
81

82
  /// user-defined label associated with a particular simulation
83
  std::string handle;
84

85
  /// "manual" if use of the decay function is allowed, "never" otherwise
86
  std::string decay;
87

88
  /// length of the simulation in timesteps (months)
89
  int duration;
90

91
  /// start year for the simulation (e.g. 1973);
92
  int y0;
93

94
  /// start month for the simulation: Jan = 1, ..., Dec = 12
95
  int m0;
96

97
  /// id for the parent simulation if any
98
  boost::uuids::uuid parent_sim;
99

100
  /// One of "init", "branch", "restart" indicating the relationship of this
101
  /// simulation to its parent simulation.
102
  std::string parent_type;
103

104
  /// timestep at which simulation branching occurs if any
105
  int branch_time;
106

107
  /// Duration in seconds of a single time step in the simulation.
108
  uint64_t dt;
109

110
  /// Epsilon in the simulation.
111
  double eps;
112

113
  /// Epsilon for resources in the simulation.
114
  double eps_rsrc;
115

116
  /// True if per-agent inventories should be explicitly queried/recorded
117
  /// every time step in a table (i.e. agent ID, Time, Nuclide, Quantity).
118
  bool explicit_inventory;
119

120
  /// True if per-agent inventories should be explicitly queried/recorded
121
  /// every time step in a table (i.e. agent ID, Time, Quantity,
122
  /// Composition-object and/or reference).
123
  bool explicit_inventory_compact;
124

125
  /// Seed for random number generator
126
  uint64_t seed;
127

128
  /// Stride length. Currently unused, but available for future development
129
  /// that may wish to initiate multiple random number generators from the
130
  /// same seed, skipping forward in the sequence by the stride length times
131
  /// some parameter, such as the agent_id.
132
  uint64_t stride;
133
};
134

135
/// A simulation context provides access to necessary simulation-global
136
/// functions and state. All code that writes to the output database, needs to
137
/// know simulation time, creates/builds facilities, and/or uses loaded
138
/// composition recipes will need a context pointer. In general, all global
139
/// state should be accessed through a simulation context.
140
///
141
/// @warning the context takes ownership of and manages the lifetime/destruction
142
/// of all agents constructed with it (including Cloned agents). Agents should
143
/// generally NEVER be allocated on the stack.
144
/// @warning the context takes ownership of the solver and will manage its
145
/// destruction.
146
class Context {
147
 public:
148
  friend class ::SimInitTest;
149
  friend class SimInit;
150
  friend class Agent;
151
  friend class Timer;
152

153
  /// Creates a new context working with the specified timer and datum manager.
154
  /// The timer does not have to be initialized (yet).
155
  Context(Timer* ti, Recorder* rec);
156

157
  /// Clean up resources including destructing the solver and all agents the
158
  /// context is aware of.
159
  ~Context();
160

161
  /// See Recorder::sim_id documentation.
162
  boost::uuids::uuid sim_id();
163

164
  /// Adds a prototype to a simulation-wide accessible list, a prototype **can
165
  /// not** be added more than once.
166
  /// @param name the prototype name
167
  /// @param m a pointer to the agent prototype
168
  /// @param overwrite, allow overwrites to the prototype listing, default:
169
  /// false
170
  /// @throws if overwrite is false and a prototype name has already been added
171
  /// @{
172
  void AddPrototype(std::string name, Agent* m);
173
  void AddPrototype(std::string name, Agent* m, bool overwrite);
174
  /// @}
175

176
  /// Registers an agent as a participant in resource exchanges. Agents should
177
  /// register from their Deploy method.
178
  inline void RegisterTrader(Trader* e) { traders_.insert(e); }
179

180
  /// Unregisters an agent as a participant in resource exchanges.
181
  inline void UnregisterTrader(Trader* e) { traders_.erase(e); }
182

183
  /// @return the current set of traders registered for resource exchange.
184
  inline const std::set<Trader*>& traders() const { return traders_; }
185

186
  /// Create a new agent by cloning the named prototype. The returned agent is
187
  /// not initialized as a simulation participant.
188
  ///
189
  /// @warning this method should generally NOT be used by agents.
190
  template <class T> T* CreateAgent(std::string proto_name) {
17,435✔
191
    if (protos_.count(proto_name) == 0) {
192
      throw KeyError("Invalid prototype name " + proto_name);
×
193
    }
194

195
    Agent* m = protos_[proto_name];
17,435✔
196
    if (m == NULL) {
17,435✔
NEW
197
      throw KeyError("Null prototype for " + proto_name);
×
198
    }
199
    T* casted(NULL);
200
    Agent* clone = m->Clone();
17,435✔
201
    if (clone == NULL) {
17,435✔
NEW
202
      throw StateError("Clone operation failed for " + proto_name);
×
203
    }
204
    casted = dynamic_cast<T*>(clone);
11✔
205
    if (casted == NULL) {
11✔
206
      PyDelAgent(clone->id());
1✔
207
      DelAgent(clone);
1✔
208
      throw CastError("Invalid cast for prototype " + proto_name);
2✔
209
    }
210
    return casted;
17,434✔
211
  }
212

213
  /// Destructs and cleans up m (and it's children recursively).
214
  ///
215
  /// @warning this method should generally NOT be used by agents.
216
  void DelAgent(Agent* m);
217

218
  /// Schedules the named prototype to be built for the specified parent at
219
  /// timestep t. The default t=-1 results in the build being scheduled for the
220
  /// next build phase (i.e. the start of the next timestep).
221
  void SchedBuild(Agent* parent, std::string proto_name, int t = -1);
222

223
  /// Schedules the given Agent to be decommissioned at the specified timestep
224
  /// t. The default t=-1 results in the decommission being scheduled for the
225
  /// next decommission phase (i.e. the end of the current timestep).
226
  void SchedDecom(Agent* m, int time = -1);
227

228
  /// Adds a composition recipe to a simulation-wide accessible list.
229
  /// Agents should NOT add their own recipes.
230
  void AddRecipe(std::string name, Composition::Ptr c);
231

232
  /// Retrieve a registered recipe.  This is intended for retrieving
233
  /// compositions loaded from an input file(s) at the start of a
234
  /// simulation and NOT for communicating compositions between facilities
235
  /// during the simulation.
236
  Composition::Ptr GetRecipe(std::string name);
237

238
  /// Registers an agent to receive tick/tock notifications every timestep.
239
  /// Agents should register from their Deploy method.
240
  void RegisterTimeListener(TimeListener* tl);
241

242
  /// Removes an agent from receiving tick/tock notifications.
243
  /// Agents should unregister from their Decommission method.
244
  void UnregisterTimeListener(TimeListener* tl);
245

246
  /// Initializes the simulation time parameters. Should only be called once -
247
  /// NOT idempotent.
248
  void InitSim(SimInfo si);
249

250
  /// Returns the current simulation timestep.
251
  virtual int time();
252

253
  /// Adds a package type to a simulation-wide accessible list.
254
  /// Agents should NOT add their own packages.
255
  void AddPackage(std::string name, double fill_min = 0,
256
                  double fill_max = std::numeric_limits<double>::max(),
257
                  std::string strategy = "first");
258

259
  /// Records package information. Should be used first on unpackaged, then
260
  /// to record user-declared packages
261
  void RecordPackage(Package::Ptr);
262

263
  /// Retrieve a registered package.
264
  Package::Ptr GetPackage(std::string name);
265

266
  /// Adds a transport unit type to a simulation-wide accessible list.
267
  /// Agents should NOT add their own transport units.
268
  void AddTransportUnit(std::string name, int fill_min = 0,
269
                        int fill_max = std::numeric_limits<int>::max(),
270
                        std::string strategy = "first");
271

272
  /// Records transport unit information. Should be used first on unrestricted,
273
  /// then to record user-declared transport units
274
  void RecordTransportUnit(TransportUnit::Ptr);
275

276
  /// Retrieve a registered transport unit.
277
  TransportUnit::Ptr GetTransportUnit(std::string name);
278

279
  int random();
280

281
  /// Generates a random number on the range [0,1)]
282
  double random_01();
283

284
  /// Returns a random number from a uniform integer distribution.
285
  int random_uniform_int(int low, int high);
286

287
  /// Returns a random number from a uniform real distribution.
288
  double random_uniform_real(double low, double high);
289

290
  /// Returns a random number from a normal distribution.
291
  double random_normal_real(double mean, double std_dev, double low = 0,
292
                            double high = std::numeric_limits<double>::max());
293

294
  /// Returns a random number from a lognormal distribution.
295
  int random_normal_int(double mean, double std_dev, int low = 0,
296
                        int high = std::numeric_limits<int>::max());
297

298
  /// Returns the duration of a single time step in seconds.
299
  inline uint64_t dt() { return si_.dt; };
272✔
300

301
  /// Returns the seed for the random number generator.
302
  inline uint64_t seed() { return si_.seed; };
303

304
  /// Returns the stride for the random number generator.
305
  inline uint64_t stride() { return si_.stride; };
306

307
  /// Return static simulation info.
308
  inline SimInfo sim_info() const { return si_; }
1,782✔
309

310
  /// See Recorder::NewDatum documentation.
311
  Datum* NewDatum(std::string title);
312

313
  /// Schedules a snapshot of simulation state to output database to occur at
314
  /// the beginning of the next timestep.
315
  void Snapshot();
316

317
  /// Schedules the simulation to be terminated at the end of this timestep.
318
  void KillSim();
319

320
  /// @return the next transaction id
321
  inline int NextTransactionID() { return trans_id_++; }
15,703✔
322

323
  /// Returns the exchange solver associated with this context
324
  ExchangeSolver* solver() {
5,049✔
325
    if (solver_ == NULL) {
5,049✔
326
      solver_ = new GreedySolver(false, NULL);
20✔
327
    }
328
    return solver_;
5,049✔
329
  }
330

331
  /// sets the solver associated with this context
332
  void solver(ExchangeSolver* solver) {
333
    solver_ = solver;
242✔
334
    solver_->sim_ctx(this);
335
  }
336

337
  /// @return the number of agents of a given prototype currently in the
338
  /// simulation
339
  inline int n_prototypes(std::string type) { return n_prototypes_[type]; }
17,043✔
340

341
  /// @return the number of agents of a given implementation currently in the
342
  /// simulation
343
  inline int n_specs(std::string impl) { return n_specs_[impl]; }
3✔
344

345
 private:
346
  /// Registers an agent as a participant in the simulation.
347
  inline void RegisterAgent(Agent* a) {
18,448✔
348
    n_prototypes_[a->prototype()]++;
18,448✔
349
    n_specs_[a->spec()]++;
18,448✔
350
  }
18,448✔
351

352
  /// Unregisters an agent as a participant in the simulation.
353
  inline void UnregisterAgent(Agent* a) {
11,668✔
354
    n_prototypes_[a->prototype()]--;
11,668✔
355
    n_specs_[a->spec()]--;
11,668✔
356
  }
11,668✔
357

358
  /// contains archetype specs of all agents for which version have already
359
  /// been recorded in the db
360
  std::set<std::string> rec_ver_;
361

362
  std::map<std::string, Agent*> protos_;
363
  std::map<std::string, Composition::Ptr> recipes_;
364
  std::map<std::string, Package::Ptr> packages_;
365
  std::map<std::string, TransportUnit::Ptr> transport_units_;
366
  std::set<Agent*> agent_list_;
367
  std::set<Trader*> traders_;
368
  std::map<std::string, int> n_prototypes_;
369
  std::map<std::string, int> n_specs_;
370

371
  SimInfo si_;
372
  Timer* ti_;
373
  ExchangeSolver* solver_;
374
  Recorder* rec_;
375
  int trans_id_;
376
  RandomNumberGenerator* rng_;
377
};
378

379
}  // namespace cyclus
380

381
#endif  // CYCLUS_SRC_CONTEXT_H_
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc