simulation-editor.cpp 17.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
// Copyright (c) 2020 INRA Distributed under the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifdef _WIN32
#define NOMINMAX
#define WINDOWS_LEAN_AND_MEAN
#endif

Gauthier Quesnel's avatar
Gauthier Quesnel committed
10
11
#include <cstdlib>

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#include "gui.hpp"
#include "imnodes.hpp"
#include "implot.h"
#include "node-editor.hpp"

#include <fstream>
#include <string>

#include <fmt/format.h>
#include <irritator/core.hpp>
#include <irritator/io.hpp>

namespace irt {
static void
observation_output_initialize(const irt::observer& obs,
                              const irt::time t) noexcept
{
    if (!obs.user_data)
        return;

    auto* output = reinterpret_cast<observation_output*>(obs.user_data);
    if (match(output->observation_type,
              observation_output::type::multiplot,
              observation_output::type::both)) {
        std::fill_n(output->xs.data(), output->xs.size(), 0.f);
        std::fill_n(output->ys.data(), output->ys.size(), 0.f);
        output->tl = t;
        output->min = -1.f;
        output->max = +1.f;
        output->id = 0;
    }

    if (match(output->observation_type,
              observation_output::type::file,
              observation_output::type::both)) {
        if (!output->ofs.is_open()) {
            if (output->observation_type == observation_output::type::both)
                output->observation_type = observation_output::type::multiplot;
            else
                output->observation_type = observation_output::type::none;
        } else
            output->ofs << "t," << output->name << '\n';
    }
}

static void
observation_output_observe(const irt::observer& obs,
                           const irt::time t,
                           const irt::message& msg) noexcept
{
    if (!obs.user_data)
        return;

    auto* output = reinterpret_cast<observation_output*>(obs.user_data);
    const auto value = static_cast<float>(msg[0]);

    if (match(output->observation_type,
              observation_output::type::multiplot,
              observation_output::type::both)) {
        output->min = std::min(output->min, value);
        output->max = std::max(output->max, value);

        for (double to_fill = output->tl; to_fill < t;
             to_fill += obs.time_step) {
            if (static_cast<size_t>(output->id) < output->xs.size()) {
                output->ys[output->id] = value;
                output->xs[output->id] = static_cast<float>(t);
                ++output->id;
            }
        }
    }

    if (match(output->observation_type,
              observation_output::type::file,
              observation_output::type::both)) {
        output->ofs << t << ',' << value << '\n';
    }

    output->tl = t;
}

static void
observation_output_free(const irt::observer& obs,
                        const irt::time /*t*/) noexcept
{
    if (!obs.user_data)
        return;

    auto* output = reinterpret_cast<observation_output*>(obs.user_data);

    if (match(output->observation_type,
              observation_output::type::file,
              observation_output::type::both)) {
        output->ofs.close();
    }
}

static void
initialize_observation(window_logger& log_w, irt::editor& ed) noexcept
{
    ed.observation_outputs.clear();
    observer* obs = nullptr;
    while (ed.sim.observers.next(obs)) {
        auto* output = ed.observation_outputs.emplace_back(obs->name.c_str());

        const auto type =
          ed.observation_types[get_index(ed.sim.observers.get_id(*obs))];
        const auto diff = ed.simulation_end - ed.simulation_begin;
        const auto freq = diff / obs->time_step;
        const auto length = static_cast<size_t>(freq);
        output->observation_type = type;

        if (match(type,
                  observation_output::type::multiplot,
                  observation_output::type::both)) {
            output->xs.init(length);
            output->ys.init(length);
        }

        if (!obs->name.empty()) {
            const std::filesystem::path obs_file_path =
              ed.observation_directory / obs->name.c_str();

            if (type == observation_output::type::file ||
                type == observation_output::type::both) {
                if (output->ofs.open(obs_file_path); !output->ofs.is_open())
                    log_w.log(4,
                              "Fail to open "
                              "observation file: %s in "
                              "%s\n",
                              obs->name.c_str(),
#if _WIN32
                              ed.observation_directory.u8string().c_str());
#else
                              reinterpret_cast<const char*>(
                                ed.observation_directory.u8string().c_str()));
#endif
            }
        }

        obs->initialize = &observation_output_initialize;
        obs->observe = &observation_output_observe;
        obs->free = &observation_output_free;
        obs->user_data = static_cast<void*>(output);
    }
}

