version GIT relicensing-7278-g091132d5eb 2026-12-02 03:10:01+00:00
\(\newcommand{\dealvcentcolon}{\mathrel{\mathop{:}}}\) \(\newcommand{\dealcoloneq}{\dealvcentcolon\mathrel{\mkern-1.2mu}=}\) \(\newcommand{\jump}[1]{\left[\!\left[ #1 \right]\!\right]}\) \(\newcommand{\average}[1]{\left\{\!\left\{ #1 \right\}\!\right\}}\)
Loading...
Searching...
No Matches
symengine_optimizer.h
Go to the documentation of this file.
1// -----------------------------------------------------------------------------
2//
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception OR LGPL-2.1-or-later
4// Copyright (C) 2020 - 2026 by the deal.II authors
5//
6// This file is part of the deal.II library.
7//
8// Detailed license information governing the source code and contributions
9// can be found in LICENSE.md and CONTRIBUTING.md at the top level directory.
10//
11// -----------------------------------------------------------------------------
12
13#ifndef dealii_differentiation_sd_symengine_optimizer_h
14#define dealii_differentiation_sd_symengine_optimizer_h
15
16#include <deal.II/base/config.h>
17
18#ifdef DEAL_II_WITH_SYMENGINE
19
20// Low level
21# include <symengine/basic.h>
22# include <symengine/dict.h>
23# include <symengine/symengine_exception.h>
24# include <symengine/symengine_rcp.h>
25
26// Optimization
27# include <symengine/lambda_double.h>
28# include <symengine/visitor.h>
29# ifdef HAVE_SYMENGINE_LLVM
30# include <symengine/llvm_double.h>
31# endif
32
35
41
42# include <boost/serialization/split_member.hpp>
43# include <boost/type_traits.hpp>
44
45# include <algorithm>
46# include <map>
47# include <memory>
48# include <type_traits>
49# include <utility>
50# include <vector>
51
52#endif // DEAL_II_WITH_SYMENGINE
53
55
56#ifdef DEAL_II_WITH_SYMENGINE
57namespace Differentiation
58{
59 namespace SD
60 {
71 "SymEngine has not been built with LLVM support.");
72
78 "The SymEngine LLVM optimizer does not (yet) support the "
79 "selected return type.");
80
84 // Forward declarations
85 template <typename ReturnType>
86 class BatchOptimizer;
87
88
94 enum class OptimizerType
95 {
104 lambda,
109 llvm
110 };
111
112
116 template <typename StreamType>
117 inline StreamType &
118 operator<<(StreamType &s, OptimizerType o)
119 {
121 s << "dictionary";
122 else if (o == OptimizerType::lambda)
123 s << "lambda";
124 else if (o == OptimizerType::llvm)
125 s << "llvm";
126 else
127 {
128 Assert(false, ExcMessage("Unknown optimization method."));
129 }
130
131 return s;
132 }
133
134
140 enum class OptimizationFlags : unsigned char
141 {
149 optimize_cse = 0x0001,
154 optimize_aggressive = 0x0002,
159 };
160
161
170 // This operator exists since if it did not then the result of the bit-or
171 // <tt>operator |</tt> would be an integer which would in turn trigger a
172 // compiler warning when we tried to assign it to an object of type
173 // OptimizationFlags.
174 inline OptimizationFlags
176 {
177 return static_cast<OptimizationFlags>(static_cast<unsigned int>(f1) |
178 static_cast<unsigned int>(f2));
179 }
180
181
186 inline OptimizationFlags &
188 {
189 f1 = f1 | f2;
190 return f1;
191 }
192
193
202 // This operator exists since if it did not then the result of the bit-or
203 // <tt>operator |</tt> would be an integer which would in turn trigger a
204 // compiler warning when we tried to assign it to an object of type
205 // OptimizationFlags.
206 inline OptimizationFlags
208 {
209 return static_cast<OptimizationFlags>(static_cast<unsigned int>(f1) &
210 static_cast<unsigned int>(f2));
211 }
212
213
218 inline OptimizationFlags &
220 {
221 f1 = f1 & f2;
222 return f1;
223 }
224
225
226 namespace internal
227 {
232 inline bool
234 {
235 return static_cast<int>(flags & OptimizationFlags::optimize_cse);
236 }
237
242 inline int
244 {
245 // With the LLVM compiler there exists the opportunity to tune
246 // the level of optimizations performed during compilation.
247 // By default SymEngine sets this at "opt_level=2", which one
248 // presumes targets -O2. Here we are a bit more specific about
249 // want we want it to do:
250 // - Normal compilation: -02 (default settings)
251 // - Aggressive mode: -03 (the whole lot!)
252 // In theory we could also target
253 // - Debug mode: -O0 (no optimizations)
254 // but this doesn't make much sense since SymEngine is a
255 // tested external library.
256 const bool use_agg_opt =
257 static_cast<int>(flags & OptimizationFlags::optimize_aggressive);
258 const int opt_level = (use_agg_opt ? 3 : 2);
259 return opt_level;
260 }
261 } // namespace internal
262
263
268 template <typename StreamType>
269 inline StreamType &
270 operator<<(StreamType &s, OptimizationFlags o)
271 {
272 s << " OptimizationFlags|";
273 if (static_cast<unsigned int>(o & OptimizationFlags::optimize_cse))
274 s << "cse|";
275
276 // LLVM optimization level
277 s << "-O" + std::to_string(internal::get_LLVM_optimization_level(o)) +
278 "|";
279
280 return s;
281 }
282
283
284 namespace internal
285 {
295 template <typename ReturnType, typename T = void>
297
298
308 template <typename ReturnType, typename T = void>
310
311
312# ifdef HAVE_SYMENGINE_LLVM
322 template <typename ReturnType, typename T = void>
323 struct LLVMOptimizer;
324# endif // HAVE_SYMENGINE_LLVM
325
326
342 template <typename ReturnType, typename Optimizer, typename T = void>
344
345
346# ifndef DOXYGEN
347
348
349 /* ----------- Specializations for the Optimizers ----------- */
350
351
352 // A helper struct to type trait detection for the optimizers that
353 // will be defined next.
354 template <typename ReturnType_, typename T = void>
355 struct SupportedOptimizerTypeTraits
356 {
357 static const bool is_supported = false;
358
359 using ReturnType = void;
360 };
361
362
363
364 // Specialization for arithmetic types
365 template <typename ReturnType_>
366 struct SupportedOptimizerTypeTraits<
367 ReturnType_,
368 std::enable_if_t<std::is_arithmetic_v<ReturnType_>>>
369 {
370 static const bool is_supported = true;
371
372 using ReturnType =
373 std::conditional_t<std::is_same_v<ReturnType_, float>, float, double>;
374 };
375
376
377
378 // Specialization for complex arithmetic types
379 template <typename ReturnType_>
380 struct SupportedOptimizerTypeTraits<
381 ReturnType_,
382 std::enable_if_t<
383 boost::is_complex<ReturnType_>::value &&
384 std::is_arithmetic_v<typename ReturnType_::value_type>>>
385 {
386 static const bool is_supported = true;
387
388 using ReturnType =
389 std::conditional_t<std::is_same_v<ReturnType_, std::complex<float>>,
390 std::complex<float>,
391 std::complex<double>>;
392 };
393
394
395
396 template <typename ReturnType_>
397 struct DictionaryOptimizer<ReturnType_,
398 std::enable_if_t<SupportedOptimizerTypeTraits<
399 ReturnType_>::is_supported>>
400 {
401 using ReturnType =
402 typename SupportedOptimizerTypeTraits<ReturnType_>::ReturnType;
403 using OptimizerType =
404 internal::DictionarySubstitutionVisitor<ReturnType, SD::Expression>;
405
406
415 static void
416 initialize(OptimizerType &optimizer,
417 const SymEngine::vec_basic &independent_symbols,
418 const SymEngine::vec_basic &dependent_functions,
419 const enum OptimizationFlags &optimization_flags)
420 {
421 const bool use_symbolic_cse = use_symbolic_CSE(optimization_flags);
422 optimizer.init(independent_symbols,
423 dependent_functions,
424 use_symbolic_cse);
425 }
426
427
428
433 template <class Archive>
434 static void
435 save(Archive &archive,
436 const unsigned int version,
437 OptimizerType &optimizer)
438 {
439 optimizer.save(archive, version);
440 }
441
442
443
448 template <class Archive>
449 static void
450 load(Archive &archive,
451 const unsigned int version,
452 OptimizerType &optimizer,
453 const SymEngine::vec_basic & /*independent_symbols*/,
454 const SymEngine::vec_basic & /*dependent_functions*/,
455 const enum OptimizationFlags & /*optimization_flags*/)
456 {
457 optimizer.load(archive, version);
458 }
459
460
461
477 template <typename Stream>
478 static void
479 print(Stream &stream,
480 const OptimizerType &optimizer,
481 const bool print_independent_symbols = false,
482 const bool print_dependent_functions = false,
483 const bool print_cse_reductions = true)
484 {
485 optimizer.print(stream,
486 print_independent_symbols,
487 print_dependent_functions,
488 print_cse_reductions);
489 }
490 };
491
492
493
494 template <typename ReturnType_>
495 struct LambdaOptimizer<ReturnType_,
496 std::enable_if_t<SupportedOptimizerTypeTraits<
497 ReturnType_>::is_supported>>
498 {
499 using ReturnType =
500 std::conditional_t<!boost::is_complex<ReturnType_>::value,
501 double,
502 std::complex<double>>;
503 using OptimizerType =
504 std::conditional_t<!boost::is_complex<ReturnType_>::value,
505 SymEngine::LambdaRealDoubleVisitor,
506 SymEngine::LambdaComplexDoubleVisitor>;
507
508
517 static void
518 initialize(OptimizerType &optimizer,
519 const SymEngine::vec_basic &independent_symbols,
520 const SymEngine::vec_basic &dependent_functions,
521 const enum OptimizationFlags &optimization_flags)
522 {
523 const bool use_symbolic_cse = use_symbolic_CSE(optimization_flags);
524 optimizer.init(independent_symbols,
525 dependent_functions,
526 use_symbolic_cse);
527 }
528
529
530
535 template <class Archive>
536 static void
537 save(Archive & /*archive*/,
538 const unsigned int /*version*/,
539 OptimizerType & /*optimizer*/)
540 {}
541
542
547 template <class Archive>
548 static void
549 load(Archive & /*archive*/,
550 const unsigned int /*version*/,
551 OptimizerType &optimizer,
552 const SymEngine::vec_basic &independent_symbols,
553 const SymEngine::vec_basic &dependent_functions,
554 const enum OptimizationFlags &optimization_flags)
555 {
556 initialize(optimizer,
557 independent_symbols,
558 dependent_functions,
559 optimization_flags);
560 }
561
562
563
579 template <typename StreamType>
580 static void
581 print(StreamType & /*stream*/,
582 const OptimizerType & /*optimizer*/,
583 const bool /*print_independent_symbols*/ = false,
584 const bool /*print_dependent_functions*/ = false,
585 const bool /*print_cse_reductions*/ = true)
586 {
587 // No built-in print function
588 }
589 };
590
591
592
593# ifdef HAVE_SYMENGINE_LLVM
594 template <typename ReturnType_>
595 struct LLVMOptimizer<ReturnType_,
596 std::enable_if_t<std::is_arithmetic_v<ReturnType_>>>
597 {
598 using ReturnType =
599 std::conditional_t<std::is_same_v<ReturnType_, float>, float, double>;
600 using OptimizerType =
601 std::conditional_t<std::is_same_v<ReturnType_, float>,
602 SymEngine::LLVMFloatVisitor,
603 SymEngine::LLVMDoubleVisitor>;
604
609 static const bool supported_by_LLVM = true;
610
611
620 static void
621 initialize(OptimizerType &optimizer,
622 const SymEngine::vec_basic &independent_symbols,
623 const SymEngine::vec_basic &dependent_functions,
624 const enum OptimizationFlags &optimization_flags)
625 {
626 const int opt_level = get_LLVM_optimization_level(optimization_flags);
627 const bool use_symbolic_cse = use_symbolic_CSE(optimization_flags);
628 optimizer.init(independent_symbols,
629 dependent_functions,
630 use_symbolic_cse,
631 opt_level);
632 }
633
634
635
640 template <class Archive>
641 static void
642 save(Archive &archive,
643 const unsigned int /*version*/,
644 OptimizerType &optimizer)
645 {
646 const std::string llvm_compiled_function = optimizer.dumps();
647 archive & llvm_compiled_function;
648 }
649
650
651
656 template <class Archive>
657 static void
658 load(Archive &archive,
659 const unsigned int /*version*/,
660 OptimizerType &optimizer,
661 const SymEngine::vec_basic & /*independent_symbols*/,
662 const SymEngine::vec_basic & /*dependent_functions*/,
663 const enum OptimizationFlags & /*optimization_flags*/)
664 {
665 std::string llvm_compiled_function;
666 archive & llvm_compiled_function;
667 optimizer.loads(llvm_compiled_function);
668 }
669
670
671
687 template <typename StreamType>
688 static void
689 print(StreamType & /*stream*/,
690 const OptimizerType & /*optimizer*/,
691 const bool /*print_independent_symbols*/ = false,
692 const bool /*print_dependent_functions*/ = false,
693 const bool /*print_cse_reductions*/ = true)
694 {
695 // No built-in print function
696 }
697 };
698
699
700 // There is no LLVM optimizer built with complex number support.
701 // So we fall back to the LambdaDouble case as a type (required
702 // at compile time), but offer no implementation. We expect that
703 // the calling class does not create this type: This can be done by
704 // checking the `supported_by_LLVM` flag.
705 template <typename ReturnType_>
706 struct LLVMOptimizer<
707 ReturnType_,
708 std::enable_if_t<
709 boost::is_complex<ReturnType_>::value &&
710 std::is_arithmetic_v<typename ReturnType_::value_type>>>
711 {
712 // Since there is no working implementation, these are dummy types
713 // that help with templating in the calling function.
714 using ReturnType = typename LambdaOptimizer<ReturnType_>::ReturnType;
715 using OptimizerType =
716 typename LambdaOptimizer<ReturnType_>::OptimizerType;
717
722 static const bool supported_by_LLVM = false;
723
724
733 static void
734 initialize(OptimizerType & /*optimizer*/,
735 const SymEngine::vec_basic & /*independent_symbols*/,
736 const SymEngine::vec_basic & /*dependent_functions*/,
737 const enum OptimizationFlags & /*optimization_flags*/)
738 {
740 }
741
742
743
748 template <class Archive>
749 static void
750 save(Archive & /*archive*/,
751 const unsigned int /*version*/,
752 OptimizerType & /*optimizer*/)
753 {
755 }
756
757
758
763 template <class Archive>
764 static void
765 load(Archive & /*archive*/,
766 const unsigned int /*version*/,
767 OptimizerType & /*optimizer*/,
768 const SymEngine::vec_basic & /*independent_symbols*/,
769 const SymEngine::vec_basic & /*dependent_functions*/,
770 const enum OptimizationFlags & /*optimization_flags*/)
771 {
773 }
774
775
776
792 template <typename StreamType>
793 static void
794 print(StreamType & /*stream*/,
795 const OptimizerType & /*optimizer*/,
796 const bool /*print_independent_symbols*/ = false,
797 const bool /*print_dependent_functions*/ = false,
798 const bool /*print_cse_reductions*/ = true)
799 {
801 }
802 };
803# endif // HAVE_SYMENGINE_LLVM
804
805
806 /* ----------- Specializations for OptimizerHelper ----------- */
807
808
809 template <typename ReturnType, typename Optimizer>
810 struct OptimizerHelper<
811 ReturnType,
812 Optimizer,
813 std::enable_if_t<
814 std::is_same_v<ReturnType, typename Optimizer::ReturnType>>>
815 {
824 static void
825 initialize(typename Optimizer::OptimizerType *optimizer,
826 const SymEngine::vec_basic &independent_symbols,
827 const SymEngine::vec_basic &dependent_functions,
828 const enum OptimizationFlags &optimization_flags)
829 {
830 Assert(optimizer, ExcNotInitialized());
831
832 // Some optimizers don't have the same interface for
833 // initialization, we filter them out through the specializations
834 // of the Optimizer class
835 Optimizer::initialize(*optimizer,
836 independent_symbols,
837 dependent_functions,
838 optimization_flags);
839 }
840
841
842
856 static void
857 substitute(typename Optimizer::OptimizerType *optimizer,
858 std::vector<ReturnType> &output_values,
859 const std::vector<ReturnType> &substitution_values)
860 {
861 Assert(optimizer, ExcNotInitialized());
862 optimizer->call(output_values.data(), substitution_values.data());
863 }
864
865
866
871 template <class Archive>
872 static void
873 save(Archive &archive,
874 const unsigned int version,
875 typename Optimizer::OptimizerType *optimizer)
876 {
877 Assert(optimizer, ExcNotInitialized());
878
879 // Some optimizers don't have the same interface for
880 // serialization, we filter them out through the specializations
881 // of the Optimizer class
882 Optimizer::save(archive, version, *optimizer);
883 }
884
885
886
891 template <class Archive>
892 static void
893 load(Archive &archive,
894 const unsigned int version,
895 typename Optimizer::OptimizerType *optimizer,
896 const SymEngine::vec_basic &independent_symbols,
897 const SymEngine::vec_basic &dependent_functions,
898 const enum OptimizationFlags &optimization_flags)
899 {
900 Assert(optimizer, ExcNotInitialized());
901
902 // Some optimizers don't have the same interface for
903 // serialization, we filter them out through the specializations
904 // of the Optimizer class
905 Optimizer::load(archive,
906 version,
907 *optimizer,
908 independent_symbols,
909 dependent_functions,
910 optimization_flags);
911 }
912
913
914
930 template <typename Stream>
931 static void
932 print(Stream &stream,
933 typename Optimizer::OptimizerType *optimizer,
934 const bool print_independent_symbols = false,
935 const bool print_dependent_functions = false,
936 const bool print_cse_reductions = true)
937 {
938 Assert(optimizer, ExcNotInitialized());
939
940 // Some optimizers don't have a print function, so
941 // we filter them out through the specializations of
942 // the Optimizer class
943 Optimizer::print(stream,
944 *optimizer,
945 print_independent_symbols,
946 print_dependent_functions,
947 print_cse_reductions);
948 }
949 };
950
951 template <typename ReturnType, typename Optimizer>
952 struct OptimizerHelper<
953 ReturnType,
954 Optimizer,
955 std::enable_if_t<
956 !std::is_same_v<ReturnType, typename Optimizer::ReturnType>>>
957 {
966 static void
967 initialize(typename Optimizer::OptimizerType *optimizer,
968 const SymEngine::vec_basic &independent_symbols,
969 const SymEngine::vec_basic &dependent_functions,
970 const enum OptimizationFlags &optimization_flags)
971 {
972 Assert(optimizer, ExcNotInitialized());
973
974 const bool use_symbolic_cse = use_symbolic_CSE(optimization_flags);
975 optimizer->init(independent_symbols,
976 dependent_functions,
977 use_symbolic_cse);
978 }
979
980
981
995 static void
996 substitute(typename Optimizer::OptimizerType *optimizer,
997 std::vector<ReturnType> &output_values,
998 const std::vector<ReturnType> &substitution_values)
999 {
1000 Assert(optimizer, ExcNotInitialized());
1001
1002 // Intermediate values to accommodate the difference in
1003 // value types.
1004 std::vector<typename Optimizer::ReturnType> int_outputs(
1005 output_values.size());
1006 std::vector<typename Optimizer::ReturnType> int_inputs(
1007 substitution_values.size());
1008
1009 std::copy(substitution_values.begin(),
1010 substitution_values.end(),
1011 int_inputs.begin());
1012 optimizer->call(int_outputs.data(), int_inputs.data());
1013 std::copy(int_outputs.begin(),
1014 int_outputs.end(),
1015 output_values.begin());
1016 }
1017
1018
1019
1024 template <class Archive>
1025 static void
1026 save(Archive &archive,
1027 const unsigned int version,
1028 typename Optimizer::OptimizerType *optimizer)
1029 {
1030 Assert(optimizer, ExcNotInitialized());
1031 Optimizer::save(archive, version, *optimizer);
1032 }
1033
1034
1035
1040 template <class Archive>
1041 static void
1042 load(Archive &archive,
1043 const unsigned int version,
1044 typename Optimizer::OptimizerType *optimizer,
1045 const SymEngine::vec_basic &independent_symbols,
1046 const SymEngine::vec_basic &dependent_functions,
1047 const enum OptimizationFlags &optimization_flags)
1048 {
1049 Assert(optimizer, ExcNotInitialized());
1050
1051 // Some optimizers don't have the same interface for
1052 // serialization, we filter them out through the specializations
1053 // of the Optimizer class
1054 Optimizer::load(archive,
1055 version,
1056 *optimizer,
1057 independent_symbols,
1058 dependent_functions,
1059 optimization_flags);
1060 }
1061
1062
1063
1079 template <typename Stream>
1080 static void
1081 print(Stream &stream,
1082 typename Optimizer::OptimizerType *optimizer,
1083 const bool print_cse_reductions = true,
1084 const bool print_independent_symbols = false,
1085 const bool print_dependent_functions = false)
1086 {
1087 Assert(optimizer, ExcNotInitialized());
1088
1089 optimizer->print(stream,
1090 print_independent_symbols,
1091 print_dependent_functions,
1092 print_cse_reductions);
1093 }
1094 };
1095
1096# endif // DOXYGEN
1097
1098
1099 /* -------------------- Utility functions ---------------------- */
1100
1101
1123 template <typename NumberType,
1124 int rank,
1125 int dim,
1126 template <int, int, typename> class TensorType>
1127 TensorType<rank, dim, NumberType>
1129 const TensorType<rank, dim, Expression> &symbol_tensor,
1130 const std::vector<NumberType> &cached_evaluation,
1131 const BatchOptimizer<NumberType> &optimizer)
1132 {
1133 TensorType<rank, dim, NumberType> out;
1134 for (unsigned int i = 0; i < out.n_independent_components; ++i)
1135 {
1136 const TableIndices<rank> indices(
1137 out.unrolled_to_component_indices(i));
1138 out[indices] =
1139 optimizer.extract(symbol_tensor[indices], cached_evaluation);
1140 }
1141 return out;
1142 }
1143
1144
1167 template <typename NumberType, int dim>
1170 const SymmetricTensor<4, dim, Expression> &symbol_tensor,
1171 const std::vector<NumberType> &cached_evaluation,
1172 const BatchOptimizer<NumberType> &optimizer)
1173 {
1175 for (unsigned int i = 0;
1176 i < SymmetricTensor<2, dim>::n_independent_components;
1177 ++i)
1178 for (unsigned int j = 0;
1179 j < SymmetricTensor<2, dim>::n_independent_components;
1180 ++j)
1181 {
1182 const TableIndices<4> indices =
1183 make_rank_4_tensor_indices<dim>(i, j);
1184 out[indices] =
1185 optimizer.extract(symbol_tensor[indices], cached_evaluation);
1186 }
1187 return out;
1188 }
1189
1190
1208 template <typename NumberType, typename T>
1209 void
1211 const T &function)
1212 {
1213 optimizer.register_function(function);
1214 }
1215
1216
1234 template <typename NumberType, typename T>
1235 void
1237 const std::vector<T> &functions)
1238 {
1239 for (const auto &function : functions)
1240 register_functions(optimizer, function);
1241 }
1242
1243
1263 template <typename NumberType, typename T, typename... Args>
1264 void
1266 const T &function,
1267 const Args &...other_functions)
1268 {
1269 register_functions(optimizer, function);
1270 register_functions(optimizer, other_functions...);
1271 }
1272
1273
1285 template <int rank,
1286 int dim,
1287 template <int, int, typename> class TensorType>
1290 const TensorType<rank, dim, Expression> &symbol_tensor)
1291 {
1293 out.reserve(symbol_tensor.n_independent_components);
1294 for (unsigned int i = 0; i < symbol_tensor.n_independent_components;
1295 ++i)
1296 {
1297 const TableIndices<rank> indices(
1298 symbol_tensor.unrolled_to_component_indices(i));
1299 out.push_back(symbol_tensor[indices].get_RCP());
1300 }
1301 return out;
1302 }
1303
1304
1314 template <int dim>
1317 const SymmetricTensor<4, dim, Expression> &symbol_tensor)
1318 {
1320 out.reserve(symbol_tensor.n_independent_components);
1321 for (unsigned int i = 0;
1322 i < SymmetricTensor<2, dim>::n_independent_components;
1323 ++i)
1324 for (unsigned int j = 0;
1325 j < SymmetricTensor<2, dim>::n_independent_components;
1326 ++j)
1327 {
1328 const TableIndices<4> indices =
1329 make_rank_4_tensor_indices<dim>(i, j);
1330 out.push_back(symbol_tensor[indices].get_RCP());
1331 }
1332 return out;
1333 }
1334
1335 } // namespace internal
1336
1337
1338
1429 template <typename ReturnType>
1431 {
1432 public:
1441
1462
1472 BatchOptimizer(const BatchOptimizer &other);
1473
1477 BatchOptimizer(BatchOptimizer &&) noexcept = default;
1478
1482 ~BatchOptimizer() = default;
1483
1494 void
1495 copy_from(const BatchOptimizer &other);
1496
1506 template <typename Stream>
1507 void
1508 print(Stream &stream, const bool print_cse = false) const;
1509
1518 template <class Archive>
1519 void
1520 save(Archive &archive, const unsigned int version) const;
1521
1535 template <class Archive>
1536 void
1537 load(Archive &archive, const unsigned int version);
1538
1539# ifdef DOXYGEN
1561 template <class Archive>
1562 void
1563 serialize(Archive &archive, const unsigned int version);
1564# else
1565 // This macro defines the serialize() method that is compatible with
1566 // the templated save() and load() method that have been implemented.
1567 BOOST_SERIALIZATION_SPLIT_MEMBER()
1568# endif
1569
1580 void
1581 register_symbols(const types::substitution_map &substitution_map);
1582
1588 void
1589 register_symbols(const SymEngine::map_basic_basic &substitution_map);
1590
1601 void
1602 register_symbols(const types::symbol_vector &symbols);
1603
1614 void
1615 register_symbols(const SymEngine::vec_basic &symbols);
1616
1623
1629 std::size_t
1631
1643 void
1644 register_function(const Expression &function);
1645
1650 template <int rank, int dim>
1651 void
1653
1658 template <int rank, int dim>
1659 void
1661 const SymmetricTensor<rank, dim, Expression> &function_tensor);
1662
1667 void
1668 register_functions(const types::symbol_vector &functions);
1669
1674 void
1675 register_functions(const SymEngine::vec_basic &functions);
1676
1686 template <typename T>
1687 void
1688 register_functions(const std::vector<T> &functions);
1689
1703 template <typename T, typename... Args>
1704 void
1705 register_functions(const T &functions, const Args &...other_functions);
1706
1711 const types::symbol_vector &
1713
1720 std::size_t
1721 n_dependent_variables() const;
1722
1741 void
1745
1750 enum OptimizerType
1751 optimization_method() const;
1752
1758 optimization_flags() const;
1759
1765 bool
1766 use_symbolic_CSE() const;
1767
1783 void
1784 optimize();
1785
1790 bool
1791 optimized() const;
1792
1809 void
1810 substitute(const types::substitution_map &substitution_map) const;
1811
1821 void
1822 substitute(const SymEngine::map_basic_basic &substitution_map) const;
1823
1834 void
1835 substitute(const types::symbol_vector &symbols,
1836 const std::vector<ReturnType> &values) const;
1837
1848 void
1849 substitute(const SymEngine::vec_basic &symbols,
1850 const std::vector<ReturnType> &values) const;
1851
1857 bool
1858 values_substituted() const;
1859
1889 const std::vector<ReturnType> &
1890 evaluate() const;
1891
1899 ReturnType
1900 evaluate(const Expression &func) const;
1901
1910 std::vector<ReturnType>
1911 evaluate(const std::vector<Expression> &funcs) const;
1912
1921 template <int rank, int dim>
1924
1925
1934 template <int rank, int dim>
1937
1938
1946 ReturnType
1947 extract(const Expression &func,
1948 const std::vector<ReturnType> &cached_evaluation) const;
1949
1950
1958 std::vector<ReturnType>
1959 extract(const std::vector<Expression> &funcs,
1960 const std::vector<ReturnType> &cached_evaluation) const;
1961
1962
1970 template <int rank, int dim>
1973 const std::vector<ReturnType> &cached_evaluation) const;
1974
1975
1983 template <int rank, int dim>
1986 const std::vector<ReturnType> &cached_evaluation) const;
1987
1990 private:
1995
2001
2012
2019
2024 bool
2026 const SD::Expression &function) const;
2027
2032 bool
2034 const SymEngine::RCP<const SymEngine::Basic> &function) const;
2035
2050 mutable std::vector<ReturnType> dependent_variables_output;
2051
2061 std::map<SD::Expression,
2062 std::size_t,
2064
2070
2077 mutable std::unique_ptr<SymEngine::Visitor> optimizer;
2078
2088
2094
2098 void
2100
2105 void
2107
2111 void
2112 create_optimizer(std::unique_ptr<SymEngine::Visitor> &optimizer);
2113
2130 void
2131 substitute(const std::vector<ReturnType> &substitution_values) const;
2132 };
2133
2134
2135
2136 /* -------------------- inline and template functions ------------------ */
2137
2138
2139# ifndef DOXYGEN
2140
2141
2142 template <typename ReturnType>
2143 template <typename Stream>
2144 void
2145 BatchOptimizer<ReturnType>::print(Stream &stream,
2146 const bool /*print_cse*/) const
2147 {
2148 // Settings
2149 stream << "Method? " << optimization_method() << '\n';
2150 stream << "Flags: " << optimization_flags() << '\n';
2151 stream << "Optimized? " << (optimized() ? "Yes" : "No") << '\n';
2152 stream << "Values substituted? " << values_substituted() << "\n\n";
2153
2154 // Independent variables
2155 stream << "Symbols (" << n_independent_variables()
2156 << " independent variables):" << '\n';
2157 int cntr = 0;
2158 for (SD::types::substitution_map::const_iterator it =
2159 independent_variables_symbols.begin();
2160 it != independent_variables_symbols.end();
2161 ++it, ++cntr)
2162 {
2163 stream << cntr << ": " << it->first << '\n';
2164 }
2165 stream << '\n' << std::flush;
2166
2167 // Dependent functions
2168 stream << "Functions (" << n_dependent_variables()
2169 << " dependent variables):" << '\n';
2170 cntr = 0;
2171 for (typename SD::types::symbol_vector::const_iterator it =
2172 dependent_variables_functions.begin();
2173 it != dependent_variables_functions.end();
2174 ++it, ++cntr)
2175 {
2176 stream << cntr << ": " << (*it) << '\n';
2177 }
2178 stream << '\n' << std::flush;
2179
2180 // Common subexpression
2181 if (optimized() == true && use_symbolic_CSE() == true)
2182 {
2183 Assert(optimizer, ExcNotInitialized());
2184 const bool print_cse_reductions = true;
2185 const bool print_independent_symbols = false;
2186 const bool print_dependent_functions = false;
2187
2188 if (optimization_method() == OptimizerType::dictionary)
2189 {
2190 Assert(dynamic_cast<typename internal::DictionaryOptimizer<
2191 ReturnType>::OptimizerType *>(optimizer.get()),
2192 ExcMessage("Cannot cast optimizer to Dictionary type."));
2193
2194 internal::OptimizerHelper<
2195 ReturnType,
2196 internal::DictionaryOptimizer<ReturnType>>::
2197 print(stream,
2198 dynamic_cast<typename internal::DictionaryOptimizer<
2199 ReturnType>::OptimizerType *>(optimizer.get()),
2200 print_independent_symbols,
2201 print_dependent_functions,
2202 print_cse_reductions);
2203
2204 stream << '\n' << std::flush;
2205 }
2206 else if (optimization_method() == OptimizerType::lambda)
2207 {
2208 Assert(dynamic_cast<typename internal::LambdaOptimizer<
2209 ReturnType>::OptimizerType *>(optimizer.get()),
2210 ExcMessage("Cannot cast optimizer to Lambda type."));
2211
2212 internal::OptimizerHelper<ReturnType,
2213 internal::LambdaOptimizer<ReturnType>>::
2214 print(stream,
2215 dynamic_cast<typename internal::LambdaOptimizer<
2216 ReturnType>::OptimizerType *>(optimizer.get()),
2217 print_independent_symbols,
2218 print_dependent_functions,
2219 print_cse_reductions);
2220 }
2221# ifdef HAVE_SYMENGINE_LLVM
2222 else if (optimization_method() == OptimizerType::llvm)
2223 {
2224 Assert(dynamic_cast<typename internal::LLVMOptimizer<
2225 ReturnType>::OptimizerType *>(optimizer.get()),
2226 ExcMessage("Cannot cast optimizer to LLVM type."));
2227
2228 internal::OptimizerHelper<ReturnType,
2229 internal::LLVMOptimizer<ReturnType>>::
2230 print(stream,
2231 dynamic_cast<typename internal::LLVMOptimizer<
2232 ReturnType>::OptimizerType *>(optimizer.get()),
2233 print_independent_symbols,
2234 print_dependent_functions,
2235 print_cse_reductions);
2236 }
2237# endif // HAVE_SYMENGINE_LLVM
2238 else
2239 {
2240 AssertThrow(false, ExcMessage("Unknown optimizer type."));
2241 }
2242 }
2243
2244 if (values_substituted())
2245 {
2246 stream << "Evaluated functions:" << '\n';
2247 stream << std::flush;
2248 cntr = 0;
2249 for (typename std::vector<ReturnType>::const_iterator it =
2250 dependent_variables_output.begin();
2251 it != dependent_variables_output.end();
2252 ++it, ++cntr)
2253 {
2254 stream << cntr << ": " << (*it) << '\n';
2255 }
2256 stream << '\n' << std::flush;
2257 }
2258 }
2259
2260
2261
2262 template <typename ReturnType>
2263 template <class Archive>
2264 void
2266 const unsigned int version) const
2267 {
2268 // Serialize enum classes...
2269 {
2270 const auto m =
2271 static_cast<std::underlying_type_t<OptimizerType>>(method);
2272 ar & m;
2273 }
2274 {
2275 const auto f =
2276 static_cast<std::underlying_type_t<OptimizationFlags>>(flags);
2277 ar & f;
2278 }
2279
2280 // Important: Independent variables must always be
2281 // serialized before the dependent variables.
2282 ar & independent_variables_symbols;
2283 ar & dependent_variables_functions;
2284
2285 ar & dependent_variables_output;
2286 ar & map_dep_expr_vec_entry;
2287 ar & ready_for_value_extraction;
2288
2289 // Mark that we've saved this class at some point.
2290 has_been_serialized = true;
2291 ar & has_been_serialized;
2292
2293 // When we serialize the optimizer itself, we have to (unfortunately)
2294 // provide it with sufficient information to rebuild itself from scratch.
2295 // This is because only two of the three optimization classes support
2296 // real serialization (i.e. have save/load capability).
2297 const SD::types::symbol_vector symbol_vec =
2298 Utilities::extract_symbols(independent_variables_symbols);
2299 if (typename internal::DictionaryOptimizer<ReturnType>::OptimizerType
2300 *opt = dynamic_cast<typename internal::DictionaryOptimizer<
2301 ReturnType>::OptimizerType *>(optimizer.get()))
2302 {
2303 Assert(optimization_method() == OptimizerType::dictionary,
2305 internal::OptimizerHelper<
2306 ReturnType,
2307 internal::DictionaryOptimizer<ReturnType>>::save(ar, version, opt);
2308 }
2309 else if (typename internal::LambdaOptimizer<ReturnType>::OptimizerType
2310 *opt = dynamic_cast<typename internal::LambdaOptimizer<
2311 ReturnType>::OptimizerType *>(optimizer.get()))
2312 {
2313 Assert(optimization_method() == OptimizerType::lambda,
2315 internal::OptimizerHelper<
2316 ReturnType,
2317 internal::LambdaOptimizer<ReturnType>>::save(ar, version, opt);
2318 }
2319# ifdef HAVE_SYMENGINE_LLVM
2320 else if (typename internal::LLVMOptimizer<ReturnType>::OptimizerType
2321 *opt = dynamic_cast<typename internal::LLVMOptimizer<
2322 ReturnType>::OptimizerType *>(optimizer.get()))
2323 {
2324 Assert(optimization_method() == OptimizerType::llvm,
2326 internal::OptimizerHelper<
2327 ReturnType,
2328 internal::LLVMOptimizer<ReturnType>>::save(ar, version, opt);
2329 }
2330# endif
2331 else
2332 {
2333 AssertThrow(false, ExcMessage("Unknown optimizer type."));
2334 }
2335 }
2336
2337
2338
2339 template <typename ReturnType>
2340 template <class Archive>
2341 void
2342 BatchOptimizer<ReturnType>::load(Archive &ar, const unsigned int version)
2343 {
2344 Assert(independent_variables_symbols.empty(), ExcInternalError());
2345 Assert(dependent_variables_functions.empty(), ExcInternalError());
2346 Assert(dependent_variables_output.empty(), ExcInternalError());
2347 Assert(map_dep_expr_vec_entry.empty(), ExcInternalError());
2348 Assert(ready_for_value_extraction == false, ExcInternalError());
2349
2350 // Deserialize enum classes...
2351 {
2352 std::underlying_type_t<OptimizerType> m;
2353 ar & m;
2354 method = static_cast<OptimizerType>(m);
2355 }
2356 {
2357 std::underlying_type_t<OptimizationFlags> f;
2358 ar & f;
2359 flags = static_cast<OptimizationFlags>(f);
2360 }
2361
2362 // Important: Independent variables must always be
2363 // deserialized before the dependent variables.
2364 ar & independent_variables_symbols;
2365 ar & dependent_variables_functions;
2366
2367 ar & dependent_variables_output;
2368 ar & map_dep_expr_vec_entry;
2369 ar & ready_for_value_extraction;
2370
2371 ar & has_been_serialized;
2372
2373 // If we're reading in data, then create the optimizer
2374 // and then deserialize it.
2375 Assert(!optimizer, ExcInternalError());
2376
2377 // Create and configure the optimizer
2378 create_optimizer(optimizer);
2379 Assert(optimizer, ExcNotInitialized());
2380
2381 // When we deserialize the optimizer itself, we have to (unfortunately)
2382 // provide it with sufficient information to rebuild itself from scratch.
2383 // This is because only two of the three optimization classes support
2384 // real serialization (i.e. have save/load capability).
2385 const SD::types::symbol_vector symbol_vec =
2386 Utilities::extract_symbols(independent_variables_symbols);
2387 if (typename internal::DictionaryOptimizer<ReturnType>::OptimizerType
2388 *opt = dynamic_cast<typename internal::DictionaryOptimizer<
2389 ReturnType>::OptimizerType *>(optimizer.get()))
2390 {
2391 Assert(optimization_method() == OptimizerType::dictionary,
2393 internal::OptimizerHelper<ReturnType,
2394 internal::DictionaryOptimizer<ReturnType>>::
2395 load(ar,
2396 version,
2397 opt,
2399 symbol_vec),
2401 dependent_variables_functions),
2402 optimization_flags());
2403 }
2404 else if (typename internal::LambdaOptimizer<ReturnType>::OptimizerType
2405 *opt = dynamic_cast<typename internal::LambdaOptimizer<
2406 ReturnType>::OptimizerType *>(optimizer.get()))
2407 {
2408 Assert(optimization_method() == OptimizerType::lambda,
2410 internal::OptimizerHelper<ReturnType,
2411 internal::LambdaOptimizer<ReturnType>>::
2412 load(ar,
2413 version,
2414 opt,
2416 symbol_vec),
2418 dependent_variables_functions),
2419 optimization_flags());
2420 }
2421# ifdef HAVE_SYMENGINE_LLVM
2422 else if (typename internal::LLVMOptimizer<ReturnType>::OptimizerType
2423 *opt = dynamic_cast<typename internal::LLVMOptimizer<
2424 ReturnType>::OptimizerType *>(optimizer.get()))
2425 {
2426 Assert(optimization_method() == OptimizerType::llvm,
2428 internal::OptimizerHelper<ReturnType,
2429 internal::LLVMOptimizer<ReturnType>>::
2430 load(ar,
2431 version,
2432 opt,
2434 symbol_vec),
2436 dependent_variables_functions),
2437 optimization_flags());
2438 }
2439# endif
2440 else
2441 {
2442 AssertThrow(false, ExcMessage("Unknown optimizer type."));
2443 }
2444 }
2445
2446
2447
2448 template <typename ReturnType>
2449 template <int rank, int dim>
2450 void
2452 const Tensor<rank, dim, Expression> &function_tensor)
2453 {
2454 Assert(optimized() == false,
2455 ExcMessage(
2456 "Cannot register functions once the optimizer is finalised."));
2457
2458 register_vector_functions(
2459 internal::unroll_to_expression_vector(function_tensor));
2460 }
2461
2462
2463
2464 template <typename ReturnType>
2465 template <int rank, int dim>
2466 void
2468 const SymmetricTensor<rank, dim, Expression> &function_tensor)
2469 {
2470 Assert(optimized() == false,
2471 ExcMessage(
2472 "Cannot register functions once the optimizer is finalised."));
2473
2474 register_vector_functions(
2475 internal::unroll_to_expression_vector(function_tensor));
2476 }
2477
2478
2479
2480 template <typename ReturnType>
2481 template <typename T, typename... Args>
2482 void
2484 const T &functions,
2485 const Args &...other_functions)
2486 {
2487 internal::register_functions(*this, functions);
2488 internal::register_functions(*this, other_functions...);
2489 }
2490
2491
2492
2493 template <typename ReturnType>
2494 template <typename T>
2495 void
2497 const std::vector<T> &functions)
2498 {
2499 internal::register_functions(*this, functions);
2500 }
2501
2502
2503
2504 template <typename ReturnType>
2505 template <int rank, int dim>
2508 const Tensor<rank, dim, Expression> &funcs,
2509 const std::vector<ReturnType> &cached_evaluation) const
2510 {
2512 cached_evaluation,
2513 *this);
2514 }
2515
2516
2517
2518 template <typename ReturnType>
2519 template <int rank, int dim>
2522 const Tensor<rank, dim, Expression> &funcs) const
2523 {
2524 Assert(
2525 values_substituted() == true,
2526 ExcMessage(
2527 "The optimizer is not configured to perform evaluation. "
2528 "This action can only performed after substitute() has been called."));
2529
2530 return extract(funcs, dependent_variables_output);
2531 }
2532
2533
2534
2535 template <typename ReturnType>
2536 template <int rank, int dim>
2540 const std::vector<ReturnType> &cached_evaluation) const
2541 {
2543 cached_evaluation,
2544 *this);
2545 }
2546
2547
2548
2549 template <typename ReturnType>
2550 template <int rank, int dim>
2553 const SymmetricTensor<rank, dim, Expression> &funcs) const
2554 {
2555 Assert(
2556 values_substituted() == true,
2557 ExcMessage(
2558 "The optimizer is not configured to perform evaluation. "
2559 "This action can only performed after substitute() has been called."));
2560
2561 return extract(funcs, dependent_variables_output);
2562 }
2563
2564# endif // DOXYGEN
2565
2566 } // namespace SD
2567} // namespace Differentiation
2568
2569#endif // DEAL_II_WITH_SYMENGINE
2570
2572
2573#endif
SymmetricTensor< rank, dim, ReturnType > extract(const SymmetricTensor< rank, dim, Expression > &funcs, const std::vector< ReturnType > &cached_evaluation) const
types::substitution_map independent_variables_symbols
void substitute(const types::substitution_map &substitution_map) const
void register_functions(const T &functions, const Args &...other_functions)
void register_scalar_function(const SD::Expression &function)
const types::symbol_vector & get_dependent_functions() const
void create_optimizer(std::unique_ptr< SymEngine::Visitor > &optimizer)
void print(Stream &stream, const bool print_cse=false) const
enum OptimizerType optimization_method() const
void copy_from(const BatchOptimizer &other)
void register_function(const Tensor< rank, dim, Expression > &function_tensor)
void set_optimization_method(const enum OptimizerType &optimization_method, const enum OptimizationFlags &optimization_flags=OptimizationFlags::optimize_all)
SymmetricTensor< rank, dim, ReturnType > evaluate(const SymmetricTensor< rank, dim, Expression > &funcs) const
void save(Archive &archive, const unsigned int version) const
enum OptimizationFlags optimization_flags() const
void register_functions(const types::symbol_vector &functions)
std::vector< ReturnType > dependent_variables_output
Tensor< rank, dim, ReturnType > extract(const Tensor< rank, dim, Expression > &funcs, const std::vector< ReturnType > &cached_evaluation) const
void serialize(Archive &archive, const unsigned int version)
void register_symbols(const types::substitution_map &substitution_map)
const std::vector< ReturnType > & evaluate() const
std::map< SD::Expression, std::size_t, SD::types::internal::ExpressionKeyLess > map_dependent_expression_to_vector_entry_t
void register_function(const Expression &function)
Tensor< rank, dim, ReturnType > evaluate(const Tensor< rank, dim, Expression > &funcs) const
std::unique_ptr< SymEngine::Visitor > optimizer
ReturnType extract(const Expression &func, const std::vector< ReturnType > &cached_evaluation) const
BatchOptimizer(BatchOptimizer &&) noexcept=default
void load(Archive &archive, const unsigned int version)
void register_functions(const std::vector< T > &functions)
bool is_valid_nonunique_dependent_variable(const SD::Expression &function) const
void register_vector_functions(const types::symbol_vector &functions)
types::symbol_vector get_independent_symbols() const
void register_function(const SymmetricTensor< rank, dim, Expression > &function_tensor)
map_dependent_expression_to_vector_entry_t map_dep_expr_vec_entry
static constexpr unsigned int n_independent_components
#define DEAL_II_NAMESPACE_OPEN
Definition config.h:38
#define DEAL_II_NAMESPACE_CLOSE
Definition config.h:39
static ::ExceptionBase & ExcNotImplemented()
#define Assert(cond, exc)
static ::ExceptionBase & ExcSymEngineLLVMReturnTypeNotSupported()
#define DeclExceptionMsg(Exception, defaulttext)
static ::ExceptionBase & ExcSymEngineLLVMNotAvailable()
static ::ExceptionBase & ExcInternalError()
static ::ExceptionBase & ExcNotInitialized()
static ::ExceptionBase & ExcMessage(std::string arg1)
#define AssertThrow(cond, exc)
SD::types::symbol_vector extract_symbols(const SD::types::substitution_map &substitution_values)
SymEngine::vec_basic convert_expression_vector_to_basic_vector(const SD::types::symbol_vector &symbol_vector)
TensorType< rank, dim, NumberType > tensor_evaluate_optimized(const TensorType< rank, dim, Expression > &symbol_tensor, const std::vector< NumberType > &cached_evaluation, const BatchOptimizer< NumberType > &optimizer)
bool use_symbolic_CSE(const enum OptimizationFlags &flags)
types::symbol_vector unroll_to_expression_vector(const TensorType< rank, dim, Expression > &symbol_tensor)
int get_LLVM_optimization_level(const enum OptimizationFlags &flags)
void register_functions(BatchOptimizer< NumberType > &optimizer, const T &function)
std::vector< SD::Expression > symbol_vector
std::map< SD::Expression, SD::Expression, internal::ExpressionKeyLess > substitution_map
OptimizationFlags & operator|=(OptimizationFlags &f1, const OptimizationFlags f2)
Expression operator|(const Expression &lhs, const Expression &rhs)
Expression operator&(const Expression &lhs, const Expression &rhs)
Expression substitute(const Expression &expression, const types::substitution_map &substitution_map)
std::ostream & operator<<(std::ostream &stream, const Expression &expression)
OptimizationFlags & operator&=(OptimizationFlags &f1, const OptimizationFlags f2)
constexpr char T
constexpr ReturnType< rank, T >::value_type & extract(T &t, const ArrayType &indices)
void load(Archive &ar, ::std_cxx26::inplace_vector< T, N > &vec, const unsigned int)
void save(Archive &ar, const ::std_cxx26::inplace_vector< T, N > &vec, const unsigned int)
STL namespace.