FireSTARR
Loading...
Searching...
No Matches
Model.h
1/* SPDX-License-Identifier: AGPL-3.0-or-later */
2#ifndef FS_MODEL_H
3#define FS_MODEL_H
4#include "stdafx.h"
5#include "Environment.h"
6#include "FireWeather.h"
7#include "Iteration.h"
8#include "Perimeter.h"
9#include "Settings.h"
10#include "unstable.h"
11namespace fs
12{
13using settings::Settings;
14class StartPoint;
15struct Event;
16class Scenario;
21{
22public:
27 explicit Semaphore(const int n) : used_{0}, limit_{n} { }
28 Semaphore(const Semaphore& rhs) = delete;
29 Semaphore(Semaphore&& rhs) = delete;
30 Semaphore& operator=(const Semaphore& rhs) = delete;
31 Semaphore& operator=(Semaphore&& rhs) = delete;
32 void set_limit(int limit)
33 {
34 logging::debug("Changing Semaphore limit from {:d} to {:d}", limit_, limit);
35 // NOTE: won't drop threads if set lower but won't give out more until below limit
36 limit_ = limit;
37 }
38 size_t limit() { return limit_; }
42 void notify()
43 {
44 std::unique_lock<std::mutex> l(mutex_);
45 --used_;
46 cv_.notify_one();
47 }
51 void wait()
52 {
53 std::unique_lock<std::mutex> l(mutex_);
54 cv_.wait(l, [this] { return used_ <= limit_; });
55 ++used_;
56 }
57
58private:
62 std::mutex mutex_;
66 std::condition_variable cv_;
70 int used_;
74 int limit_;
75};
81{
86
87public:
92 explicit CriticalSection(Semaphore& ss) : s_{ss} { s_.wait(); }
93 CriticalSection(const CriticalSection& rhs) = delete;
94 CriticalSection(CriticalSection&& rhs) = delete;
95 CriticalSection& operator=(const CriticalSection& rhs) = delete;
96 CriticalSection& operator=(CriticalSection&& rhs) = delete;
97 ~CriticalSection() noexcept
98 {
99 try
100 {
101 s_.notify();
102 }
103 catch (const std::exception& ex)
104 {
105 exit(logging::fatal(ex));
106 }
107 }
108};
113class Model
114{
115public:
128 [[nodiscard]] static int runScenarios(
129 const string_view output_directory,
130 const LazyPath& weather_input,
131 const FwiWeather& yesterday,
132 const char* raster_root,
133 const StartPoint& start_point,
134 const tm& start_time,
135 const LazyPath& perimeter,
136 const size_t size
137 );
138 [[nodiscard]]
139 Cell cell(const XYIdx xy) const
140 {
141 return env_->cell(xy);
142 }
143 [[nodiscard]] constexpr Idx height() const { return env_->height(); }
144 [[nodiscard]] constexpr Idx width() const { return env_->width(); }
149 [[nodiscard]] constexpr MathSize cellSize() const { return env_->cellSize(); }
154 [[nodiscard]] constexpr const Environment& environment() const { return *env_; }
159 [[nodiscard]] constexpr Clock::time_point runningSince() const { return running_since_; }
164 [[nodiscard]] constexpr Clock::duration timeLimit() const { return time_limit_; }
169 [[nodiscard]] constexpr Clock::duration interimTimeLimit() const
170 {
172 }
177 [[nodiscard]] bool shouldStop() const noexcept;
182 [[nodiscard]] bool isOutOfTime() const noexcept;
187 [[nodiscard]] bool isUnderSimulationCountMinimum() const noexcept;
192 [[nodiscard]] size_t activeSimulationsStillRequired() const noexcept;
197 [[nodiscard]] bool isOverSimulationCountMaximum() const noexcept;
202 [[nodiscard]] int year() const noexcept { return year_; }
207 [[nodiscard]] size_t ignitionScenarios() const noexcept { return starts_.size(); }
212 [[nodiscard]] size_t scenarioCount() const noexcept { return wx_.size() * ignitionScenarios(); }
218 [[nodiscard]] constexpr int nd(const DurationSize time) const
219 {
220 return nd_.at(static_cast<Day>(time));
221 }
222 [[nodiscard]] const char* outputDirectory() const { return output_directory_.c_str(); }
227 [[nodiscard]] std::chrono::seconds runTime() const;
228 [[nodiscard]] std::chrono::seconds timeSinceLastSave() const;
239 [[nodiscard]] shared_ptr<ProbabilityMap> makeProbabilityMap(
240 DurationSize time,
241 DurationSize start_time,
242 int min_value,
243 int low_max,
244 int med_max,
245 int max_value
246 ) const;
247 ~Model() = default;
253 Model(
254 const tm& start_time,
255 const string_view output_directory,
256 const StartPoint& start_point,
257 Environment* env
258 );
259 Model(
260 const tm& start_time,
261 const string_view output_directory,
262 const StartPoint& start_point,
263 Environment* env,
264 const Settings& settings
265 );
266 Model(Model&& rhs) noexcept = delete;
267 Model(const Model& rhs) = delete;
268 Model& operator=(Model&& rhs) noexcept = delete;
269 Model& operator=(const Model& rhs) = delete;
274 void setWeather(const FwiWeather& weather, const Day start_day);
281 void readWeather(const FwiWeather& yesterday, const MathSize latitude, const string& filename);
289 void makeStarts(Coordinates coordinates, const Point& point, const LazyPath& perim, size_t size);
298 [[nodiscard]] Iteration readScenarios(
299 const StartPoint& start_point,
300 DurationSize start,
301 Day start_day,
302 Day last_date
303 );
311 ptr<const FwiWeather> yesterday() const noexcept { return &yesterday_; }
315 MathSize initial_size() const
316 {
317 // if more than one cell at start then we'd have a perimeter
318 const auto num_cells = (nullptr == perimeter_) ? 1 : perimeter_->burned.size();
319 return env_->to_hectares(num_cells);
320 };
321
322private:
323 const string output_directory_;
331 [[nodiscard]] bool add_statistics(
332 vector<MathSize>* all_sizes,
333 vector<MathSize>* means,
334 vector<MathSize>* pct,
335 const SafeVector& sizes
336 );
348 map<DurationSize, shared_ptr<ProbabilityMap>> runIterations(
349 const StartPoint& start_point,
350 DurationSize start,
351 Day start_day
352 );
356 void findAllStarts();
360 DurationSize saveProbabilities(
361 map<DurationSize, shared_ptr<ProbabilityMap>>& probabilities,
362 const Day start_day,
363 const bool is_interim
364 );
369 void findStarts(const XYIdx& location);
373 array<int, MAX_DAYS> nd_{};
377 map<size_t, FireWeather> wx_{};
381 map<size_t, FireWeather> wx_daily_{};
385 vector<XYIdx> starts_{};
389 Clock::time_point running_since_;
393 Clock::duration time_limit_;
397 Clock::time_point no_interim_save_since_;
401 Clock::duration interim_save_interval_;
405 shared_ptr<Perimeter> perimeter_ = nullptr;
409 Environment* env_{nullptr};
410#ifdef DEBUG_WEATHER
414 void outputWeather();
420 void outputWeather(map<size_t, FireWeather>& weather, const char* file_name);
421#endif
425 int year_;
429 bool is_out_of_time_ = false;
441 atomic<size_t> scenarios_done_ = 0;
445 atomic<size_t> scenarios_required_done_ = 0;
449 atomic<size_t> scenarios_last_save_ = 0;
461 bool interim_changed_ = true;
478 // /**
479 // * @brief Time when we last checked if simulation should end
480 // *
481 // */
482 std::chrono::steady_clock::time_point last_checked_;
486 MathSize latitude_;
490 MathSize longitude_;
491};
492}
493#endif
A Position with a Slope, Aspect, and Fuel.
Definition Cell.h:13
Indicates a section of code that is limited to a certain number of threads running at once.
Definition Model.h:81
CriticalSection(Semaphore &ss)
Constructor.
Definition Model.h:92
Semaphore & s_
Semaphore that this keeps track of access for.
Definition Model.h:85
The area that a Model is run for, with Fuel, Slope, and Aspect grids.
Definition Environment.h:42
constexpr MathSize cellSize() const
Cell width and height (m)
Definition Environment.h:88
Definition Util.h:338
Contains all the immutable information regarding a simulation that is common between Scenarios.
Definition Model.h:114
constexpr Clock::duration timeLimit() const
Maximum amount of time simulation can run for before being stopped.
Definition Model.h:164
Model(const tm &start_time, const string_view output_directory, const StartPoint &start_point, Environment *env)
Constructor.
Definition Model.cpp:21
map< DurationSize, shared_ptr< ProbabilityMap > > runIterations(const StartPoint &start_point, DurationSize start, Day start_day)
Run Iterations until confidence is reached.
Definition Model.cpp:851
bool is_over_simulation_count_
If simulation is over max simulation count.
Definition Model.h:473
std::chrono::steady_clock::time_point last_checked_
Time when we last checked if simulation should end.
Definition Model.h:482
bool add_statistics(vector< MathSize > *all_sizes, vector< MathSize > *means, vector< MathSize > *pct, const SafeVector &sizes)
Add statistics for completed iterations.
Definition Model.cpp:603
bool isOverSimulationCountMaximum() const noexcept
Whether or not simulation is over max simulation count.
Definition Model.cpp:554
bool should_output_interim_
If simulation is past the time interval between interim outputs.
Definition Model.h:433
FwiWeather yesterday_
Definition Model.h:477
void setWeather(const FwiWeather &weather, const Day start_day)
Set constant weather.
Definition Model.cpp:56
tm start_time_
Start time of simulation.
Definition Model.h:340
atomic< size_t > scenarios_last_save_
Scenarios completed at time of last interim save.
Definition Model.h:449
bool shouldStop() const noexcept
Whether or not simulation has exceeded any limits that mean it should stop.
Definition Model.cpp:542
atomic< size_t > scenarios_required_done_
How many scenarios out of first iteration have been completed.
Definition Model.h:445
bool is_under_simulation_minimum_
If simulation is undex min simulation count.
Definition Model.h:465
constexpr MathSize cellSize() const
Cell width and height (m)
Definition Model.h:149
size_t iterations_done_
How many iterations have been completed.
Definition Model.h:457
atomic< size_t > scenarios_done_
How many scenarios have been completed.
Definition Model.h:441
bool isUnderSimulationCountMinimum() const noexcept
Whether or not simulation is under min simulation count.
Definition Model.cpp:549
Clock::time_point no_interim_save_since_
Time of last interim save.
Definition Model.h:397
size_t activeSimulationsStillRequired() const noexcept
How many active simulations are still needed.
Definition Model.cpp:550
constexpr const Environment & environment() const
Environment simulation is occurring in.
Definition Model.h:154
Clock::duration time_limit_
Maximum amount of time simulation can run for before being stopped.
Definition Model.h:393
constexpr int nd(const DurationSize time) const
Difference between date and the date of minimum foliar moisture content.
Definition Model.h:218
void findStarts(const XYIdx &location)
Find Cell(s) that can burn closest to Location.
Definition Model.cpp:270
bool interim_changed_
If interim outputs are different than last time they were saved.
Definition Model.h:461
std::chrono::seconds runTime() const
Duration that model has run for.
Definition Model.cpp:530
void findAllStarts()
Find all Cell(s) that can burn in entire Environment.
Definition Model.cpp:320
static Semaphore task_limiter
Semaphore used to limit how many things run at once.
Definition Model.h:307
DurationSize saveProbabilities(map< DurationSize, shared_ptr< ProbabilityMap > > &probabilities, const Day start_day, const bool is_interim)
Definition Model.cpp:776
void makeStarts(Coordinates coordinates, const Point &point, const LazyPath &perim, size_t size)
Make starts based on desired point and where nearest combustible cells are.
Definition Model.cpp:337
ptr< const FwiWeather > yesterday() const noexcept
Definition Model.h:311
MathSize latitude_
Latitude to use for any calcualtions.
Definition Model.h:486
Clock::duration interim_save_interval_
Definition Model.h:401
map< size_t, FireWeather > wx_daily_
Map of scenario number to weather stream.
Definition Model.h:381
shared_ptr< 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:555
shared_ptr< Perimeter > perimeter_
Perimeter to use for initializing simulations.
Definition Model.h:405
vector< XYIdx > starts_
Cell(s) that can burn closest to start Location.
Definition Model.h:385
int year_
What year the weather is for.
Definition Model.h:425
size_t scenarios_per_iteration_
Number of scenarios per iteration.
Definition Model.h:453
constexpr Clock::time_point runningSince() const
Time that execution started.
Definition Model.h:159
Clock::time_point running_since_
Time to use for simulation start.
Definition Model.h:389
Iteration readScenarios(const StartPoint &start_point, DurationSize start, Day start_day, Day last_date)
Create an Iteration by initializing Scenarios.
Definition Model.cpp:430
map< size_t, FireWeather > wx_
Map of scenario number to weather stream.
Definition Model.h:377
constexpr Clock::duration interimTimeLimit() const
Time between generating interim outputs (s)
Definition Model.h:169
MathSize initial_size() const
Initial fire size at start of scenario.
Definition Model.h:315
bool isOutOfTime() const noexcept
Whether or not simulation has been running longer than maximum duration.
Definition Model.cpp:548
size_t ignitionScenarios() const noexcept
How many ignition scenarios are being used.
Definition Model.h:207
MathSize longitude_
Longitude to use for any calcualtions.
Definition Model.h:490
array< int, MAX_DAYS > nd_
Differences between date and the date of minimum foliar moisture content.
Definition Model.h:373
static int runScenarios(const string_view output_directory, const LazyPath &weather_input, const FwiWeather &yesterday, const char *raster_root, const StartPoint &start_point, const tm &start_time, const LazyPath &perimeter, const size_t size)
Run Scenarios initialized from given inputs.
Definition Model.cpp:1193
void readWeather(const FwiWeather &yesterday, const MathSize latitude, const string &filename)
Read weather used for Scenarios.
Definition Model.cpp:76
Environment * env_
Environment to use for Model.
Definition Model.h:409
size_t active_simulations_still_required_
Number of active simulations still required.
Definition Model.h:469
size_t scenarioCount() const noexcept
How many Scenarios are in each Iteration.
Definition Model.h:212
int year() const noexcept
What year the weather is for.
Definition Model.h:202
bool is_out_of_time_
If simulation is out of time and should stop.
Definition Model.h:429
bool is_being_cancelled_
If simulation is being cancelled.
Definition Model.h:437
A vector with added thread safety.
Definition SafeVector.h:12
Provides the ability to limit number of threads running at once.
Definition Model.h:21
void wait()
Wait until allowed to run.
Definition Model.h:51
int limit_
Limit for number of threads.
Definition Model.h:74
void notify()
Notify something that's waiting so it can run.
Definition Model.h:42
std::condition_variable cv_
Condition variable to use for checking count.
Definition Model.h:66
std::mutex mutex_
Mutex for parallel access.
Definition Model.h:62
Semaphore(const int n)
Create a Semaphore that limits number of concurrent things running.
Definition Model.h:27
int used_
Variable to keep count of threads in use.
Definition Model.h:70
A Point that has sunrise and sunset times for each day.
Definition StartPoint.h:14
A Weather value with calculated FWI indices.
Definition FWI.h:142
Definition Location.h:81