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]] bool shouldStop() const noexcept;
247 [[nodiscard]] bool isOutOfTime() const noexcept;
252 [[nodiscard]] bool isOverSimulationCountLimit() const noexcept;
257 [[nodiscard]] int year() const noexcept
258 {
259 return year_;
260 }
265 [[nodiscard]] int ignitionScenarios() const noexcept
266 {
267 return starts_.size();
268 }
273 [[nodiscard]] int scenarioCount() const noexcept
274 {
275 return wx_.size() * ignitionScenarios();
276 }
282 [[nodiscard]] constexpr int nd(const DurationSize time) const
283 {
284 return nd_.at(static_cast<Day>(time));
285 }
286 [[nodiscard]] const char* outputDirectory() const
287 {
288 return dir_out_.c_str();
289 }
294 [[nodiscard]] std::chrono::seconds runTime() const;
305 [[nodiscard]] ProbabilityMap* makeProbabilityMap(DurationSize time,
306 DurationSize start_time,
307 int min_value,
308 int low_max,
309 int med_max,
310 int max_value) const;
311 ~Model() = default;
317 Model(const string dir_out,
318 const topo::StartPoint& start_point,
319 topo::Environment* env);
320 Model(Model&& rhs) noexcept = delete;
321 Model(const Model& rhs) = delete;
322 Model& operator=(Model&& rhs) noexcept = delete;
323 Model& operator=(const Model& rhs) = delete;
328 void setWeather(const wx::FwiWeather& weather, const Day start_day);
336 const MathSize latitude,
337 const string& filename);
345 void makeStarts(Coordinates coordinates,
346 const topo::Point& point,
347 string perim,
348 size_t size);
357 [[nodiscard]] Iteration readScenarios(const topo::StartPoint& start_point,
358 DurationSize start,
359 Day start_day,
360 Day last_date);
365 [[nodiscard]] BurnedData* getBurnedVector() const noexcept;
370 void releaseBurnedVector(BurnedData* has_burned) const noexcept;
378 const wx::FwiWeather* yesterday() const noexcept
379 {
380 return &yesterday_;
381 }
382private:
383 const string dir_out_;
391 [[nodiscard]] bool add_statistics(vector<MathSize>* all_sizes,
392 vector<MathSize>* means,
393 vector<MathSize>* pct,
394 const util::SafeVector& sizes);
398 mutable mutex vector_mutex_;
406 mutable vector<unique_ptr<BurnedData>> vectors_{};
414 map<DurationSize, ProbabilityMap*> runIterations(const topo::StartPoint& start_point,
415 DurationSize start,
416 Day start_day);
420 void findAllStarts();
424 DurationSize saveProbabilities(map<DurationSize, ProbabilityMap*>& probabilities, const Day start_day, const bool is_interim);
429 void findStarts(Location location);
433 array<int, MAX_DAYS> nd_{};
437 map<size_t, shared_ptr<wx::FireWeather>> wx_{};
441 map<size_t, shared_ptr<wx::FireWeather>> wx_daily_{};
445 vector<shared_ptr<topo::Cell>> starts_{};
449 Clock::time_point running_since_;
453 Clock::duration time_limit_;
454 // /**
455 // * @brief Initial intensity map based off perimeter
456 // */
457 // shared_ptr<IntensityMap> initial_intensity_ = nullptr;
461 shared_ptr<topo::Perimeter> perimeter_ = nullptr;
466#ifdef DEBUG_WEATHER
470 void outputWeather();
476 void outputWeather(
477 map<size_t, shared_ptr<wx::FireWeather>>& weather,
478 const char* file_name);
479#endif
483 int year_;
487 bool is_out_of_time_ = false;
496 // /**
497 // * @brief Time when we last checked if simulation should end
498 // *
499 // */
500 std::chrono::steady_clock::time_point last_checked_;
504 MathSize latitude_;
508 MathSize longitude_;
509};
510}
511}
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:461
topo::Cell cell(const Idx row, const Idx column) const
Cell at the given row and column.
Definition Model.h:167
Clock::duration time_limit_
Maximum amount of time simulation can run for before being stopped.
Definition Model.h:453
bool is_out_of_time_
If simulation is out of time and should stop.
Definition Model.h:487
MathSize latitude_
Latitude to use for any calcualtions.
Definition Model.h:504
map< size_t, shared_ptr< wx::FireWeather > > wx_daily_
Map of scenario number to weather stream.
Definition Model.h:441
void findStarts(Location location)
Find Cell(s) that can burn closest to Location.
Definition Model.cpp:357
MathSize longitude_
Longitude to use for any calcualtions.
Definition Model.h:508
map< size_t, shared_ptr< wx::FireWeather > > wx_
Map of scenario number to weather stream.
Definition Model.h:437
void releaseBurnedVector(BurnedData *has_burned) const noexcept
Return a BurnedData so it can be used in the future.
Definition Model.cpp:51
void findAllStarts()
Find all Cell(s) that can burn in entire Environment.
Definition Model.cpp:389
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:409
bool isOverSimulationCountLimit() const noexcept
Whether or not simulation is over max simulation count.
Definition Model.cpp:588
int year() const noexcept
What year the weather is for.
Definition Model.h:257
static Semaphore task_limiter
Semaphore used to limit how many things run at once.
Definition Model.h:374
void readWeather(const wx::FwiWeather &yesterday, const MathSize latitude, const string &filename)
Read weather used for Scenarios.
Definition Model.cpp:104
const wx::FwiWeather * yesterday() const noexcept
Definition Model.h:378
constexpr Idx columns() const
Number of columns in extent.
Definition Model.h:202
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:449
bool add_statistics(vector< MathSize > *all_sizes, vector< MathSize > *means, vector< MathSize > *pct, const util::SafeVector &sizes)
Add statistics for completed iterations.
Definition Model.cpp:644
ProbabilityMap * makeProbabilityMap(DurationSize time, DurationSize start_time, int min_value, int low_max, int med_max, int max_value) const
Create a ProbabilityMap with the same extent as this.
Definition Model.cpp:592
constexpr Clock::time_point runningSince() const
Time that execution started.
Definition Model.h:226
mutex vector_mutex_
Mutex for parallel access.
Definition Model.h:398
constexpr int nd(const DurationSize time) const
Difference between date and the date of minimum foliar moisture content.
Definition Model.h:282
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:491
std::chrono::seconds runTime() const
Duration that model has run for.
Definition Model.cpp:569
wx::FwiWeather yesterday_
Definition Model.h:495
int year_
What year the weather is for.
Definition Model.h:483
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:1115
vector< shared_ptr< topo::Cell > > starts_
Cell(s) that can burn closest to start Location.
Definition Model.h:445
vector< unique_ptr< BurnedData > > vectors_
Pool of BurnedData that can be reused.
Definition Model.h:406
DurationSize saveProbabilities(map< DurationSize, ProbabilityMap * > &probabilities, const Day start_day, const bool is_interim)
Definition Model.cpp:751
map< DurationSize, ProbabilityMap * > runIterations(const topo::StartPoint &start_point, DurationSize start, Day start_day)
Run Iterations until confidence is reached.
Definition Model.cpp:771
tm start_time_
Start time of simulation.
Definition Model.h:402
Model(const string dir_out, const topo::StartPoint &start_point, topo::Environment *env)
Constructor.
Definition Model.cpp:69
int ignitionScenarios() const noexcept
How many ignition scenarios are being used.
Definition Model.h:265
int scenarioCount() const noexcept
How many Scenarios are in each Iteration.
Definition Model.h:273
bool is_over_simulation_count_
If simulation is over max simulation count.
Definition Model.h:491
constexpr Clock::duration timeLimit() const
Maximum amount of time simulation can run for before being stopped.
Definition Model.h:234
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:433
std::chrono::steady_clock::time_point last_checked_
Time when we last checked if simulation should end.
Definition Model.h:500
bool shouldStop() const noexcept
Whether or not simulation has exceeded any limits that mean it should stop.
Definition Model.cpp:575
topo::Environment * env_
Environment to use for Model.
Definition Model.h:465
bool isOutOfTime() const noexcept
Whether or not simulation has been running longer than maximum duration.
Definition Model.cpp:579
void setWeather(const wx::FwiWeather &weather, const Day start_day)
Set constant weather.
Definition Model.cpp:95
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