16#ifndef dealii_differentiation_sd_symengine_optimizer_h
17#define dealii_differentiation_sd_symengine_optimizer_h
21#ifdef DEAL_II_WITH_SYMENGINE
25# include <symengine/basic.h>
26# include <symengine/dict.h>
27# include <symengine/symengine_exception.h>
28# include <symengine/symengine_rcp.h>
31# include <symengine/lambda_double.h>
32# include <symengine/visitor.h>
33# ifdef HAVE_SYMENGINE_LLVM
34# include <symengine/llvm_double.h>
48# include <boost/serialization/split_member.hpp>
49# include <boost/type_traits.hpp>
54# include <type_traits>
76 "SymEngine has not been built with LLVM support.");
83 "The SymEngine LLVM optimizer does not (yet) support the "
84 "selected return type.");
90 template <
typename ReturnType>
121 template <
class StreamType>
183 static_cast<unsigned int>(f2));
215 static_cast<unsigned int>(f2));
261 const bool use_agg_opt =
263 const int opt_level = (use_agg_opt ? 3 : 2);
273 template <
class StreamType>
277 s <<
" OptimizationFlags|";
302 template <
typename ReturnType,
typename T =
void>
315 template <
typename ReturnType,
typename T =
void>
319# ifdef HAVE_SYMENGINE_LLVM
329 template <
typename ReturnType,
typename T =
void>
330 struct LLVMOptimizer;
349 template <
typename ReturnType,
typename Optimizer,
typename T =
void>
361 template <
typename ReturnType_,
typename T =
void>
362 struct SupportedOptimizerTypeTraits
364 static const bool is_supported =
false;
366 using ReturnType = void;
372 template <
typename ReturnType_>
373 struct SupportedOptimizerTypeTraits<
375 typename
std::enable_if<std::is_arithmetic<ReturnType_>::value>::type>
377 static const bool is_supported =
true;
380 typename std::conditional<std::is_same<ReturnType_, float>::value,
388 template <
typename ReturnType_>
389 struct SupportedOptimizerTypeTraits<
391 typename
std::enable_if<
392 boost::is_complex<ReturnType_>::value &&
393 std::is_arithmetic<typename ReturnType_::value_type>::value>::type>
395 static const bool is_supported =
true;
397 using ReturnType =
typename std::conditional<
398 std::is_same<ReturnType_, std::complex<float>>::value,
400 std::complex<double>>::type;
405 template <
typename ReturnType_>
406 struct DictionaryOptimizer<
408 typename
std::enable_if<
409 SupportedOptimizerTypeTraits<ReturnType_>::is_supported>::type>
412 typename SupportedOptimizerTypeTraits<ReturnType_>::ReturnType;
414 internal::DictionarySubstitutionVisitor<ReturnType, SD::Expression>;
427 const SymEngine::vec_basic & independent_symbols,
428 const SymEngine::vec_basic & dependent_functions,
432 optimizer.init(independent_symbols,
443 template <
class Archive>
445 save(Archive & archive,
446 const unsigned int version,
449 optimizer.save(archive, version);
458 template <
class Archive>
460 load(Archive & archive,
461 const unsigned int version,
463 const SymEngine::vec_basic & ,
464 const SymEngine::vec_basic & ,
467 optimizer.load(archive, version);
487 template <
typename Stream>
489 print(Stream & stream,
491 const bool print_independent_symbols =
false,
492 const bool print_dependent_functions =
false,
493 const bool print_cse_reductions =
true)
495 optimizer.print(stream,
496 print_independent_symbols,
497 print_dependent_functions,
498 print_cse_reductions);
504 template <
typename ReturnType_>
505 struct LambdaOptimizer<
507 typename
std::enable_if<
508 SupportedOptimizerTypeTraits<ReturnType_>::is_supported>::type>
511 typename std::conditional<!boost::is_complex<ReturnType_>::value,
513 std::complex<double>>::type;
515 !boost::is_complex<ReturnType_>::value,
516 SymEngine::LambdaRealDoubleVisitor,
517 SymEngine::LambdaComplexDoubleVisitor>::type;
530 const SymEngine::vec_basic & independent_symbols,
531 const SymEngine::vec_basic & dependent_functions,
535 optimizer.init(independent_symbols,
546 template <
class Archive>
558 template <
class Archive>
563 const SymEngine::vec_basic & independent_symbols,
564 const SymEngine::vec_basic & dependent_functions,
567 initialize(optimizer,
590 template <
typename StreamType>
604# ifdef HAVE_SYMENGINE_LLVM
605 template <
typename ReturnType_>
606 struct LLVMOptimizer<
608 typename
std::enable_if<std::is_arithmetic<ReturnType_>::value>::type>
611 typename std::conditional<std::is_same<ReturnType_, float>::value,
615 typename std::conditional<std::is_same<ReturnType_, float>::value,
616 SymEngine::LLVMFloatVisitor,
617 SymEngine::LLVMDoubleVisitor>::type;
623 static const bool supported_by_LLVM =
true;
636 const SymEngine::vec_basic & independent_symbols,
637 const SymEngine::vec_basic & dependent_functions,
642 optimizer.init(independent_symbols,
654 template <
class Archive>
656 save(Archive &archive,
660 const std::string llvm_compiled_function = optimizer.dumps();
661 archive & llvm_compiled_function;
670 template <
class Archive>
672 load(Archive &archive,
675 const SymEngine::vec_basic & ,
676 const SymEngine::vec_basic & ,
679 std::string llvm_compiled_function;
680 archive & llvm_compiled_function;
681 optimizer.loads(llvm_compiled_function);
701 template <
typename StreamType>
719 template <
typename ReturnType_>
720 struct LLVMOptimizer<
722 typename
std::enable_if<
723 boost::is_complex<ReturnType_>::value &&
724 std::is_arithmetic<typename ReturnType_::value_type>::value>::type>
728 using ReturnType =
typename LambdaOptimizer<ReturnType_>::ReturnType;
736 static const bool supported_by_LLVM =
false;
749 const SymEngine::vec_basic & ,
750 const SymEngine::vec_basic & ,
762 template <
class Archive>
777 template <
class Archive>
782 const SymEngine::vec_basic & ,
783 const SymEngine::vec_basic & ,
806 template <
typename StreamType>
823 template <
typename ReturnType,
typename Optimizer>
824 struct OptimizerHelper<ReturnType,
826 typename
std::enable_if<std::is_same<
828 typename Optimizer::ReturnType>::value>::type>
840 const SymEngine::vec_basic & independent_symbols,
841 const SymEngine::vec_basic & dependent_functions,
849 Optimizer::initialize(*optimizer,
872 std::vector<ReturnType> & output_values,
873 const std::vector<ReturnType> & substitution_values)
876 optimizer->call(output_values.data(), substitution_values.data());
885 template <
class Archive>
887 save(Archive & archive,
888 const unsigned int version,
896 Optimizer::save(archive, version, *optimizer);
905 template <
class Archive>
907 load(Archive & archive,
908 const unsigned int version,
910 const SymEngine::vec_basic & independent_symbols,
911 const SymEngine::vec_basic & dependent_functions,
919 Optimizer::load(archive,
944 template <
typename Stream>
946 print(Stream & stream,
948 const bool print_independent_symbols =
false,
949 const bool print_dependent_functions =
false,
950 const bool print_cse_reductions =
true)
957 Optimizer::print(stream,
959 print_independent_symbols,
960 print_dependent_functions,
961 print_cse_reductions);
965 template <
typename ReturnType,
typename Optimizer>
966 struct OptimizerHelper<ReturnType,
968 typename
std::enable_if<!std::is_same<
970 typename Optimizer::ReturnType>::value>::type>
982 const SymEngine::vec_basic & independent_symbols,
983 const SymEngine::vec_basic & dependent_functions,
989 optimizer->init(independent_symbols,
1011 std::vector<ReturnType> & output_values,
1012 const std::vector<ReturnType> & substitution_values)
1018 std::vector<typename Optimizer::ReturnType> int_outputs(
1019 output_values.size());
1020 std::vector<typename Optimizer::ReturnType> int_inputs(
1021 substitution_values.size());
1024 substitution_values.end(),
1025 int_inputs.begin());
1026 optimizer->call(int_outputs.data(), int_inputs.data());
1029 output_values.begin());
1038 template <
class Archive>
1040 save(Archive & archive,
1041 const unsigned int version,
1045 Optimizer::save(archive, version, *optimizer);
1054 template <
class Archive>
1056 load(Archive & archive,
1057 const unsigned int version,
1059 const SymEngine::vec_basic & independent_symbols,
1060 const SymEngine::vec_basic & dependent_functions,
1068 Optimizer::load(archive,
1071 independent_symbols,
1072 dependent_functions,
1073 optimization_flags);
1093 template <
typename Stream>
1095 print(Stream & stream,
1097 const bool print_cse_reductions =
true,
1098 const bool print_independent_symbols =
false,
1099 const bool print_dependent_functions =
false)
1103 optimizer->print(stream,
1104 print_independent_symbols,
1105 print_dependent_functions,
1106 print_cse_reductions);
1137 template <
typename NumberType,
1140 template <
int,
int,
typename>
class TensorType>
1141 TensorType<rank, dim, NumberType>
1143 const TensorType<rank, dim, Expression> &symbol_tensor,
1144 const std::vector<NumberType> & cached_evaluation,
1147 TensorType<rank, dim, NumberType> out;
1148 for (
unsigned int i = 0; i < out.n_independent_components; ++i)
1151 out.unrolled_to_component_indices(i));
1153 optimizer.
extract(symbol_tensor[indices], cached_evaluation);
1181 template <
typename NumberType,
int dim>
1185 const std::vector<NumberType> & cached_evaluation,
1189 for (
unsigned int i = 0;
1190 i < SymmetricTensor<2, dim>::n_independent_components;
1192 for (
unsigned int j = 0;
1193 j < SymmetricTensor<2, dim>::n_independent_components;
1197 make_rank_4_tensor_indices<dim>(i, j);
1199 optimizer.
extract(symbol_tensor[indices], cached_evaluation);
1222 template <
typename NumberType,
typename T>
1248 template <
typename NumberType,
typename T>
1277 template <
typename NumberType,
typename T,
typename... Args>
1281 const Args &... other_functions)
1301 template <
int,
int,
typename>
class TensorType>
1304 const TensorType<rank, dim, Expression> &symbol_tensor)
1307 out.reserve(symbol_tensor.n_independent_components);
1308 for (
unsigned int i = 0; i < symbol_tensor.n_independent_components;
1312 symbol_tensor.unrolled_to_component_indices(i));
1313 out.push_back(symbol_tensor[indices].get_RCP());
1335 for (
unsigned int i = 0;
1336 i < SymmetricTensor<2, dim>::n_independent_components;
1338 for (
unsigned int j = 0;
1339 j < SymmetricTensor<2, dim>::n_independent_components;
1343 make_rank_4_tensor_indices<dim>(i, j);
1344 out.push_back(symbol_tensor[indices].get_RCP());
1443 template <
typename ReturnType>
1508 template <
typename Stream>
1510 print(Stream &stream,
const bool print_cse =
false)
const;
1520 template <
class Archive>
1522 save(Archive &archive,
const unsigned int version)
const;
1537 template <
class Archive>
1539 load(Archive &archive,
const unsigned int version);
1563 template <
class Archive>
1569 BOOST_SERIALIZATION_SPLIT_MEMBER()
1652 template <
int rank,
int dim>
1660 template <
int rank,
int dim>
1688 template <
typename T>
1705 template <
typename T,
typename... Args>
1838 const std::vector<ReturnType> &
values)
const;
1851 substitute(
const SymEngine::vec_basic & symbols,
1852 const std::vector<ReturnType> &
values)
const;
1891 const std::vector<ReturnType> &
1912 std::vector<ReturnType>
1913 evaluate(
const std::vector<Expression> &funcs)
const;
1923 template <
int rank,
int dim>
1936 template <
int rank,
int dim>
1950 const std::vector<ReturnType> &cached_evaluation)
const;
1960 std::vector<ReturnType>
1961 extract(
const std::vector<Expression> &funcs,
1962 const std::vector<ReturnType> &cached_evaluation)
const;
1972 template <
int rank,
int dim>
1975 const std::vector<ReturnType> & cached_evaluation)
const;
1985 template <
int rank,
int dim>
1988 const std::vector<ReturnType> &cached_evaluation)
const;
2036 const SymEngine::RCP<const SymEngine::Basic> &function)
const;
2133 substitute(
const std::vector<ReturnType> &substitution_values)
const;
2144 template <
typename ReturnType>
2145 template <
typename Stream>
2151 stream <<
"Method? " << optimization_method() <<
"\n";
2152 stream <<
"Flags: " << optimization_flags() <<
"\n";
2153 stream <<
"Optimized? " << (optimized() ?
"Yes" :
"No") <<
"\n";
2154 stream <<
"Values substituted? " << values_substituted() <<
"\n\n";
2157 stream <<
"Symbols (" << n_independent_variables()
2158 <<
" independent variables):"
2161 for (SD::types::substitution_map::const_iterator it =
2162 independent_variables_symbols.begin();
2163 it != independent_variables_symbols.end();
2166 stream << cntr <<
": " << it->first <<
"\n";
2168 stream <<
"\n" << std::flush;
2171 stream <<
"Functions (" << n_dependent_variables()
2172 <<
" dependent variables):"
2175 for (
typename SD::types::symbol_vector::const_iterator it =
2176 dependent_variables_functions.begin();
2177 it != dependent_variables_functions.end();
2180 stream << cntr <<
": " << (*it) <<
"\n";
2182 stream <<
"\n" << std::flush;
2188 const bool print_cse_reductions =
true;
2189 const bool print_independent_symbols =
false;
2190 const bool print_dependent_functions =
false;
2194 Assert(
dynamic_cast<typename internal::DictionaryOptimizer<
2196 ExcMessage(
"Cannot cast optimizer to Dictionary type."));
2198 internal::OptimizerHelper<
2200 internal::DictionaryOptimizer<ReturnType>>::
2202 dynamic_cast<typename internal::DictionaryOptimizer<
2204 print_independent_symbols,
2205 print_dependent_functions,
2206 print_cse_reductions);
2208 stream <<
"\n" << std::flush;
2212 Assert(
dynamic_cast<typename internal::LambdaOptimizer<
2214 ExcMessage(
"Cannot cast optimizer to Lambda type."));
2216 internal::OptimizerHelper<ReturnType,
2217 internal::LambdaOptimizer<ReturnType>>::
2219 dynamic_cast<typename internal::LambdaOptimizer<
2221 print_independent_symbols,
2222 print_dependent_functions,
2223 print_cse_reductions);
2225# ifdef HAVE_SYMENGINE_LLVM
2228 Assert(
dynamic_cast<typename internal::LLVMOptimizer<
2230 ExcMessage(
"Cannot cast optimizer to LLVM type."));
2232 internal::OptimizerHelper<ReturnType,
2233 internal::LLVMOptimizer<ReturnType>>::
2235 dynamic_cast<typename internal::LLVMOptimizer<
2237 print_independent_symbols,
2238 print_dependent_functions,
2239 print_cse_reductions);
2248 if (values_substituted())
2250 stream <<
"Evaluated functions:"
2252 stream << std::flush;
2254 for (
typename std::vector<ReturnType>::const_iterator it =
2255 dependent_variables_output.begin();
2256 it != dependent_variables_output.end();
2259 stream << cntr <<
": " << (*it) <<
"\n";
2261 stream <<
"\n" << std::flush;
2267 template <
typename ReturnType>
2268 template <
class Archive>
2271 const unsigned int version)
const
2276 static_cast<typename std::underlying_type<OptimizerType>::type
>(
2282 static_cast<typename std::underlying_type<OptimizationFlags>::type
>(
2289 ar &independent_variables_symbols;
2290 ar &dependent_variables_functions;
2292 ar &dependent_variables_output;
2293 ar &map_dep_expr_vec_entry;
2294 ar &ready_for_value_extraction;
2297 has_been_serialized =
true;
2298 ar &has_been_serialized;
2307 *opt =
dynamic_cast<typename internal::DictionaryOptimizer<
2312 internal::OptimizerHelper<
2314 internal::DictionaryOptimizer<ReturnType>>::save(ar, version, opt);
2317 *opt =
dynamic_cast<typename internal::LambdaOptimizer<
2322 internal::OptimizerHelper<
2324 internal::LambdaOptimizer<ReturnType>>::save(ar, version, opt);
2326# ifdef HAVE_SYMENGINE_LLVM
2328 *opt =
dynamic_cast<typename internal::LLVMOptimizer<
2333 internal::OptimizerHelper<
2335 internal::LLVMOptimizer<ReturnType>>::save(ar, version, opt);
2346 template <
typename ReturnType>
2347 template <
class Archive>
2359 typename std::underlying_type<OptimizerType>::type m;
2364 typename std::underlying_type<OptimizationFlags>::type f;
2371 ar &independent_variables_symbols;
2372 ar &dependent_variables_functions;
2374 ar &dependent_variables_output;
2375 ar &map_dep_expr_vec_entry;
2376 ar &ready_for_value_extraction;
2378 ar &has_been_serialized;
2385 create_optimizer(optimizer);
2395 *opt =
dynamic_cast<typename internal::DictionaryOptimizer<
2400 internal::OptimizerHelper<ReturnType,
2401 internal::DictionaryOptimizer<ReturnType>>::
2408 dependent_variables_functions),
2409 optimization_flags());
2412 *opt =
dynamic_cast<typename internal::LambdaOptimizer<
2417 internal::OptimizerHelper<ReturnType,
2418 internal::LambdaOptimizer<ReturnType>>::
2425 dependent_variables_functions),
2426 optimization_flags());
2428# ifdef HAVE_SYMENGINE_LLVM
2430 *opt =
dynamic_cast<typename internal::LLVMOptimizer<
2435 internal::OptimizerHelper<ReturnType,
2436 internal::LLVMOptimizer<ReturnType>>::
2443 dependent_variables_functions),
2444 optimization_flags());
2455 template <
typename ReturnType>
2456 template <
int rank,
int dim>
2461 Assert(optimized() ==
false,
2463 "Cannot register functions once the optimizer is finalised."));
2465 register_vector_functions(
2471 template <
typename ReturnType>
2472 template <
int rank,
int dim>
2477 Assert(optimized() ==
false,
2479 "Cannot register functions once the optimizer is finalised."));
2481 register_vector_functions(
2487 template <
typename ReturnType>
2488 template <
typename T,
typename... Args>
2492 const Args &... other_functions)
2500 template <
typename ReturnType>
2501 template <
typename T>
2511 template <
typename ReturnType>
2512 template <
int rank,
int dim>
2516 const std::vector<ReturnType> & cached_evaluation)
const
2519 values_substituted() ==
true,
2521 "The optimizer is not configured to perform evaluation. "
2522 "This action can only performed after substitute() has been called."));
2531 template <
typename ReturnType>
2532 template <
int rank,
int dim>
2537 return extract(funcs, dependent_variables_output);
2542 template <
typename ReturnType>
2543 template <
int rank,
int dim>
2547 const std::vector<ReturnType> & cached_evaluation)
const
2550 values_substituted() ==
true,
2552 "The optimizer is not configured to perform evaluation. "
2553 "This action can only performed after substitute() has been called."));
2562 template <
typename ReturnType>
2563 template <
int rank,
int dim>
2568 return extract(funcs, dependent_variables_output);
static constexpr unsigned int n_independent_components
#define DEAL_II_NAMESPACE_OPEN
#define DEAL_II_DISABLE_EXTRA_DIAGNOSTICS
#define DEAL_II_NAMESPACE_CLOSE
#define DEAL_II_ENABLE_EXTRA_DIAGNOSTICS
SymmetricTensor< rank, dim, ReturnType > extract(const SymmetricTensor< rank, dim, Expression > &funcs, const std::vector< ReturnType > &cached_evaluation) const
bool use_symbolic_CSE() const
types::substitution_map independent_variables_symbols
types::symbol_vector dependent_variables_functions
void substitute(const types::substitution_map &substitution_map) const
enum OptimizationFlags flags
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)
bool ready_for_value_extraction
void print(Stream &stream, const bool print_cse=false) const
TensorType< rank, dim, NumberType > tensor_evaluate_optimized(const TensorType< rank, dim, Expression > &symbol_tensor, const std::vector< NumberType > &cached_evaluation, const BatchOptimizer< NumberType > &optimizer)
enum OptimizerType optimization_method() const
void register_functions(const T &functions, const Args &... other_functions)
void register_function(const Tensor< rank, dim, Expression > &function_tensor)
static ::ExceptionBase & ExcNotImplemented()
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
OptimizationFlags & operator|=(OptimizationFlags &f1, const OptimizationFlags f2)
void save(Archive &archive, const unsigned int version) const
bool use_symbolic_CSE(const enum OptimizationFlags &flags)
enum OptimizationFlags optimization_flags() const
types::symbol_vector unroll_to_expression_vector(const TensorType< rank, dim, Expression > &symbol_tensor)
#define Assert(cond, exc)
std::string to_string(const T &t)
void register_functions(const types::symbol_vector &functions)
BatchOptimizer(BatchOptimizer &&)=default
std::vector< ReturnType > dependent_variables_output
static ::ExceptionBase & ExcSymEngineLLVMReturnTypeNotSupported()
~BatchOptimizer()=default
Expression operator|(const Expression &lhs, const Expression &rhs)
enum OptimizerType method
int get_LLVM_optimization_level(const enum OptimizationFlags &flags)
Tensor< rank, dim, ReturnType > extract(const Tensor< rank, dim, Expression > &funcs, const std::vector< ReturnType > &cached_evaluation) const
std::size_t n_dependent_variables() const
void serialize(Archive &archive, const unsigned int version)
#define DeclExceptionMsg(Exception, defaulttext)
void register_symbols(const types::substitution_map &substitution_map)
const std::vector< ReturnType > & evaluate() const
static ::ExceptionBase & ExcSymEngineLLVMNotAvailable()
static ::ExceptionBase & ExcInternalError()
std::map< SD::Expression, std::size_t, SD::types::internal::ExpressionKeyLess > map_dependent_expression_to_vector_entry_t
Expression operator&(const Expression &lhs, const Expression &rhs)
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
static ::ExceptionBase & ExcNotInitialized()
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)
void register_functions(BatchOptimizer< NumberType > &optimizer, const T &function)
std::ostream & operator<<(std::ostream &stream, const Expression &expression)
static ::ExceptionBase & ExcMessage(std::string arg1)
std::size_t n_independent_variables() const
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
OptimizationFlags & operator&=(OptimizationFlags &f1, const OptimizationFlags f2)
#define AssertThrow(cond, exc)
bool values_substituted() const
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)
std::vector< SD::Expression > symbol_vector
std::map< SD::Expression, SD::Expression, internal::ExpressionKeyLess > substitution_map
Expression substitute(const Expression &expression, const types::substitution_map &substitution_map)
constexpr ReturnType< rank, T >::value_type & extract(T &t, const ArrayType &indices)
void copy(const T *begin, const T *end, U *dest)
int(&) functions(const void *v1, const void *v2)