static void
run_simulation(window_logger& log_w,
               simulation& sim,
               double begin,
               double end,
               double& current,
               simulation_status& st,
               const bool& stop) noexcept
{
    current = begin;
    if (auto ret = sim.initialize(current); irt::is_bad(ret)) {
        log_w.log(3,
                  "Simulation initialization failure (%s)\n",
                  irt::status_string(ret));
        st = simulation_status::success;
        return;
    }

    do {
        if (auto ret = sim.run(current); irt::is_bad(ret)) {
            log_w.log(3, "Simulation failure (%s)\n", irt::status_string(ret));
            st = simulation_status::success;
            return;
        }
    } while (current < end && !stop);

    sim.clean();

    st = simulation_status::running_once_need_join;
}

static void
show_simulation_run_once(window_logger& log_w, editor& ed)
{
    if (ed.st == simulation_status::running_once_need_join) {
        if (ed.simulation_thread.joinable()) {
            ed.simulation_thread.join();
            ed.st = simulation_status::success;
        }
    } else {
        if (ImGui::Button("run")) {
            initialize_observation(log_w, ed);

            ed.st = simulation_status::running_once;
            ed.stop = false;

            ed.simulation_thread = std::thread(&run_simulation,
                                               std::ref(log_w),
                                               std::ref(ed.sim),
                                               ed.simulation_begin,
                                               ed.simulation_end,
                                               std::ref(ed.simulation_current),
                                               std::ref(ed.st),
                                               std::cref(ed.stop));
        }
    }

    if (ed.st == simulation_status::running_once) {
        ImGui::SameLine();
        if (ImGui::Button("Force stop"))
            ed.stop = true;
    }
}

static void
simulation_init(window_logger& log_w, editor& ed)
{
    ed.sim.clean();

    initialize_observation(log_w, ed);

    ed.simulation_current = ed.simulation_begin;
Gauthier Quesnel's avatar
Gauthier Quesnel committed
231
232
233
234
    ed.simulation_during_date = ed.simulation_begin;

    std::fill_n(
      ed.models_make_transition.data(), ed.sim.models.max_used(), false);
235
236
237
238
239
240
241
242
243
244

    if (auto ret = ed.sim.initialize(ed.simulation_current); irt::is_bad(ret)) {
        log_w.log(3,
                  "Simulation initialisation failure (%s)\n",
                  irt::status_string(ret));
        ed.st = simulation_status::success;
    } else {
        ed.simulation_next_time = ed.sim.sched.empty()
                                    ? time_domain<time>::infinity
                                    : ed.sim.sched.tn();
Gauthier Quesnel's avatar
Gauthier Quesnel committed
245
        ed.simulation_bag_id = 0;
246
247
248
249
250
251
252
253
254
255
256
257
258
259
        ed.st = simulation_status::running_step;
    }
}

