Last active
May 17, 2021 21:36
-
-
Save klieret/04a44163ab487afde09c790f4894e924 to your computer and use it in GitHub Desktop.
Cache the result of Mathematica calculations and load it again later.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cachedCalc::usage="Cache the result of a calculation into a .mx file at \ | |
<notebook directory>/<notebook name>/<variable name>.mx | |
Arg1: variable (variable as symbol or variable name as string) | |
Arg2: expression (how to calculate value of the variable) | |
Arg3: forceRecalculate (bool; default False; recalculate even if found in Cache). | |
Optional arguments: | |
quiet (bool: should debug messages be printed?) | |
maxAge (date difference object: if the cache is older than that age, a \ | |
recalculation is performed automatically) | |
Furthermore, there are the following global options (just define the variables): | |
cachedCalcForceRecalculate (bool, default False) | |
cachedCalcMaxAge (date difference object, default 0/disabled) | |
(both get ignored if the corresponding optional argument is given to this function)."; | |
Begin["`Private`"]; | |
(*stop arguments from being evaluated right away*) | |
SetAttributes[cachedCalc,HoldAll] | |
Options[cachedCalc]={ | |
quiet->False, | |
maxAge->0 | |
}; | |
cachedCalc[variable_,expression_,force_:False,OptionsPattern[]]:= | |
Module[{thisFilename, exportFilename,exportDirname,verbose,variableName,cforceRecalculate,cmaxAge,recalculate}, | |
verbose=!OptionValue[quiet]; | |
variableName=If[ | |
StringQ@variable, | |
variable, | |
SymbolName@Unevaluated@variable | |
]; | |
(*filename of this notebook without extension*) | |
thisFilename=StringJoin@Part[#,1;;-2]&@StringSplit[#,"."]&@Last@FileNameSplit@NotebookFileName[]; | |
exportDirname=FileNameJoin@{NotebookDirectory[],"mathematica_cache",thisFilename}; | |
exportFilename=FileNameJoin@{exportDirname,ToString@variableName<>".mx"}; | |
(*setup global variables*) | |
If[ | |
!ValueQ@cachedCalcForceRecalculate, | |
cachedCalcForceRecalculate=False | |
]; | |
If[ | |
!ValueQ@cachedCalcMaxAge, | |
cachedCalcMaxAge=0(*disable*); | |
]; | |
cforceRecalculate= force || cachedCalcForceRecalculate; | |
cmaxAge = If[OptionValue@maxAge!=0,OptionValue@maxAge,cachedCalcMaxAge]; | |
(*create directory if needed*) | |
If[ | |
!DirectoryQ@exportDirname, | |
(*then*) | |
verbose && Print["Creating directory "<>exportDirname<>"..."]; | |
CreateDirectory@DirectoryName@exportFilename; | |
]; | |
recalculate=False; | |
If[ | |
cforceRecalculate, | |
recalculate=True | |
]; | |
If[ | |
FileExistsQ@exportFilename && !(cmaxAge===0) && Now-FileDate[exportFilename]>cmaxAge, | |
recalculate=True | |
]; | |
If[ | |
!FileExistsQ@exportFilename, | |
recalculate=True | |
]; | |
If[ | |
recalculate, | |
(*then*) | |
verbose && PrintTemporary@"Recalculating..."; | |
Clear@Evaluate@variableName; | |
Evaluate@Symbol@variableName=ReleaseHold@expression; | |
verbose && PrintTemporary@"Saving to Cache..."; | |
DumpSave[exportFilename,Evaluate@variableName];, | |
(*else*) | |
verbose && PrintTemporary@"Loading from cache..."; | |
(*clearing the old value of the variable*) | |
Clear@Evaluate@variableName; | |
DumpGet[exportFilename] | |
verbose && Print["Variable '"<>variableName<>"' was loaded from cache (last updated ",Now-FileDate[exportFilename]," ago)."] | |
]; | |
]; | |
End[]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
see blog entry http://www.lieret.net/2017/12/28/cached-calculations/