FireSTARR
Loading...
Searching...
No Matches
Model.h
1/* Copyright (c) Queen's Printer for Ontario, 2020. */
2/* Copyright (c) His Majesty the King in Right of Canada as represented by the Minister of Natural Resources, 2021-2025. */
3
4/* SPDX-License-Identifier: AGPL-3.0-or-later */
5
6#pragma once
7#include <condition_variable>
8#include <cstdio>
9#include <future>
10#include <map>
11#include <memory>
12#include <mutex>
13#include <string>
14#include <thread>
15#include <vector>
16#include "Environment.h"
17#include "Iteration.h"
18#include "FireWeather.h"
19namespace fs
20{
21namespace topo
22{
23class StartPoint;
24}
25namespace sim
26{
27class Event;
28class Scenario;
33{
34public:
39 explicit Semaphore(const int n)
40 : used_{0},
41 limit_{n}
42 {
43 }
44 Semaphore(const Semaphore& rhs) = delete;
45 Semaphore(Semaphore&& rhs) = delete;
46 Semaphore& operator=(const Semaphore& rhs) = delete;
47 Semaphore& operator=(Semaphore&& rhs) = delete;
48 void set_limit(size_t limit)
49 {
50 logging::debug("Changing Semaphore limit from %d to %d", limit_, limit);
51 // NOTE: won't drop threads if set lower but won't give out more until below limit
52 limit_ = limit;
53 }
54 size_t limit()
55 {
56 return limit_;
57 }
61 void notify()
62 {
63 std::unique_lock<std::mutex> l(mutex_);
64 --used_;
65 cv_.notify_one();
66 }
70 void wait()
71 {
72 std::unique_lock<std::mutex> l(mutex_);
73 cv_.wait(l, [this] { return used_ <= limit_; });
74 ++used_;
75 }
76private:
80 std::mutex mutex_;
84 std::condition_variable cv_;
88 int used_;
92 int limit_;
93};
98{
103public:
109 : s_{ss}
110 {
111 s_.wait();
112 }
113 CriticalSection(const CriticalSection& rhs) = delete;
114 CriticalSection(CriticalSection&& rhs) = delete;
115 CriticalSection& operator=(const CriticalSection& rhs) = delete;
116 CriticalSection& operator=(CriticalSection&& rhs) = delete;
117 ~CriticalSection() noexcept
118 {
119 try
120 {
121 s_.notify();
122 }
123 catch (const std::exception& ex)
124 {
125 logging::fatal(ex);
126 std::terminate();
127 }
128 }
129};
133class Model
134{
135public:
148 [[nodiscard]] static int runScenarios(const string dir_out,
149 const char* weather_input,
151 const char* raster_root,
152 const topo::StartPoint& start_point,
153 const tm& start_time,
154 const string& perimeter,
155 size_t size);
162 [[nodiscard]]
163#ifdef NDEBUG
164 CONSTEXPR
165#endif
167 cell(const Idx row, const Idx column) const
168 {
169 return env_->cell(row, column);
170 }
176 template <class P>
177 [[nodiscard]] constexpr topo::Cell cell(const Position<P>& position) const
178 {
179 return env_->cell(position);
180 }
186 // [[nodiscard]] constexpr topo::Cell cell(const HashSize hash_size) const
187 // {
188 // return env_->cell(hash_size);
189 // }
194 [[nodiscard]] constexpr Idx rows() const
195 {
196 return env_->rows();
197 }
202 [[nodiscard]] constexpr Idx columns() const
203 {
204 return env_->columns();
205 }
210 [[nodiscard]] constexpr MathSize cellSize() const
211 {
212 return env_->cellSize();
213 }
218 [[nodiscard]] constexpr const topo::Environment& environment() const
219 {
220 return *env_;
221 }
226 [[nodiscard]] constexpr Clock::time_point runningSince() const
227 {
228 return running_since_;
229 }
234 [[nodiscard]] constexpr Clock::duration timeLimit() const
235 {
236 return time_limit_;
237 }
242 [[nodiscard]] constexpr Clock::duration interimTimeLimit() const
243 {
245 }
250 [[nodiscard]] bool shouldStop() const noexcept;
255 [[nodiscard]] bool isOutOfTime() const noexcept;
260 [[nodiscard]] bool isOverSimulationCountLimit() const noexcept;
265 [[nodiscard]] int year() const noexcept
266 {
267 return year_;
268 }
273 [[nodiscard]] int ignitionScenarios() const noexcept
274 {
275 return starts_.size();
276 }
281 [[nodiscard]] int scenarioCount() const noexcept
282 {
283 return wx_.size() * ignitionScenarios();
284 }
290 [[nodiscard]] constexpr int nd(const DurationSize time) const
291 {
292 return nd_.at(static_cast<Day>(time));
293 }
294 [[nodiscard]] const char* outputDirectory() const
295 {
296 return dir_out_.c_str();
297 }
302 [[nodiscard]] std::chrono::seconds runTime() const;
307 [[nodiscard]] std::chrono::seconds timeSinceLastSave() const;
318 [[nodiscard]] ProbabilityMap* makeProbabilityMap(DurationSize time,
319 DurationSize start_time) const;
320 ~Model() = default;
326 Model(const string dir_out,
327 const topo::StartPoint& start_point,
328 topo::Environment* env);
329 Model(Model&& rhs) noexcept = delete;
330 Model(const Model& rhs) = delete;
331 Model& operator=(Model&& rhs) noexcept = delete;
332 Model& operator=(const Model& rhs) = delete;
337 void setWeather(const wx::FwiWeather& weather, const Day start_day);
345 const MathSize latitude,
346 const string& filename);
354 void makeStarts(Coordinates coordinates,
355 const topo::Point& point,
356 string perim,
357 size_t size);
366 [[nodiscard]] Iteration readScenarios(const topo::StartPoint& start_point,
367 DurationSize start,
368 Day start_day,
369 Day last_date);
374 [[nodiscard]] BurnedData* getBurnedVector() const noexcept;
379 void releaseBurnedVector(BurnedData* has_burned) const noexcept;
387 const wx::FwiWeather* yesterday() const noexcept
388 {
389 return &yesterday_;
390 }
391private:
392 const string dir_out_;
400 void add_statistics(vector<MathSize>* all_sizes,
401 vector<MathSize>* means,
402 vector<MathSize>* pct,
403 const util::SafeVector& sizes);
407 mutable mutex vector_mutex_;
415 mutable vector<unique_ptr<BurnedData>> vectors_{};
423 map<DurationSize, ProbabilityMap*> runIterations(const topo::StartPoint& start_point,
424 DurationSize start,
425 Day start_day);
429 DurationSize saveProbabilities(map<DurationSize, ProbabilityMap*>& probabilities, const Day start_day, const bool is_interim);
434 void findStarts(Location location);
438 array<int, MAX_DAYS> nd_{};
442 map<size_t, shared_ptr<wx::FireWeather>> wx_{};
446 map<size_t, shared_ptr<wx::FireWeather>> wx_daily_{};
450 vector<shared_ptr<topo::Cell>> starts_{};
454 Clock::time_point running_since_;
458 Clock::duration time_limit_;
462 Clock::time_point no_interim_save_since_;
466 Clock::duration interim_save_interval_;
467 // /**
468 // * @brief Initial intensity map based off perimeter
469 // */
470 // shared_ptr<IntensityMap> initial_intensity_ = nullptr;
474 shared_ptr<topo::Perimeter> perimeter_ = nullptr;
479#ifdef DEBUG_WEATHER
483 void outputWeather();
489 void outputWeather(
490 map<size_t, shared_ptr<wx::FireWeather>>& weather,
491 const char* file_name);
492#endif
496 int year_;
500 bool is_out_of_time_ = false;
512 size_t scenarios_done_ = 0;
520 atomic<size_t> scenarios_last_save_ = 0;
532 bool interim_changed_ = true;
541 // /**
542 // * @brief Time when we last checked if simulation should end
543 // *
544 // */
545 std::chrono::steady_clock::time_point last_checked_;
549 MathSize latitude_;
553 MathSize longitude_;
554private:
555 mutex mutex_;
556};
557}
558}
Indicates a section of code that is limited to a certain number of threads running at once.
Definition Model.h:98
Semaphore & s_
Semaphore that this keeps track of access for.
Definition Model.h:102
CriticalSection(Semaphore &ss)
Constructor.
Definition Model.h:108
Contains all the immutable information regarding a simulation that is common between Scenarios.
Definition Model.h:134
shared_ptr< topo::Perimeter > perimeter_
Initial intensity map based off perimeter.
Definition Model.h:474
size_t scenarios_required_done_
How many scenarios out of first iteration have been completed.
Definition Model.h:516
topo::Cell cell(const Idx row, const Idx column) const
Cell at the given row and column.
Definition Model.h:167
bool interim_changed_
If interim outputs are different than last time they were saved.
Definition Model.h:532
Clock::duration time_limit_
Maximum amount of time simulation can run for before being stopped.
Definition Model.h:458
constexpr Clock::duration interimTimeLimit() const
Time between generating interim outputs (s)
Definition Model.h:242
bool is_out_of_time_
If simulation is out of time and should stop.
Definition Model.h:500
Clock::time_point no_interim_save_since_
Time of last interim save.
Definition Model.h:462
size_t scenarios_done_
How many scenarios have been completed.
Definition Model.h:512
MathSize latitude_
Latitude to use for any calcualtions.
Definition Model.h:549
map< size_t, shared_ptr< wx::FireWeather > > wx_daily_
Map of scenario number to weather stream.
Definition Model.h:446
size_t scenarios_per_iteration_
Number of scenarios per iteration.
Definition Model.h:524
void findStarts(Location location)
Find Cell(s) that can burn closest to Location.
Definition Model.cpp:359
MathSize longitude_
Longitude to use for any calcualtions.
Definition Model.h:553
map< size_t, shared_ptr< wx::FireWeather > > wx_
Map of scenario number to weather stream.
Definition Model.h:442
bool is_being_cancelled_
If simulation is being cancelled.
Definition Model.h:508
void releaseBurnedVector(BurnedData *has_burned) const noexcept
Return a BurnedData so it can be used in the future.
Definition Model.cpp:51
bool should_output_interim_
If simulation is past the time interval between interim outputs.
Definition Model.h:504
void makeStarts(Coordinates coordinates, const topo::Point &point, string perim, size_t size)
Make starts based on desired point and where nearest combustible cells are.
Definition Model.cpp:391
bool isOverSimulationCountLimit() const noexcept
Whether or not simulation is over max simulation count.
Definition Model.cpp:545
int year() const noexcept
What year the weather is for.
Definition Model.h:265
static Semaphore task_limiter
Semaphore used to limit how many things run at once.
Definition Model.h:383
void readWeather(const wx::FwiWeather &yesterday, const MathSize latitude, const string &filename)
Read weather used for Scenarios.
Definition Model.cpp:106
const wx::FwiWeather * yesterday() const noexcept
Definition Model.h:387
constexpr Idx columns() const
Number of columns in extent.
Definition Model.h:202
atomic< size_t > scenarios_last_save_
Scenarios completed at time of last interim save.
Definition Model.h:520
BurnedData * getBurnedVector() const noexcept
Acquire a BurnedData that has already burnt cells set.
Definition Model.cpp:25
Clock::time_point running_since_
Time to use for simulation start.
Definition Model.h:454
constexpr Clock::time_point runningSince() const
Time that execution started.
Definition Model.h:226
mutex vector_mutex_
Mutex for parallel access.
Definition Model.h:407
constexpr int nd(const DurationSize time) const
Difference between date and the date of minimum foliar moisture content.
Definition Model.h:290
constexpr Idx rows() const
Cell at the Location represented by the given hash.
Definition Model.h:194
Iteration readScenarios(const topo::StartPoint &start_point, DurationSize start, Day start_day, Day last_date)
Create an Iteration by initializing Scenarios.
Definition Model.cpp:466
size_t iterations_done_
How many iterations have been completed.
Definition Model.h:528
std::chrono::seconds runTime() const
Duration that model has run for.
Definition Model.cpp:521
wx::FwiWeather yesterday_
Definition Model.h:540
int year_
What year the weather is for.
Definition Model.h:496
constexpr topo::Cell cell(const Position< P > &position) const
Cell at the given Location.
Definition Model.h:177
static int runScenarios(const string dir_out, const char *weather_input, const wx::FwiWeather &yesterday, const char *raster_root, const topo::StartPoint &start_point, const tm &start_time, const string &perimeter, size_t size)
Run Scenarios initialized from given inputs.
Definition Model.cpp:1005
vector< shared_ptr< topo::Cell > > starts_
Cell(s) that can burn closest to start Location.
Definition Model.h:450
vector< unique_ptr< BurnedData > > vectors_
Pool of BurnedData that can be reused.
Definition Model.h:415
DurationSize saveProbabilities(map< DurationSize, ProbabilityMap * > &probabilities, const Day start_day, const bool is_interim)
Definition Model.cpp:666
map< DurationSize, ProbabilityMap * > runIterations(const topo::StartPoint &start_point, DurationSize start, Day start_day)
Run Iterations until confidence is reached.
Definition Model.cpp:742
tm start_time_
Start time of simulation.
Definition Model.h:411
Model(const string dir_out, const topo::StartPoint &start_point, topo::Environment *env)
Constructor.
Definition Model.cpp:69
Clock::duration interim_save_interval_
Definition Model.h:466
int ignitionScenarios() const noexcept
How many ignition scenarios are being used.
Definition Model.h:273
ProbabilityMap * makeProbabilityMap(DurationSize time, DurationSize start_time) const
Create a ProbabilityMap with the same extent as this.
Definition Model.cpp:549
int scenarioCount() const noexcept
How many Scenarios are in each Iteration.
Definition Model.h:281
std::chrono::seconds timeSinceLastSave() const
Time since last interim save.
Definition Model.cpp:527
bool is_over_simulation_count_
If simulation is over max simulation count.
Definition Model.h:536
constexpr Clock::duration timeLimit() const
Maximum amount of time simulation can run for before being stopped.
Definition Model.h:234
void add_statistics(vector< MathSize > *all_sizes, vector< MathSize > *means, vector< MathSize > *pct, const util::SafeVector &sizes)
Add statistics for completed iterations.
Definition Model.cpp:585
constexpr MathSize cellSize() const
Cell width and height (m)
Definition Model.h:210
constexpr const topo::Environment & environment() const
Environment simulation is occurring in.
Definition Model.h:218
array< int, MAX_DAYS > nd_
Differences between date and the date of minimum foliar moisture content.
Definition Model.h:438
std::chrono::steady_clock::time_point last_checked_
Time when we last checked if simulation should end.
Definition Model.h:545
bool shouldStop() const noexcept
Whether or not simulation has exceeded any limits that mean it should stop.
Definition Model.cpp:532
topo::Environment * env_
Environment to use for Model.
Definition Model.h:478
bool isOutOfTime() const noexcept
Whether or not simulation has been running longer than maximum duration.
Definition Model.cpp:536
void setWeather(const wx::FwiWeather &weather, const Day start_day)
Set constant weather.
Definition Model.cpp:97
Provides the ability to limit number of threads running at once.
Definition Model.h:33
std::condition_variable cv_
Condition variable to use for checking count.
Definition Model.h:84
std::mutex mutex_
Mutex for parallel access.
Definition Model.h:80
void wait()
Wait until allowed to run.
Definition Model.h:70
int limit_
Limit for number of threads.
Definition Model.h:92
void notify()
Notify something that's waiting so it can run.
Definition Model.h:61
int used_
Variable to keep count of threads in use.
Definition Model.h:88
Semaphore(const int n)
Create a Semaphore that limits number of concurrent things running.
Definition Model.h:39
A Position with a Slope, Aspect, and Fuel.
Definition Cell.h:20
The area that a Model is run for, with Fuel, Slope, and Aspect grids.
Definition Environment.h:49
constexpr Idx columns() const
Number of columns in grid.
Definition Environment.h:129
Cell cell(const Idx row, const Idx column) const
Cell at given row and column.
Definition Environment.h:160
constexpr MathSize cellSize() const
Cell width and height (m)
Definition Environment.h:137
constexpr Idx rows() const
Number of rows in grid.
Definition Environment.h:121
Definition Location.h:229
A geographic location in lat/long coordinates.
Definition Point.h:13
A Position with a row and column.
Definition Location.h:57
A Point that has sunrise and sunset times for each day.
Definition StartPoint.h:17
A vector with added thread safety.
Definition SafeVector.h:15
A Weather value with calculated FWI indices.
Definition FWI.h:209
Definition util.h:14