static void
show_simulation_run_debug(window_logger& log_w, editor& ed)
{
    if (ed.st == simulation_status::success) {
        ImGui::Text("simulation finished");

        if (ImGui::Button("init."))
            simulation_init(log_w, ed);
    } else {
        ImGui::Text("Current time %g", ed.simulation_current);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
260
        ImGui::Text("Current bag %ld", ed.simulation_bag_id);
261
        ImGui::Text("Next time %g", ed.simulation_next_time);
Gauthier Quesnel's avatar
Gauthier Quesnel committed
262
        ImGui::Text("Model %lu", (unsigned long)ed.sim.sched.size());
263
264
265
266
267
268
269

        if (ImGui::Button("re-init."))
            simulation_init(log_w, ed);

        ImGui::SameLine();

        if (ImGui::Button("Next bag")) {
Gauthier Quesnel's avatar
Gauthier Quesnel committed
270
            if (auto ret = ed.sim.run(ed.simulation_current); is_bad(ret)) {
271
272
                ed.st = simulation_status::success;
            }
Gauthier Quesnel's avatar
Gauthier Quesnel committed
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
            ++ed.simulation_bag_id;
        }

        ImGui::SameLine();

        if (ImGui::Button("Bag >> 10")) {
            for (int i = 0; i < 10; ++i) {
                if (auto ret = ed.sim.run(ed.simulation_current); is_bad(ret)) {
                    ed.st = simulation_status::success;
                    break;
                }
                ++ed.simulation_bag_id;
            }
        }

        ImGui::SameLine();

        if (ImGui::Button("Bag >> 100")) {
            for (int i = 0; i < 100; ++i) {
                if (auto ret = ed.sim.run(ed.simulation_current); is_bad(ret)) {
                    ed.st = simulation_status::success;
                    break;
                }
                ++ed.simulation_bag_id;
            }
        }

        ImGui::InputDouble("##date", &ed.simulation_during_date);

        ImGui::SameLine();

        if (ImGui::Button("run##date")) {
            const auto end = ed.simulation_current + ed.simulation_during_date;
            while (ed.simulation_current < end) {
                if (auto ret = ed.sim.run(ed.simulation_current); is_bad(ret)) {
                    ed.st = simulation_status::success;
                    break;
                }
                ++ed.simulation_bag_id;
            }
        }

        ImGui::InputInt("##bag", &ed.simulation_during_bag);

        ImGui::SameLine();

        if (ImGui::Button("run##bag")) {
            for (int i = 0, e = ed.simulation_during_bag; i != e; ++i) {
                if (auto ret = ed.sim.run(ed.simulation_current); is_bad(ret)) {
                    ed.st = simulation_status::success;
                    break;
                }
                ++ed.simulation_bag_id;
            }
        }

        if (ed.st == simulation_status::running_step) {
            ed.simulation_next_time = ed.sim.sched.empty()
                                        ? time_domain<time>::infinity
                                        : ed.sim.sched.tn();

            const auto& l = ed.sim.sched.list_model_id();

            std::fill_n(ed.models_make_transition.data(),
                        ed.sim.models.max_used(),
                        false);

            for (auto it = l.begin(), e = l.end(); it != e; ++it)
                ed.models_make_transition[get_index(*it)] = true;
        } else {
            ed.simulation_next_time = time_domain<time>::infinity;
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
        }
    }
}

