-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctors.cpp
More file actions
1968 lines (1782 loc) · 82.5 KB
/
functors.cpp
File metadata and controls
1968 lines (1782 loc) · 82.5 KB
1
2
3
4
5
6
7
8
9
10
11
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
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
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// GAMBIT: Global and Modular BSM Inference Tool
// *********************************************
/// \file
///
/// Functor base class definitions.
///
/// *********************************************
///
/// Authors (add name and date if you modify):
///
/// \author Pat Scott
/// (patscott@physics.mcgill.ca)
/// \date 2013 Apr-July, Dec
/// \date 2014 Jan, Mar-May, Sep
/// \date 2015 Apr
///
/// \author Anders Kvellestad
/// (anders.kvellestad@fys.uio.no)
/// \date 2013 Apr, Nov
///
/// \author Christoph Weniger
/// (c.weniger@uva.nl)
/// \date 2013 May, June, July
///
/// \author Ben Farmer
/// (benjamin.farmer@monash.edu.au)
/// \date 2013 July, Sep
/// \date 2014 Jan
/// \date 2015 Nov
///
/// \author Lars A. Dal
/// (l.a.dal@fys.uio.no)
/// \date 2015 Jan
///
/// \author Tomas Gonzalo
/// (gonzalo@physik.rwth-aachen.de)
/// \date 2021 Sep
///
/// \author Patrick Stoecker
/// (stoecker@physik.rwth-aachen.de)
/// \date 2023 May, Nov
///
/// *********************************************
#include <chrono>
#include "gambit/Elements/functors.hpp"
#include "gambit/Elements/functor_definitions.hpp"
#include "gambit/Elements/type_equivalency.hpp"
#include "gambit/Utils/standalone_error_handlers.hpp"
#include "gambit/Models/models.hpp"
#include "gambit/Logs/logger.hpp"
#include "gambit/Logs/logging.hpp"
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/io/ios_state.hpp>
namespace Gambit
{
using namespace LogTags;
// Functor class methods
/// Constructor
functor::functor (str func_name,
str func_capability,
str result_type,
str origin_name,
Models::ModelFunctorClaw &claw) :
myName (func_name),
myCapability (func_capability),
myType (Utils::fix_type(result_type)),
myOrigin (origin_name),
myClaw (&claw),
#ifdef GAMBIT_LIGHT
myLabel (func_capability),
#else
myLabel ("#"+func_capability+" @"+origin_name+"::"+func_name),
#endif
myTimingLabel ("Runtime(ns) for "+myLabel),
myStatus (FunctorStatus::Model_incompatible),
myVertexID (-1), // (Note: myVertexID = -1 is intended to mean that no vertexID has been assigned)
myTimingVertexID(-1), // Not actually a graph vertex; ID assigned by "get_main_param_id" function.
verbose (false) // For debugging.
{}
/// Virtual calculate(); needs to be redefined in daughters.
void functor::calculate() {}
/// Interfaces for runtime optimization
/// Need to be implemented by daughters
/// @{
double functor::getRuntimeAverage() { return 0; }
double functor::getInvalidationRate() { return 0; }
void functor::setFadeRate(double) {}
void functor::notifyOfInvalidation(const str&) {}
void functor::reset() {}
void functor::reset(int) {}
/// @}
/// Reset-then-recalculate method
void functor::reset_and_calculate() { this->reset(omp_get_thread_num()); this->calculate(); }
/// Setter for purpose (relevant only for next-to-output functors)
void functor::setPurpose(str purpose) { myPurpose = purpose; }
/// Setter for critical flag (relevant only for next-to-output functors)
void functor::setCritical(bool critical) { myCritical = critical; }
/// Setter for vertex ID (used in printer system)
void functor::setVertexID(int ID) { myVertexID = ID; }
/// Acquire ID for timing 'vertex' (used in printer system)
void functor::setTimingVertexID(int ID) { myTimingVertexID = ID; }
/// Setter for status
void functor::setStatus(FunctorStatus stat)
{
myStatus = stat;
setInUse(myStatus == FunctorStatus::Active);
}
/// Getter for the wrapped function's name
str functor::name() const { return myName; }
/// Getter for the wrapped function's reported capability
str functor::capability() const { return myCapability; }
/// Getter for the wrapped function's reported return type
str functor::type() const { return myType; }
/// Getter for the wrapped function's origin (module or backend name)
str functor::origin() const { return myOrigin; }
/// Getter for the version of the wrapped function's origin (module or backend)
str functor::version() const { utils_error().raise(LOCAL_INFO,"The version method is only defined for backend functors."); return ""; }
/// Getter for the 'safe' incarnation of the version of the wrapped function's origin (module or backend)
str functor::safe_version()const { utils_error().raise(LOCAL_INFO,"The safe_version method is only defined for backend functors."); return ""; }
/// Getter for the functors current status
FunctorStatus functor::status() const { return myStatus; }
/// Checks whether the functor is available (or even already activate)
bool functor::isAvailable() const { return myStatus > 0; }
/// Checks whether the functor is active (or even hyperactive)
bool functor::isActive() const { return myStatus >= 2; }
/// Checks whether the functor is disabled (discriminant is negative)
bool functor::isDisabled() const { return myStatus < 0; }
/// Checks whether the functor is enabled (discriminant is non negative)
bool functor::isEnabled() const { return myStatus >= 0; }
/// Getter for the overall quantity provided by the wrapped function (capability-type pair)
sspair functor::quantity() const { return std::make_pair(myCapability, myType); }
/// Getter for purpose (relevant for output nodes, aka helper structures for the dep. resolution)
str functor::purpose() const { return myPurpose; }
/// Getter for critical (relevant for output nodes, aka helper structures for the dep. resolution)
bool functor::critical() const { return myCritical; }
/// Getter for citation key
str functor::citationKey() const { return myCitationKey; }
/// Getter for vertex ID
int functor::vertexID() const { return myVertexID; }
/// Getter for timing vertex ID
int functor::timingVertexID() const { return myTimingVertexID; }
/// Getter indicating if the wrapped function's result should to be printed
bool functor::requiresPrinting() const { return false; }
/// Getter indicating if the timing data for this function's execution should be printed
bool functor::requiresTimingPrinting() const { return false; }
/// Getter for the printer label
str functor::label() const { return myLabel; }
/// Getter for the printer timing label
str functor::timingLabel() const { return myTimingLabel; }
/// Setter for indicating if the wrapped function's result should to be printed
void functor::setPrintRequirement(bool flag)
{
if (flag)
{
utils_error().raise(LOCAL_INFO,"The setPrintRequirement method has not been defined in this class.");
}
}
/// Setter for indicating if the timing data for this functor should be printed
void functor::setTimingPrintRequirement(bool flag)
{
if (flag)
{
utils_error().raise(LOCAL_INFO,"The setTimingPrintRequirement method has not been defined in this class.");
}
}
/// Set the ordered list of pointers to other functors that should run nested in a loop managed by this one
void functor::setNestedList (std::vector<functor*>&)
{
utils_error().raise(LOCAL_INFO,"The setNestedList method has not been defined in this class.");
}
/// Set the iteration number in a loop in which this functor runs
void functor::setIteration (long long)
{
utils_error().raise(LOCAL_INFO,"The setIteration method has not been defined in this class.");
}
/// Getter for revealing whether this is permitted to be a manager functor
bool functor::canBeLoopManager()
{
utils_error().raise(LOCAL_INFO,"The canBeLoopManager method has not been defined in this class.");
return false;
}
/// Getter for revealing whether this functor needs a loop manager
bool functor::needsLoopManager()
{
utils_error().raise(LOCAL_INFO,"The needsLoopManager method has not been defined in this class.");
return false;
}
/// Getter for revealing the required capability of the wrapped function's loop manager
str functor::loopManagerCapability()
{
utils_error().raise(LOCAL_INFO,"The loopManagerCapability method has not been defined in this class.");
return "none";
}
/// Getter for revealing the required type of the wrapped function's loop manager
str functor::loopManagerType()
{
utils_error().raise(LOCAL_INFO,"The loopManagerType method has not been defined in this class.");
return "none";
}
/// Getter for revealing the name of the wrapped function's assigned loop manager
str functor::loopManagerName()
{
utils_error().raise(LOCAL_INFO,"The loopManagerName method has not been defined in this class.");
return "none";
}
/// Getter for revealing the module of the wrapped function's assigned loop manager
str functor::loopManagerOrigin()
{
utils_error().raise(LOCAL_INFO,"The loopManagerOrigin method has not been defined in this class.");
return "none";
}
/// Getter for listing currently activated dependencies
std::set<sspair> functor::dependencies()
{
utils_error().raise(LOCAL_INFO,"The dependencies method has not been defined in this class.");
std::set<sspair> empty;
return empty;
}
/// Getter for listing backends that require class loading
std::set<sspair> functor::backendclassloading()
{
utils_error().raise(LOCAL_INFO,"The backendclassloading method has not been defined in this class.");
std::set<sspair> empty;
return empty;
}
/// Getter for listing backend requirement groups
std::set<str> functor::backendgroups()
{
utils_error().raise(LOCAL_INFO,"The backendgroups method has not been defined in this class.");
std::set<str> empty;
return empty;
}
/// Getter for listing all backend requirements
std::set<sspair> functor::backendreqs()
{
utils_error().raise(LOCAL_INFO,"The backendreqs method has not been defined in this class.");
std::set<sspair> empty;
return empty;
}
/// Getter for listing backend requirements from a specific group
std::set<sspair> functor::backendreqs(str)
{
utils_error().raise(LOCAL_INFO,"The backendreqs method has not been defined in this class.");
std::set<sspair> empty;
return empty;
}
/// Getter for listing permitted backends
std::set<sspair> functor::backendspermitted(sspair)
{
utils_error().raise(LOCAL_INFO,"The backendspermitted method has not been defined in this class.");
std::set<sspair> empty;
return empty;
}
/// Getter for listing tags associated with backend requirements
std::set<str> functor::backendreq_tags(sspair)
{
utils_error().raise(LOCAL_INFO,"The backendreq_tags method has not been defined in this class.");
std::set<str> empty;
return empty;
}
/// Getter for listing backend requirements that must be resolved from the same backend
std::set<sspair> functor::forcematchingbackend(str)
{
utils_error().raise(LOCAL_INFO,"The forcematchingbackend method has not been defined in this class.");
std::set<sspair> empty;
return empty;
}
/// Getter for listing backend-specific conditional dependencies (4-string version)
std::set<sspair> functor::backend_conditional_dependencies (str, str, str, str)
{
utils_error().raise(LOCAL_INFO,"The backend_conditional_dependencies method has not been defined in this class.");
std::set<sspair> empty;
return empty;
}
/// Tell the functor that the loop it manages should break now.
void functor::breakLoop()
{
utils_error().raise(LOCAL_INFO,"The breakLoop method has not been defined in this class.");
}
/// Getter for backend-specific conditional dependencies (3-string version)
std::set<sspair> functor::backend_conditional_dependencies (str req, str type, str be)
{
return backend_conditional_dependencies(req, type, be, "any");
}
/// Getter for backend-specific conditional dependencies (backend functor pointer version)
std::set<sspair> functor::backend_conditional_dependencies (functor* be_functor)
{
return backend_conditional_dependencies (be_functor->capability(), be_functor->type(),
be_functor->origin(), be_functor->version());
}
/// Getter for listing model-specific conditional dependencies (matches also on parents and friends)
std::set<sspair> functor::model_conditional_dependencies (str)
{
utils_error().raise(LOCAL_INFO,"The model_conditional_dependencies method has not been defined in this class.");
std::set<sspair> empty;
return empty;
}
/// Getter for listing model-specific conditional dependencies (matches on the exact model)
std::set<sspair> functor::model_conditional_dependencies_exact (str)
{
utils_error().raise(LOCAL_INFO,"The model_conditional_dependencies_exact method has not been defined in this class.");
std::set<sspair> empty;
return empty;
}
/// Getter for listing model-specific conditional backend requirements (matches also on parents and friends)
std::set<sspair> functor::model_conditional_backend_reqs (str)
{
utils_error().raise(LOCAL_INFO,"The model_conditional_backend_reqs method has not been defined in this class.");
std::set<sspair> empty;
return empty;
}
/// Getter for listing model-specific conditional backend requirements (matches on the exact model)
std::set<sspair> functor::model_conditional_backend_reqs_exact (str)
{
utils_error().raise(LOCAL_INFO,"The model_conditional_backend_reqs_exact method has not been defined in this class.");
std::set<sspair> empty;
return empty;
}
/// Resolve a dependency using a pointer to another functor object
void functor::resolveDependency (functor*)
{
utils_error().raise(LOCAL_INFO,"The resolveDependency method has not been defined in this class.");
}
/// Set this functor's loop manager (if it has one)
void functor::resolveLoopManager (functor*)
{
utils_error().raise(LOCAL_INFO,"The resolveLoopManager method has not been defined in this class.");
}
/// Resolve a backend requirement using a pointer to another functor object
void functor::resolveBackendReq (functor*)
{
utils_error().raise(LOCAL_INFO,"The resolveBackendReq method has not been defined in this class.");
}
/// Notify the functor that a certain model is being scanned, so that it can activate its dependencies accordingly.
void functor::notifyOfModel(str)
{
utils_error().raise(LOCAL_INFO,"The notifyOfModel method has not been defined in this class.");
}
/// Notify the functor that it is being used to fill a dependency of another functor
void functor::notifyOfDependee (functor*)
{
utils_error().raise(LOCAL_INFO,"The notifyOfDependee method has not been defined in this class.");
}
/// Indicate to the functor which backends are actually loaded and working
void functor::notifyOfBackends(std::map<str, std::set<str> >)
{
utils_error().raise(LOCAL_INFO,"The notifyOfBackends method has not been defined in this class.");
}
#ifndef NO_PRINTERS
/// Print function
void functor::print(Printers::BasePrinter*, const int, int)
{
str warn_msg = "This is the functor base class print function! This should not\n";
warn_msg += "be used; the print function should be redefined in daughter\n"
"functor classes. If this is running there is a problem somewhere.\n"
"Currently only functors derived from module_functor_common<!=void>\n"
"are allowed to try to print themselves; i.e. backend and void\n"
"functors may not do this (they inherit this default message).";
utils_warning().raise(LOCAL_INFO,warn_msg);
}
/// Printer function (no-thread-index short-circuit)
void functor::print(Printers::BasePrinter* printer, const int pointID)
{
print(printer,pointID,0);
}
#endif
/// Notify the functor about an instance of the options class that contains
/// information from its corresponding ini-file entry in the auxiliaries or
/// observables section.
void functor::notifyOfIniOptions(const Options& opt)
{
myOptions = opt;
}
/// Return a safe pointer to the options that this functor is supposed to run with (e.g. from the ini file).
safe_ptr<Options> functor::getOptions()
{
return safe_ptr<Options>(&myOptions);
}
/// Notify the functor about a string in YAML that contains the sub-capability information (for use in standalones)
void functor::notifyOfSubCaps(const str& subcap_string)
{
YAML::Node subcap_node_simple = YAML::Load(subcap_string);
YAML::Node subcap_node_complex;
for (auto x : subcap_node_simple) subcap_node_complex[x.as<str>()] = YAML::Node();
notifyOfSubCaps(subcap_node_complex);
}
/// Notify the functor about an instance of the options class that contains sub-capability information
void functor::notifyOfSubCaps(const Options& subcaps)
{
for (auto entry : subcaps)
{
str key = entry.first.as<std::string>();
if (not mySubCaps.hasKey(key)) mySubCaps.setValue(key, entry.second);
else
{
std::ostringstream ss1, ss2;
ss1 << mySubCaps.getValue<YAML::Node>(key);
ss2 << entry.second.as<YAML::Node>();
if (not (ss1.str() == ss2.str()))
{
std::ostringstream ss;
ss << "Duplicate sub_capability clash. " << endl
<< "Your ObsLike section of the YAML file contains both " << endl
<< key << ": " << ss1.str() << endl << "and" << endl << key << ": " << ss2.str() << endl
<< "GAMBIT does not know which value to choose when trying to determine the sub-capabilities" << endl
<< "served by " << myOrigin << "::" << myName << ", as both ObsLike entries depend on this function.";
utils_error().raise(LOCAL_INFO, ss.str());
}
}
}
}
/// Return a safe pointer to the subcaps that this functor realises it is supposed to facilitate downstream calculation of.
safe_ptr<Options> functor::getSubCaps()
{
return safe_ptr<Options>(&mySubCaps);
}
/// Return a safe pointer to the vector of all capability,type pairs of functors arranged downstream of this one in the dependency tree.
safe_ptr<std::set<sspair>> functor::getDependees()
{
return safe_ptr<std::set<sspair>>(&myDependees);
}
/// Getter for listing allowed models
const std::set<str>& functor::getAllowedModels()
{
return allowedModels;
}
/// Getter for listing conditional models
const std::set<str>& functor::getConditionalModels()
{
return conditionalModels;
}
/// Getter for map of model groups and the set of models in each group
const std::map<str, std::set<str>>& functor::getModelGroups()
{
return modelGroups;
}
/// Test whether the functor is allowed (either explicitly or implicitly) to be used with a given model
bool functor::modelAllowed(str model)
{
bool allowed = false;
if (verbose)
{
std::cout << "Checking allowedModels set for functor "<<myLabel<<std::endl;
for(std::set<str>::iterator it = allowedModels.begin(); it != allowedModels.end(); ++it)
{
std::cout << " "<< *it << std::endl;
}
}
if (allowedModels.empty() and allowedGroupCombos.empty()) allowed=true;
if (allowed_parent_or_friend_exists(model)) allowed=true;
if (verbose) std::cout << " Allowed to be used with model "<<model<<"? "<<allowed<<std::endl;
return allowed;
}
/// Test whether the functor has been explictly allowed to be used with a given model
bool functor::modelExplicitlyAllowed(str model)
{
if (allowedModels.find(model) != allowedModels.end()) return true;
return false;
}
/// Test whether the functor is allowed to be used with all models
bool functor::allModelsAllowed()
{
return allowedModels.empty() and allowedGroupCombos.empty();
}
/// Add a model to the internal list of models for which this functor is allowed to be used.
void functor::setAllowedModel(str model) { allowedModels.insert(model); }
/// Test whether the functor is allowed (either explicitly or implicitly) to be used with a given combination of models
bool functor::modelComboAllowed(std::set<str> combo)
{
// If any model in the combo is always allowed, then give the combo a thumbs up.
for(std::set<str>::const_iterator model = combo.begin(); model != combo.end(); model++)
{
if (modelAllowed(*model)) return true;
}
// Loop over the allowed combinations, and check if the passed combo matches any of them
for(std::set<std::set<str> >::const_iterator group_combo = allowedGroupCombos.begin(); group_combo != allowedGroupCombos.end(); group_combo++)
{
bool matches = true;
//Loop over each group in the allowed group combination, and check if one of the entries in the passed model combination matches it somehow.
for(std::set<str>::const_iterator group = group_combo->begin(); group != group_combo->end(); group++)
{
matches = matches and contains_anything_interpretable_as_member_of(combo, *group);
if (not matches) break;
}
//Return true immediately if all entries in the allowed group combination have been matched.
if (matches) return true;
}
return false;
}
/// Test whether the functor has been explictly allowed to be used with a given combination of models
bool functor::modelComboExplicitlyAllowed(std::set<str> combo)
{
// If any model in the combo is always explicitly allowed, then give the combo a thumbs up.
for(std::set<str>::const_iterator model = combo.begin(); model != combo.end(); model++)
{
if (modelExplicitlyAllowed(*model)) return true;
}
// Loop over the allowed combinations, and check if the passed combo matches any of them
for(std::set<std::set<str> >::const_iterator group_combo = allowedGroupCombos.begin(); group_combo != allowedGroupCombos.end(); group_combo++)
{
bool matches = true;
//Loop over each group in the allowed group combination, and check if one of the entries in the passed model combination matches it explicitly.
for(std::set<str>::const_iterator group = group_combo->begin(); group != group_combo->end(); group++)
{
matches = matches and has_common_elements(combo, *group);
if (not matches) break;
}
//Return true immediately if all entries in the allowed group combination have been matched.
if (matches) return true;
}
return false;
}
/// Add a model group definition to the internal list of model groups.
void functor::setModelGroup(str group, str contents)
{
//Strip the group contents of its parentheses, then split it, turn it into a set and save it in the map
Utils::strip_parentheses(contents);
std::vector<str> v = Utils::delimiterSplit(contents, ",");
std::set<str> combo(v.begin(), v.end());
modelGroups[group] = combo;
}
/// Add a model group combination to the internal list of combinations for which this functor is allowed to be used.
void functor::setAllowedModelGroupCombo(str groups)
{
//Strip the group combo of its parentheses and whitespace, then split it and save it in the vector of allowed combos
Utils::strip_parentheses(groups);
Utils::strip_whitespace_except_after_const(groups);
std::vector<str> v = Utils::delimiterSplit(groups, ",");
std::set<str> group_combo(v.begin(), v.end());
allowedGroupCombos.insert(group_combo);
}
/// Add an observable to the set of those that this functor matches.
void functor::addMatchedObservable(const DRes::Observable* obs) { matched_observables.insert(obs); }
/// Retrieve the set of observables that this functor matches.
const std::set<const DRes::Observable*>& functor::getMatchedObservables() { return matched_observables; }
/// Add a module rule to the set of those against which this functor has been tested and found to match.
void functor::addMatchedModuleRule(const DRes::ModuleRule* r) { matched_module_rules.insert(r); }
/// Add a backend rule to the set of those against which this functor has been tested and found to match.
void functor::addMatchedBackendRule(const DRes::BackendRule* r) { matched_backend_rules.insert(r); }
/// Retrieve the set of module rules against which this functor has been tested and found to match.
const std::set<const DRes::ModuleRule*>& functor::getMatchedModuleRules() { return matched_module_rules; }
/// Retrieve the set of backend rules against which this functor has been tested and found to match.
const std::set<const DRes::BackendRule*>& functor::getMatchedBackendRules() { return matched_backend_rules; }
// Retrieve matched rules by type.
template<>
const std::set<const DRes::ModuleRule*>& functor::getMatchedRules() { return getMatchedModuleRules(); }
template<>
const std::set<const DRes::BackendRule*>& functor::getMatchedRules() { return getMatchedBackendRules(); }
/// Attempt to retrieve a dependency or model parameter that has not been resolved
void functor::failBigTime(str method)
{
str error_msg = "Attempted to use a functor method from a null pointer.";
error_msg += "\nProbably you tried to use a conditional dependency that has"
"\nnot been activated, or a model parameter that is not defined"
"\nin the model for which this function has been invoked."
"\nPlease check your module function source code."
"\nMethod invoked: " + method + ".";
utils_error().raise(LOCAL_INFO,error_msg);
}
/// Test if there is a model in the functor's allowedModels list as which this model can be interpreted
inline bool functor::allowed_parent_or_friend_exists(str model)
{
for (std::set<str>::reverse_iterator it = allowedModels.rbegin() ; it != allowedModels.rend(); ++it)
{
if (myClaw->model_exists(*it))
{
if (myClaw->downstream_of(model, *it)) return true;
}
}
return false;
}
/// Check that a model is actually part of a combination that is allowed to be used with this functor.
inline bool functor::in_allowed_combo(str model)
{
// If the model is allowed on its own, just give the thumbs up immediately.
if (modelAllowed(model)) return true;
// Loop over the allowed combinations, and check if the passed model matches anything in any of them
for(std::set<std::set<str> >::const_iterator group_combo = allowedGroupCombos.begin(); group_combo != allowedGroupCombos.end(); group_combo++)
{
//Loop over each group in the allowed group combination, and check if the model is interpretable as a model in the group.
for(std::set<str>::const_iterator group = group_combo->begin(); group != group_combo->end(); group++)
{
// Work through the members of the model group
std::set<str> models = modelGroups.at(*group);
for (std::set<str>::reverse_iterator it = models.rbegin() ; it != models.rend(); ++it)
{
if (myClaw->model_exists(*it))
{
if (myClaw->downstream_of(model, *it)) return true;
}
}
}
}
return false;
}
/// Test whether any of the entries in a given model group is a valid interpretation of any members in a given combination
inline bool functor::contains_anything_interpretable_as_member_of(std::set<str> combo, str group)
{
// Work through the members of the model group
std::set<str> models = modelGroups.at(group);
for (std::set<str>::const_iterator it = models.begin() ; it != models.end(); ++it)
{
if (myClaw->model_exists(*it))
{
// Work through the members of the combination
for (std::set<str>::const_iterator jt = combo.begin() ; jt != combo.end(); ++jt)
{
if (myClaw->model_exists(*jt))
{
if (myClaw->downstream_of(*jt, *it)) return true;
}
}
}
}
return false;
}
/// Work out whether a given combination of models and a model group have any elements in common
inline bool functor::has_common_elements(std::set<str> combo, str group)
{
// Work through the members of the model group
std::set<str> models = modelGroups.at(group);
for (std::set<str>::reverse_iterator it = models.rbegin() ; it != models.rend(); ++it)
{
if ( std::find(combo.begin(), combo.end(), *it) == combo.end() ) return true;
}
return false;
}
/// Try to find a parent or friend model in some user-supplied map from models to sspair vectors
/// Preferentially returns the 'least removed' parent or friend, i.e. less steps back in the model lineage.
str functor::find_friend_or_parent_model_in_map(str model, std::map< str, std::set<sspair> > karta)
{
std::vector<str> candidates;
for (std::map< str, std::set<sspair> >::reverse_iterator it = karta.rbegin() ; it != karta.rend(); ++it)
{
if (myClaw->model_exists(it->first))
{
if (myClaw->downstream_of(model, it->first)) candidates.push_back(it->first);
}
}
// If found no candidates, return the empty string.
if (candidates.empty()) return "";
// If found just one, return it with no further questions.
if (candidates.size() == 1) return candidates[0];
// If found more than one, choose the one closest to the model passed in.
str result = candidates.front();
for (std::vector<str>::iterator it = candidates.begin()+1; it != candidates.end(); ++it)
{
if (myClaw->downstream_of(*it, result)) result = *it;
}
return result;
}
/// Retrieve the previously saved exception generated when this functor invalidated the current point in model space.
invalid_point_exception* functor::retrieve_invalid_point_exception() { return NULL; }
// Module_functor_common class methods
/// Constructor
module_functor_common::module_functor_common(str func_name,
str func_capability,
str result_type,
str origin_name,
Models::ModelFunctorClaw &claw)
: functor (func_name, func_capability, result_type, origin_name, claw),
myTimingPrintFlag (false),
start (NULL),
end (NULL),
point_exception_raised (false),
runtime_average (FUNCTORS_RUNTIME_INIT), // default 1 micro second
fadeRate (FUNCTORS_FADE_RATE), // can be set individually for each functor
pInvalidation (FUNCTORS_BASE_INVALIDATION_RATE),
needs_recalculating (NULL),
already_printed (NULL),
already_printed_timing (NULL),
iCanManageLoops (false),
iRunNested (false),
myLoopManagerCapability ("none"),
myLoopManagerType ("none"),
myLoopManager (NULL),
myCurrentIteration (NULL),
globlMaxThreads (omp_get_max_threads()),
myLogTag (-1)
{
if (globlMaxThreads == 0) utils_error().raise(LOCAL_INFO,"Cannot determine number of hardware threads available on this system.");
// Determine LogTag number
myLogTag = Logging::str2tag(myOrigin);
if (not claw.model_exists(origin_name)) check_missing_LogTag();
}
/// Destructor
module_functor_common::~module_functor_common()
{
if (start != NULL) delete [] start;
if (end != NULL) delete [] end;
if (needs_recalculating != NULL) delete [] needs_recalculating;
if (already_printed != NULL) delete [] already_printed;
if (already_printed_timing != NULL) delete [] already_printed_timing;
if (myCurrentIteration != NULL) delete [] myCurrentIteration;
}
/// Check if an appropriate LogTag for this functor is missing from the logging system.
void module_functor_common::check_missing_LogTag()
{
if(myLogTag==-1)
{
std::ostringstream ss;
ss << "Cannot retrieve LogTag number; no match for module name in tag2str map." << endl
<< "Module: " << myOrigin << endl
<< "Function: " << myName << endl
<< "This is probably because there is no log specified for " << myOrigin << " in your yaml file.";
utils_warning().raise(LOCAL_INFO,ss.str());
}
}
/// Getter for averaged runtime
double module_functor_common::getRuntimeAverage()
{
return runtime_average;
}
/// Setter for indicating if the timing data for this function's execution should be printed
void module_functor_common::setTimingPrintRequirement(bool flag)
{
myTimingPrintFlag = flag;
}
/// Getter indicating if the timing data for this function's execution should be printed
bool module_functor_common::requiresTimingPrinting() const
{
return myTimingPrintFlag;
}
/// Reset functor for all threads
void module_functor_common::reset()
{
init_memory();
int n = (iRunNested ? globlMaxThreads : 1);
std::fill(needs_recalculating, needs_recalculating+n, true);
std::fill(already_printed, already_printed+n, false);
std::fill(already_printed_timing, already_printed_timing+n, false);
if (iCanManageLoops) resetLoop();
point_exception_raised = false;
}
/// Reset functor for one thread only
void module_functor_common::reset(int thread_num)
{
init_memory();
needs_recalculating[thread_num] = true;
already_printed[thread_num] = false;
already_printed_timing[thread_num] = false;
if (iCanManageLoops) resetLoop();
}
/// Tell the functor that it invalidated the current point in model space, pass a message explaining why, and throw an exception.
void module_functor_common::notifyOfInvalidation(const str& msg)
{
acknowledgeInvalidation(invalid_point());
retrieve_invalid_point_exception()->raise(msg);
}
/// Acknowledge that this functor invalidated the current point in model space.
void module_functor_common::acknowledgeInvalidation(invalid_point_exception& e, functor* f)
{
#pragma omp atomic
pInvalidation += fadeRate*(1-FUNCTORS_BASE_INVALIDATION_RATE);
if (f==NULL) f = this;
#pragma omp critical (raised_point_exception)
{
e.set_thrower(f);
raised_point_exception = e;
point_exception_raised = true;
}
if (omp_get_level()!=0) breakLoop();
}
/// Retrieve the previously saved exception generated when this functor invalidated the current point in model space.
invalid_point_exception* module_functor_common::retrieve_invalid_point_exception()
{
if (point_exception_raised) return &raised_point_exception;
for (auto f = myNestedFunctorList.begin(); f != myNestedFunctorList.end(); ++f)
{
invalid_point_exception* e = (*f)->retrieve_invalid_point_exception();
if (e != NULL) return e;
}
return NULL;
}
/// Getter for invalidation rate
double module_functor_common::getInvalidationRate()
{
return pInvalidation;
}
/// Setter for the fade rate
void module_functor_common::setFadeRate(double new_rate)
{
fadeRate = new_rate;
}
/// Indicate whether or not a known model is activated or not.
bool module_functor_common::getActiveModelFlag(str model)
{
if (activeModelFlags.find(model) == activeModelFlags.end())
{
std::ostringstream ss;
ss << "Problem with ModelInUse(\"" << model << "\")." << endl
<< "This model is not known by " << myOrigin << "::" << myName << "." << endl
<< "Please make sure that it has been mentioned in some context in the" << endl
<< "rollcall header declaration of this function.";
model_error().raise(LOCAL_INFO,ss.str());
}
return activeModelFlags.at(model);
}
/// Return a safe pointer to a string indicating which backend requirement has been activated for a given backend group.
safe_ptr<str> module_functor_common::getChosenReqFromGroup(str group)
{
chosenReqsFromGroups[group] = "none";
return safe_ptr<str>(&chosenReqsFromGroups[group]);
}
/// Execute a single iteration in the loop managed by this functor.
void module_functor_common::iterate(long long iteration)
{
if (not myNestedFunctorList.empty())
{
for (std::vector<functor*>::iterator it = myNestedFunctorList.begin();
it != myNestedFunctorList.end(); ++it)
{
(*it)->setIteration(iteration); // Tell the nested functor what iteration this is.
try
{
(*it)->reset_and_calculate(); // Reset the nested functor so that it recalculates, then set it off
}
catch (invalid_point_exception& e)
{
acknowledgeInvalidation(e,*it);
if (omp_get_level()==0) throw(e); // If not in an OpenMP parallel block, inform of invalidation and throw onwards
}
catch (halt_loop_exception& e)
{
// Skip the rest of the iteration, without trying to evaluate the rest of the loop, and wrap it up.
breakLoop();
break;
}
catch (invalid_loop_iteration_exception& e)
{
// Just skip on to the next iteration, without trying to evaluate the rest of the loop.
break;
}
}
}
}
// Initialise the array holding the current iteration(s) of this functor.
void module_functor_common::init_myCurrentIteration_if_NULL()
{
if(myCurrentIteration==NULL)
{
#pragma omp critical(module_functor_init_myCurrentIteration_if_NULL)
{
if(myCurrentIteration==NULL) // Check again in case two threads managed to get this far in sequence.
{
// Set the number of slots to the max number of threads allowed iff this functor can run in parallel
int nslots = (iRunNested ? globlMaxThreads : 1);
// Reserve enough space to hold as many iteration numbers as there are slots (threads) allowed
myCurrentIteration = new long long[nslots];
// Zero them to start off
std::fill(myCurrentIteration, myCurrentIteration+nslots, 0);
}
}
}
}
/// Tell the manager of the loop in which this functor runs that it is time to break the loop.
void module_functor_common::breakLoopFromManagedFunctor()
{
if (myLoopManager == NULL)
{
str errmsg = "Problem whilst attempting to break out of loop:";
errmsg += "\n Loop Manager not properly defined."
"\n This is " + this->name() + " in " + this->origin() + ".";
utils_error().raise(LOCAL_INFO,errmsg);
}
else
{
myLoopManager->breakLoop();
}
}
/// Tell the functor that the loop it manages should break now.
void module_functor_common::breakLoop()
{
#pragma omp critical (myLoopIsDone)
{
myLoopIsDone = true;
}
}
/// Return a safe pointer to the flag indicating that a loop managed by this functor should break now.
safe_ptr<bool> module_functor_common::loopIsDone()
{
return safe_ptr<bool>(&myLoopIsDone);
}
/// Provide a way to reset the flag indicating that a loop managed by this functor should break.
void module_functor_common::resetLoop()
{
#pragma omp critical (myLoopIsDone)
{
myLoopIsDone = false;
}
}
/// Setter for setting the iteration number in the loop in which this functor runs
void module_functor_common::setIteration (long long iteration)
{
init_myCurrentIteration_if_NULL(); // Init memory if this is the first run through.
myCurrentIteration[omp_get_thread_num()] = iteration;
}
/// Return a safe pointer to the iteration number in the loop in which this functor runs.
omp_safe_ptr<long long> module_functor_common::iterationPtr()
{