Line data Source code
1 : //* This file is part of the MOOSE framework 2 : //* https://mooseframework.inl.gov 3 : //* 4 : //* All rights reserved, see COPYRIGHT for full restrictions 5 : //* https://github.com/idaholab/moose/blob/master/COPYRIGHT 6 : //* 7 : //* Licensed under LGPL 2.1, please see LICENSE for details 8 : //* https://www.gnu.org/licenses/lgpl-2.1.html 9 : 10 : #include "MemoizedFunctionInterface.h" 11 : 12 : InputParameters 13 659 : MemoizedFunctionInterface::validParams() 14 : { 15 659 : InputParameters params = Function::validParams(); 16 : 17 659 : params.addClassDescription("The function uses a cache to potentially reduce the computational " 18 : "burden of reusing a complex or costly function"); 19 : 20 1318 : params.addParam<bool>("enable_cache", 21 1318 : false, 22 : "Enables cached function evaluations. Recommended only if this function is " 23 : "used directly in a BC or Kernel. This will be enabled automatically if " 24 : "any of the FX-based BCs are used."); 25 : 26 1318 : params.addParam<bool>("respect_time", false, "Enable to clear the cache at each new time step."); 27 : 28 659 : return params; 29 0 : } 30 : 31 392 : MemoizedFunctionInterface::MemoizedFunctionInterface(const InputParameters & parameters) 32 : : Function(parameters), 33 784 : _enable_cache(getParam<bool>("enable_cache")), 34 1176 : _respect_time(getParam<bool>("respect_time")) 35 : { 36 392 : } 37 : 38 : void 39 0 : MemoizedFunctionInterface::meshChanged() 40 : { 41 : // The mesh has changed, which invalidates the cache 42 0 : invalidateCache(); 43 0 : } 44 : 45 : Real 46 1844116 : MemoizedFunctionInterface::value(Real time, const Point & point) const 47 : { 48 : MemoizedFunctionInterface * ptr = const_cast<MemoizedFunctionInterface *>(this); 49 : 50 1844116 : if (_enable_cache) 51 : { 52 : // Start the cache over if we are at a new time step 53 1709364 : if (_respect_time && time != _current_time) 54 : { 55 0 : _current_time = time; 56 0 : ptr->invalidateCache(); 57 : } 58 : 59 : // Try to insert a new value into the cache 60 1709364 : auto result = _cache.insert({hashing::hashCombine(time, point), 0.0}); 61 : 62 : // Evaluate and apply if the insertion worked, i.e. the element didn't exist 63 1709364 : if (result.second) 64 59336 : result.first->second = ptr->evaluateValue(time, point); 65 : 66 : // Return the cached value 67 1709364 : return result.first->second; 68 : } 69 : 70 134752 : return ptr->evaluateValue(time, point); 71 : } 72 : 73 : ADReal 74 0 : MemoizedFunctionInterface::value(const ADReal &, const ADPoint &) const 75 : { 76 0 : mooseError("Not implemented"); 77 : } 78 : 79 : void 80 95 : MemoizedFunctionInterface::useCache(bool use) 81 : { 82 95 : _enable_cache = use; 83 : 84 95 : if (!_enable_cache) 85 0 : invalidateCache(); 86 95 : } 87 : 88 : void 89 20432 : MemoizedFunctionInterface::invalidateCache() 90 : { 91 : _cache.clear(); 92 20432 : }