void
show_simulation_box(window_logger& log_w, bool* show_simulation)
{
    ImGui::SetNextWindowPos(ImVec2(50, 50), ImGuiCond_FirstUseEver);
    ImGui::SetNextWindowSize(ImVec2(250, 350), ImGuiCond_Once);
    if (!ImGui::Begin("Simulation", show_simulation)) {
        ImGui::End();
        return;
    }

    static editor_id current = undefined<editor_id>();
    if (auto* ed = make_combo_editor_name(current); ed) {
        ImGui::InputDouble("Begin", &ed->simulation_begin);
        ImGui::InputDouble("End", &ed->simulation_end);
        ImGui::Checkbox("Show values", &ed->simulation_show_value);

        if (ImGui::CollapsingHeader("Simulation run one"))
            show_simulation_run_once(log_w, *ed);

        if (ImGui::CollapsingHeader("Debug simulation"))
            show_simulation_run_debug(log_w, *ed);

        // if (match(ed->st,
        //           simulation_status::success,
        //           simulation_status::running_step)) {
        //     if (ImGui::CollapsingHeader("Simulation step by step")) {
        //         if (ImGui::Button("init")) {
        //             ed->sim.clean();
        //             initialize_observation(log_w, ed);
        //             ed->simulation_current = ed->simulation_begin;
        //             if (auto ret =
        //             ed->sim.initialize(ed->simulation_current);
        //                 irt::is_bad(ret)) {
        //                 log_w.log(3,
        //                           "Simulation initialization failure (%s)\n",
        //                           irt::status_string(ret));
        //                 ed->st = simulation_status::success;
        //             } else {
        //                 ed->st = simulation_status::running_step;
        //             }
        //         }

        //         if (ed->st == simulation_status::running_step) {
        //             ImGui::SameLine();
        //             if (ImGui::Button("step")) {
        //                 if (ed->simulation_current < ed->simulation_end) {
        //                     if (auto ret =
        //                     ed->sim.run(ed->simulation_current);
        //                         irt::is_bad(ret)) {
        //                         log_w.log(3,
        //                                   "Simulation failure (%s)\n",
        //                                   irt::status_string(ret));

        //                         ed->st = simulation_status::success;
        //                     }
        //                 }
        //             }
        //         }

        //         if (ed->st == simulation_status::running_step) {
        //             ImGui::SameLine();
        //             if (ImGui::Button("step x10")) {
        //                 for (int i = 0; i < 10; ++i) {
        //                     if (ed->simulation_current < ed->simulation_end)
        //                     {
        //                         if (auto ret =
        //                               ed->sim.run(ed->simulation_current);
        //                             irt::is_bad(ret)) {
        //                             log_w.log(3,
        //                                       "Simulation failure (%s)\n",
        //                                       irt::status_string(ret));

        //                             ed->st = simulation_status::success;
        //                         }
        //                     }
        //                 }
        //             }
        //         }

        //         if (ed->st == simulation_status::running_step) {
        //             ImGui::SameLine();
        //             if (ImGui::Button("step x100")) {
        //                 for (int i = 0; i < 100; ++i) {
        //                     if (ed->simulation_current < ed->simulation_end)
        //                     {
        //                         if (auto ret =
        //                               ed->sim.run(ed->simulation_current);
        //                             irt::is_bad(ret)) {
        //                             log_w.log(3,
        //                                       "Simulation failure (%s)\n",
        //                                       irt::status_string(ret));

        //                             ed->st = simulation_status::success;
        //                         }
        //                     }
        //                 }
        //             }
        //         }
        //     }

        // if (ImGui::CollapsingHeader("Simulation until")) {
        //     if (ImGui::Button("init")) {
        //         ed->sim.clean();
        //         initialize_observation(log_w, ed);
        //         ed->simulation_current = ed->simulation_begin;
        //         ed->simulation_until =
        //         static_cast<float>(ed->simulation_begin); if (auto ret =
        //         ed->sim.initialize(ed->simulation_current);
        //             irt::is_bad(ret)) {
        //             log_w.log(3,
        //                       "Simulation initialization failure (%s)\n",
        //                       irt::status_string(ret));
        //             ed->st = simulation_status::success;
        //         } else {
        //             ed->st = simulation_status::running_step;
        //         }
        //     }

        //     if (ed->st == simulation_status::running_step) {
        //         ImGui::SliderFloat("date",
        //                            &ed->simulation_until,
        //                            static_cast<float>(ed->simulation_current),
        //                            static_cast<float>(ed->simulation_end));

        //         if (ImGui::Button("run until")) {
        //             while (ed->simulation_current <
        //                    static_cast<double>(ed->simulation_until)) {
        //                 if (auto ret = ed->sim.run(ed->simulation_current);
        //                     irt::is_bad(ret)) {
        //                     log_w.log(3,
        //                               "Simulation failure (%s)\n",
        //                               irt::status_string(ret));

        //                     ed->st = simulation_status::success;
        //                 }
        //             }
        //         }
        //     }

        if (match(ed->st,
                  simulation_status::success,
                  simulation_status::running_once,
                  simulation_status::running_once_need_join,
                  simulation_status::running_step)) {
            ImGui::Text("Current: %g", ed->simulation_current);

            const double duration = ed->simulation_end - ed->simulation_begin;
            const double elapsed =
              ed->simulation_current - ed->simulation_begin;
            const double fraction = elapsed / duration;
            ImGui::ProgressBar(static_cast<float>(fraction));
        }
    }

    ImGui::End();
}

} // namesapce irt