How can I make assignments persist among sessions?Saving Mathematica kernel state?How to substitute variables in interpolated function?How to mix Unevaluated property of function arguments with expression assignments?how can I generate a sequence of assignments?How can I make Which format its output?How I can define a new function as a function argument?How to make Piecewise continuousHow can I “save” a function?Share variables among notebooks with different KernelsHow can I use manipulate to control many functions with many variables?How can I see what Get restored?

Unfrosted light bulb

Variable completely messes up echoed string

Synchronized implementation of a bank account in Java

Tikz: place node leftmost of two nodes of different widths

What does Jesus mean regarding "Raca," and "you fool?" - is he contrasting them?

Have the tides ever turned twice on any open problem?

Optimising a list searching algorithm

Recruiter wants very extensive technical details about all of my previous work

Existence of a celestial body big enough for early civilization to be thought of as a second moon

Does the attack bonus from a Masterwork weapon stack with the attack bonus from Masterwork ammunition?

gerund and noun applications

How to terminate ping <dest> &

Why is indicated airspeed rather than ground speed used during the takeoff roll?

Can other pieces capture a threatening piece and prevent a checkmate?

Suggestions on how to spend Shaabath (constructively) alone

How does 取材で訪れた integrate into this sentence?

If "dar" means "to give", what does "daros" mean?

How is the partial sum of a geometric sequence calculated?

What does "mu" mean as an interjection?

Usage and meaning of "up" in "...worth at least a thousand pounds up in London"

Should I use acronyms in dialogues before telling the readers what it stands for in fiction?

What is the term when voters “dishonestly” choose something that they do not want to choose?

How do hiring committees for research positions view getting "scooped"?

Describing a chess game in a novel



How can I make assignments persist among sessions?


Saving Mathematica kernel state?How to substitute variables in interpolated function?How to mix Unevaluated property of function arguments with expression assignments?how can I generate a sequence of assignments?How can I make Which format its output?How I can define a new function as a function argument?How to make Piecewise continuousHow can I “save” a function?Share variables among notebooks with different KernelsHow can I use manipulate to control many functions with many variables?How can I see what Get restored?













6












$begingroup$


Yesterday, I imported a large set of data into a Mathematica notebook and stored each imported list of numbers in a function. For example, I would map a list like 10, 20, 30 to a function value as shown below



f[0] = 10, 20 30;
f[1] = 40, 50, 60;


With the lists stored in the functions I generated the below chart by writing



averageComparisonChart = 
BarChart[fpAverages, fpiAverages,
ChartLabels -> "FP Quicksort", "FP Insertion Quicksort",
Range[0, 160, 10], AxesLabel -> HoldForm["Vector size"],
HoldForm["Execution time (ms)"], PlotLabel -> HoldForm["Quicksort vs.
Insertion sort"], LabelStyle -> GrayLevel[0]]


which output



bar chart



Before going to bed, I saved my notebook and shut down my computer. Today, all my functions have been reset. For example inputting f[0] outputs f[0] rather than the previously assigned list 10, 20, 30.



Does anyone know what has caused this issue? How can a loss of data be avoided in the future? Is there a better way to store lists than in functions? Is there a way to restore the values from yesterday?



Related Question



The accepted answer to this question provides a method for creating persistence of data between sessions.










share|improve this question









New contributor




K. Claesson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$







  • 1




    $begingroup$
    What exactly is the question? You seem to be aware of the fact that Mathematica does not save the kernel state together with the notebook (see linked question), which explains why your values are gone. In general, a notebook should contain everything needed to restore the kernel state (this means e.g. that you have to keep all definitions that are required in the notebook)
    $endgroup$
    – Lukas Lang
    2 days ago







  • 1




    $begingroup$
    You may want to look at Iconize.
    $endgroup$
    – Carl Lange
    2 days ago










  • $begingroup$
    @LukasLang I was not aware that Mathematica does not save the kernel until recently. The question is what the best wat to create persistence of data in Mathematica.
    $endgroup$
    – K. Claesson
    2 days ago






  • 1




    $begingroup$
    Which way is best depends on your exact workflow and requirements, which you have not stated. For different options, look at the linked question (and questions linked there), Iconize (as suggested by @CarlLange), Put/Export and Get/Import.
    $endgroup$
    – Lukas Lang
    2 days ago






  • 2




    $begingroup$
    @K.Claesson What other system do you know that saves the state on exit without any user intervention? Most systems can't even save the state at all. Those that can (like R) still require the user to do it explicitly. It is not a natural expectation that definitions would persist.
    $endgroup$
    – Szabolcs
    2 days ago
















6












$begingroup$


Yesterday, I imported a large set of data into a Mathematica notebook and stored each imported list of numbers in a function. For example, I would map a list like 10, 20, 30 to a function value as shown below



f[0] = 10, 20 30;
f[1] = 40, 50, 60;


With the lists stored in the functions I generated the below chart by writing



averageComparisonChart = 
BarChart[fpAverages, fpiAverages,
ChartLabels -> "FP Quicksort", "FP Insertion Quicksort",
Range[0, 160, 10], AxesLabel -> HoldForm["Vector size"],
HoldForm["Execution time (ms)"], PlotLabel -> HoldForm["Quicksort vs.
Insertion sort"], LabelStyle -> GrayLevel[0]]


which output



bar chart



Before going to bed, I saved my notebook and shut down my computer. Today, all my functions have been reset. For example inputting f[0] outputs f[0] rather than the previously assigned list 10, 20, 30.



Does anyone know what has caused this issue? How can a loss of data be avoided in the future? Is there a better way to store lists than in functions? Is there a way to restore the values from yesterday?



Related Question



The accepted answer to this question provides a method for creating persistence of data between sessions.










share|improve this question









New contributor




K. Claesson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$







  • 1




    $begingroup$
    What exactly is the question? You seem to be aware of the fact that Mathematica does not save the kernel state together with the notebook (see linked question), which explains why your values are gone. In general, a notebook should contain everything needed to restore the kernel state (this means e.g. that you have to keep all definitions that are required in the notebook)
    $endgroup$
    – Lukas Lang
    2 days ago







  • 1




    $begingroup$
    You may want to look at Iconize.
    $endgroup$
    – Carl Lange
    2 days ago










  • $begingroup$
    @LukasLang I was not aware that Mathematica does not save the kernel until recently. The question is what the best wat to create persistence of data in Mathematica.
    $endgroup$
    – K. Claesson
    2 days ago






  • 1




    $begingroup$
    Which way is best depends on your exact workflow and requirements, which you have not stated. For different options, look at the linked question (and questions linked there), Iconize (as suggested by @CarlLange), Put/Export and Get/Import.
    $endgroup$
    – Lukas Lang
    2 days ago






  • 2




    $begingroup$
    @K.Claesson What other system do you know that saves the state on exit without any user intervention? Most systems can't even save the state at all. Those that can (like R) still require the user to do it explicitly. It is not a natural expectation that definitions would persist.
    $endgroup$
    – Szabolcs
    2 days ago














6












6








6


2



$begingroup$


Yesterday, I imported a large set of data into a Mathematica notebook and stored each imported list of numbers in a function. For example, I would map a list like 10, 20, 30 to a function value as shown below



f[0] = 10, 20 30;
f[1] = 40, 50, 60;


With the lists stored in the functions I generated the below chart by writing



averageComparisonChart = 
BarChart[fpAverages, fpiAverages,
ChartLabels -> "FP Quicksort", "FP Insertion Quicksort",
Range[0, 160, 10], AxesLabel -> HoldForm["Vector size"],
HoldForm["Execution time (ms)"], PlotLabel -> HoldForm["Quicksort vs.
Insertion sort"], LabelStyle -> GrayLevel[0]]


which output



bar chart



Before going to bed, I saved my notebook and shut down my computer. Today, all my functions have been reset. For example inputting f[0] outputs f[0] rather than the previously assigned list 10, 20, 30.



Does anyone know what has caused this issue? How can a loss of data be avoided in the future? Is there a better way to store lists than in functions? Is there a way to restore the values from yesterday?



Related Question



The accepted answer to this question provides a method for creating persistence of data between sessions.










share|improve this question









New contributor




K. Claesson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




Yesterday, I imported a large set of data into a Mathematica notebook and stored each imported list of numbers in a function. For example, I would map a list like 10, 20, 30 to a function value as shown below



f[0] = 10, 20 30;
f[1] = 40, 50, 60;


With the lists stored in the functions I generated the below chart by writing



averageComparisonChart = 
BarChart[fpAverages, fpiAverages,
ChartLabels -> "FP Quicksort", "FP Insertion Quicksort",
Range[0, 160, 10], AxesLabel -> HoldForm["Vector size"],
HoldForm["Execution time (ms)"], PlotLabel -> HoldForm["Quicksort vs.
Insertion sort"], LabelStyle -> GrayLevel[0]]


which output



bar chart



Before going to bed, I saved my notebook and shut down my computer. Today, all my functions have been reset. For example inputting f[0] outputs f[0] rather than the previously assigned list 10, 20, 30.



Does anyone know what has caused this issue? How can a loss of data be avoided in the future? Is there a better way to store lists than in functions? Is there a way to restore the values from yesterday?



Related Question



The accepted answer to this question provides a method for creating persistence of data between sessions.







functions variable-definitions persistence






share|improve this question









New contributor




K. Claesson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




K. Claesson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited yesterday









Αλέξανδρος Ζεγγ

4,43011029




4,43011029






New contributor




K. Claesson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 2 days ago









K. ClaessonK. Claesson

334




334




New contributor




K. Claesson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





K. Claesson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






K. Claesson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 1




    $begingroup$
    What exactly is the question? You seem to be aware of the fact that Mathematica does not save the kernel state together with the notebook (see linked question), which explains why your values are gone. In general, a notebook should contain everything needed to restore the kernel state (this means e.g. that you have to keep all definitions that are required in the notebook)
    $endgroup$
    – Lukas Lang
    2 days ago







  • 1




    $begingroup$
    You may want to look at Iconize.
    $endgroup$
    – Carl Lange
    2 days ago










  • $begingroup$
    @LukasLang I was not aware that Mathematica does not save the kernel until recently. The question is what the best wat to create persistence of data in Mathematica.
    $endgroup$
    – K. Claesson
    2 days ago






  • 1




    $begingroup$
    Which way is best depends on your exact workflow and requirements, which you have not stated. For different options, look at the linked question (and questions linked there), Iconize (as suggested by @CarlLange), Put/Export and Get/Import.
    $endgroup$
    – Lukas Lang
    2 days ago






  • 2




    $begingroup$
    @K.Claesson What other system do you know that saves the state on exit without any user intervention? Most systems can't even save the state at all. Those that can (like R) still require the user to do it explicitly. It is not a natural expectation that definitions would persist.
    $endgroup$
    – Szabolcs
    2 days ago













  • 1




    $begingroup$
    What exactly is the question? You seem to be aware of the fact that Mathematica does not save the kernel state together with the notebook (see linked question), which explains why your values are gone. In general, a notebook should contain everything needed to restore the kernel state (this means e.g. that you have to keep all definitions that are required in the notebook)
    $endgroup$
    – Lukas Lang
    2 days ago







  • 1




    $begingroup$
    You may want to look at Iconize.
    $endgroup$
    – Carl Lange
    2 days ago










  • $begingroup$
    @LukasLang I was not aware that Mathematica does not save the kernel until recently. The question is what the best wat to create persistence of data in Mathematica.
    $endgroup$
    – K. Claesson
    2 days ago






  • 1




    $begingroup$
    Which way is best depends on your exact workflow and requirements, which you have not stated. For different options, look at the linked question (and questions linked there), Iconize (as suggested by @CarlLange), Put/Export and Get/Import.
    $endgroup$
    – Lukas Lang
    2 days ago






  • 2




    $begingroup$
    @K.Claesson What other system do you know that saves the state on exit without any user intervention? Most systems can't even save the state at all. Those that can (like R) still require the user to do it explicitly. It is not a natural expectation that definitions would persist.
    $endgroup$
    – Szabolcs
    2 days ago








1




1




$begingroup$
What exactly is the question? You seem to be aware of the fact that Mathematica does not save the kernel state together with the notebook (see linked question), which explains why your values are gone. In general, a notebook should contain everything needed to restore the kernel state (this means e.g. that you have to keep all definitions that are required in the notebook)
$endgroup$
– Lukas Lang
2 days ago





$begingroup$
What exactly is the question? You seem to be aware of the fact that Mathematica does not save the kernel state together with the notebook (see linked question), which explains why your values are gone. In general, a notebook should contain everything needed to restore the kernel state (this means e.g. that you have to keep all definitions that are required in the notebook)
$endgroup$
– Lukas Lang
2 days ago





1




1




$begingroup$
You may want to look at Iconize.
$endgroup$
– Carl Lange
2 days ago




$begingroup$
You may want to look at Iconize.
$endgroup$
– Carl Lange
2 days ago












$begingroup$
@LukasLang I was not aware that Mathematica does not save the kernel until recently. The question is what the best wat to create persistence of data in Mathematica.
$endgroup$
– K. Claesson
2 days ago




$begingroup$
@LukasLang I was not aware that Mathematica does not save the kernel until recently. The question is what the best wat to create persistence of data in Mathematica.
$endgroup$
– K. Claesson
2 days ago




1




1




$begingroup$
Which way is best depends on your exact workflow and requirements, which you have not stated. For different options, look at the linked question (and questions linked there), Iconize (as suggested by @CarlLange), Put/Export and Get/Import.
$endgroup$
– Lukas Lang
2 days ago




$begingroup$
Which way is best depends on your exact workflow and requirements, which you have not stated. For different options, look at the linked question (and questions linked there), Iconize (as suggested by @CarlLange), Put/Export and Get/Import.
$endgroup$
– Lukas Lang
2 days ago




2




2




$begingroup$
@K.Claesson What other system do you know that saves the state on exit without any user intervention? Most systems can't even save the state at all. Those that can (like R) still require the user to do it explicitly. It is not a natural expectation that definitions would persist.
$endgroup$
– Szabolcs
2 days ago





$begingroup$
@K.Claesson What other system do you know that saves the state on exit without any user intervention? Most systems can't even save the state at all. Those that can (like R) still require the user to do it explicitly. It is not a natural expectation that definitions would persist.
$endgroup$
– Szabolcs
2 days ago











2 Answers
2






active

oldest

votes


















10












$begingroup$

If you wrap your definitions in Once then their results will be remembered across sessions:



f[0] = Once[Print["a"]; 10, 20, 30, "Local"]


Here the printing and the numbers 10, 20, 30 are used instead of a lengthy calculation that you only want to do once and whose result you want to remember in the next session.



On the first execution, the above code prints "a" and assigns the numbers 10, 20, 30 to f[0]. On subsequent executions (even after you've closed Mathematica and come back and are reevaluating the notebook), the execution of the first argument of Once does not take place any more, so there is no printing, and only the remembered result 10, 20, 30 is directly assigned to f[0]. This speeds up the reprocessing on subsequent executions dramatically if the list 10, 20, 30 is replaced with something hard to compute.



With Once you don't need to save/restore semi-manually as some comments suggest with Save, DumpSave, Get. Instead, persistent storage operates transparently to cache what has been calculated before.



If you place these Once calls within an initialization cell/group, then you have something resembling a persistent assignment.



Once has more options: you can specify in which cache the persistent storage should be (in the front end session, or locally so that even when you close and reopen Mathematica it's still there) and how long it should persist.




Another way to create persistent objects is with PersistentValue, which is a bit lower-level than Once but basically the same mechanism.



How to get rid of persistent objects



A certain wariness with persistent storage is in order. But note that these Once definitions are associated with a hash of the expression executed as the first argument to Once, and not with where you're storing the result (as in f[0] in my example): the documentation says that "Once has attribute HoldFirst and compares unevaluated expressions." In this sense I consider Once a safe and unconfusing technique to use; I haven't run into trouble with undesired cross-contamination of unconditionally persistent objects. No persistent storage will be consulted unless you explicitly wrap an expression in Once.



Nonetheless in practice I keep the persistent storage pool as clean as possible. As the documentation states, you can inspect the storage pool with



PersistentObjects["Hashes/Once/*"]



PersistentObject["Hashes/Once/BlVsTGCUwUI", PersistentLocation[..., Type:Local]],
PersistentObject["Hashes/Once/FziAfp1s_y2", PersistentLocation[..., Type:Local]]




and clean it with



DeleteObject[%]





share|improve this answer











$endgroup$












  • $begingroup$
    Do you use this in practice? It feels a bit dangerous to make definitions unconditionally persistent ... Could you add the command to reset these definitions (in case someone messes up their Mathematica and needs a way to revert it)?
    $endgroup$
    – Szabolcs
    2 days ago










  • $begingroup$
    @Szabolcs yes I agree, see my edit. Thanks for bringing this up, it was a hurdle for me to get started too.
    $endgroup$
    – Roman
    2 days ago


















7












$begingroup$

Like in all other systems I am familiar with, variable and function definitions exist in memory (RAM) only and do not persist across sessions.



If you want a definition to persist, you must save it explicitly. See Save and DumpSave.



However, what I recommend for cases like yours is not to store such data in DownValue definitions. Store them in a data structure that is easy to serialize, then save them to a file. So, instead of f[1]=a; f[2]=b; f[3]=c use a list a,b,c. If the indices are not contiguous, you can use a SparseArray or Association. You can save any data that is stored as a Mathematica expression into an MX file, which is the most practical and flexible format for short-term storage (not for archiving because of weak cross-version compatibility promises). For archiving or for exchange with other systems, consider JSON: any expression that consists of lists, associations, numbers and strings can be saved to JSON.






share|improve this answer











$endgroup$












    Your Answer





    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "387"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    K. Claesson is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f193301%2fhow-can-i-make-assignments-persist-among-sessions%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    10












    $begingroup$

    If you wrap your definitions in Once then their results will be remembered across sessions:



    f[0] = Once[Print["a"]; 10, 20, 30, "Local"]


    Here the printing and the numbers 10, 20, 30 are used instead of a lengthy calculation that you only want to do once and whose result you want to remember in the next session.



    On the first execution, the above code prints "a" and assigns the numbers 10, 20, 30 to f[0]. On subsequent executions (even after you've closed Mathematica and come back and are reevaluating the notebook), the execution of the first argument of Once does not take place any more, so there is no printing, and only the remembered result 10, 20, 30 is directly assigned to f[0]. This speeds up the reprocessing on subsequent executions dramatically if the list 10, 20, 30 is replaced with something hard to compute.



    With Once you don't need to save/restore semi-manually as some comments suggest with Save, DumpSave, Get. Instead, persistent storage operates transparently to cache what has been calculated before.



    If you place these Once calls within an initialization cell/group, then you have something resembling a persistent assignment.



    Once has more options: you can specify in which cache the persistent storage should be (in the front end session, or locally so that even when you close and reopen Mathematica it's still there) and how long it should persist.




    Another way to create persistent objects is with PersistentValue, which is a bit lower-level than Once but basically the same mechanism.



    How to get rid of persistent objects



    A certain wariness with persistent storage is in order. But note that these Once definitions are associated with a hash of the expression executed as the first argument to Once, and not with where you're storing the result (as in f[0] in my example): the documentation says that "Once has attribute HoldFirst and compares unevaluated expressions." In this sense I consider Once a safe and unconfusing technique to use; I haven't run into trouble with undesired cross-contamination of unconditionally persistent objects. No persistent storage will be consulted unless you explicitly wrap an expression in Once.



    Nonetheless in practice I keep the persistent storage pool as clean as possible. As the documentation states, you can inspect the storage pool with



    PersistentObjects["Hashes/Once/*"]



    PersistentObject["Hashes/Once/BlVsTGCUwUI", PersistentLocation[..., Type:Local]],
    PersistentObject["Hashes/Once/FziAfp1s_y2", PersistentLocation[..., Type:Local]]




    and clean it with



    DeleteObject[%]





    share|improve this answer











    $endgroup$












    • $begingroup$
      Do you use this in practice? It feels a bit dangerous to make definitions unconditionally persistent ... Could you add the command to reset these definitions (in case someone messes up their Mathematica and needs a way to revert it)?
      $endgroup$
      – Szabolcs
      2 days ago










    • $begingroup$
      @Szabolcs yes I agree, see my edit. Thanks for bringing this up, it was a hurdle for me to get started too.
      $endgroup$
      – Roman
      2 days ago















    10












    $begingroup$

    If you wrap your definitions in Once then their results will be remembered across sessions:



    f[0] = Once[Print["a"]; 10, 20, 30, "Local"]


    Here the printing and the numbers 10, 20, 30 are used instead of a lengthy calculation that you only want to do once and whose result you want to remember in the next session.



    On the first execution, the above code prints "a" and assigns the numbers 10, 20, 30 to f[0]. On subsequent executions (even after you've closed Mathematica and come back and are reevaluating the notebook), the execution of the first argument of Once does not take place any more, so there is no printing, and only the remembered result 10, 20, 30 is directly assigned to f[0]. This speeds up the reprocessing on subsequent executions dramatically if the list 10, 20, 30 is replaced with something hard to compute.



    With Once you don't need to save/restore semi-manually as some comments suggest with Save, DumpSave, Get. Instead, persistent storage operates transparently to cache what has been calculated before.



    If you place these Once calls within an initialization cell/group, then you have something resembling a persistent assignment.



    Once has more options: you can specify in which cache the persistent storage should be (in the front end session, or locally so that even when you close and reopen Mathematica it's still there) and how long it should persist.




    Another way to create persistent objects is with PersistentValue, which is a bit lower-level than Once but basically the same mechanism.



    How to get rid of persistent objects



    A certain wariness with persistent storage is in order. But note that these Once definitions are associated with a hash of the expression executed as the first argument to Once, and not with where you're storing the result (as in f[0] in my example): the documentation says that "Once has attribute HoldFirst and compares unevaluated expressions." In this sense I consider Once a safe and unconfusing technique to use; I haven't run into trouble with undesired cross-contamination of unconditionally persistent objects. No persistent storage will be consulted unless you explicitly wrap an expression in Once.



    Nonetheless in practice I keep the persistent storage pool as clean as possible. As the documentation states, you can inspect the storage pool with



    PersistentObjects["Hashes/Once/*"]



    PersistentObject["Hashes/Once/BlVsTGCUwUI", PersistentLocation[..., Type:Local]],
    PersistentObject["Hashes/Once/FziAfp1s_y2", PersistentLocation[..., Type:Local]]




    and clean it with



    DeleteObject[%]





    share|improve this answer











    $endgroup$












    • $begingroup$
      Do you use this in practice? It feels a bit dangerous to make definitions unconditionally persistent ... Could you add the command to reset these definitions (in case someone messes up their Mathematica and needs a way to revert it)?
      $endgroup$
      – Szabolcs
      2 days ago










    • $begingroup$
      @Szabolcs yes I agree, see my edit. Thanks for bringing this up, it was a hurdle for me to get started too.
      $endgroup$
      – Roman
      2 days ago













    10












    10








    10





    $begingroup$

    If you wrap your definitions in Once then their results will be remembered across sessions:



    f[0] = Once[Print["a"]; 10, 20, 30, "Local"]


    Here the printing and the numbers 10, 20, 30 are used instead of a lengthy calculation that you only want to do once and whose result you want to remember in the next session.



    On the first execution, the above code prints "a" and assigns the numbers 10, 20, 30 to f[0]. On subsequent executions (even after you've closed Mathematica and come back and are reevaluating the notebook), the execution of the first argument of Once does not take place any more, so there is no printing, and only the remembered result 10, 20, 30 is directly assigned to f[0]. This speeds up the reprocessing on subsequent executions dramatically if the list 10, 20, 30 is replaced with something hard to compute.



    With Once you don't need to save/restore semi-manually as some comments suggest with Save, DumpSave, Get. Instead, persistent storage operates transparently to cache what has been calculated before.



    If you place these Once calls within an initialization cell/group, then you have something resembling a persistent assignment.



    Once has more options: you can specify in which cache the persistent storage should be (in the front end session, or locally so that even when you close and reopen Mathematica it's still there) and how long it should persist.




    Another way to create persistent objects is with PersistentValue, which is a bit lower-level than Once but basically the same mechanism.



    How to get rid of persistent objects



    A certain wariness with persistent storage is in order. But note that these Once definitions are associated with a hash of the expression executed as the first argument to Once, and not with where you're storing the result (as in f[0] in my example): the documentation says that "Once has attribute HoldFirst and compares unevaluated expressions." In this sense I consider Once a safe and unconfusing technique to use; I haven't run into trouble with undesired cross-contamination of unconditionally persistent objects. No persistent storage will be consulted unless you explicitly wrap an expression in Once.



    Nonetheless in practice I keep the persistent storage pool as clean as possible. As the documentation states, you can inspect the storage pool with



    PersistentObjects["Hashes/Once/*"]



    PersistentObject["Hashes/Once/BlVsTGCUwUI", PersistentLocation[..., Type:Local]],
    PersistentObject["Hashes/Once/FziAfp1s_y2", PersistentLocation[..., Type:Local]]




    and clean it with



    DeleteObject[%]





    share|improve this answer











    $endgroup$



    If you wrap your definitions in Once then their results will be remembered across sessions:



    f[0] = Once[Print["a"]; 10, 20, 30, "Local"]


    Here the printing and the numbers 10, 20, 30 are used instead of a lengthy calculation that you only want to do once and whose result you want to remember in the next session.



    On the first execution, the above code prints "a" and assigns the numbers 10, 20, 30 to f[0]. On subsequent executions (even after you've closed Mathematica and come back and are reevaluating the notebook), the execution of the first argument of Once does not take place any more, so there is no printing, and only the remembered result 10, 20, 30 is directly assigned to f[0]. This speeds up the reprocessing on subsequent executions dramatically if the list 10, 20, 30 is replaced with something hard to compute.



    With Once you don't need to save/restore semi-manually as some comments suggest with Save, DumpSave, Get. Instead, persistent storage operates transparently to cache what has been calculated before.



    If you place these Once calls within an initialization cell/group, then you have something resembling a persistent assignment.



    Once has more options: you can specify in which cache the persistent storage should be (in the front end session, or locally so that even when you close and reopen Mathematica it's still there) and how long it should persist.




    Another way to create persistent objects is with PersistentValue, which is a bit lower-level than Once but basically the same mechanism.



    How to get rid of persistent objects



    A certain wariness with persistent storage is in order. But note that these Once definitions are associated with a hash of the expression executed as the first argument to Once, and not with where you're storing the result (as in f[0] in my example): the documentation says that "Once has attribute HoldFirst and compares unevaluated expressions." In this sense I consider Once a safe and unconfusing technique to use; I haven't run into trouble with undesired cross-contamination of unconditionally persistent objects. No persistent storage will be consulted unless you explicitly wrap an expression in Once.



    Nonetheless in practice I keep the persistent storage pool as clean as possible. As the documentation states, you can inspect the storage pool with



    PersistentObjects["Hashes/Once/*"]



    PersistentObject["Hashes/Once/BlVsTGCUwUI", PersistentLocation[..., Type:Local]],
    PersistentObject["Hashes/Once/FziAfp1s_y2", PersistentLocation[..., Type:Local]]




    and clean it with



    DeleteObject[%]






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited yesterday

























    answered 2 days ago









    RomanRoman

    3,290819




    3,290819











    • $begingroup$
      Do you use this in practice? It feels a bit dangerous to make definitions unconditionally persistent ... Could you add the command to reset these definitions (in case someone messes up their Mathematica and needs a way to revert it)?
      $endgroup$
      – Szabolcs
      2 days ago










    • $begingroup$
      @Szabolcs yes I agree, see my edit. Thanks for bringing this up, it was a hurdle for me to get started too.
      $endgroup$
      – Roman
      2 days ago
















    • $begingroup$
      Do you use this in practice? It feels a bit dangerous to make definitions unconditionally persistent ... Could you add the command to reset these definitions (in case someone messes up their Mathematica and needs a way to revert it)?
      $endgroup$
      – Szabolcs
      2 days ago










    • $begingroup$
      @Szabolcs yes I agree, see my edit. Thanks for bringing this up, it was a hurdle for me to get started too.
      $endgroup$
      – Roman
      2 days ago















    $begingroup$
    Do you use this in practice? It feels a bit dangerous to make definitions unconditionally persistent ... Could you add the command to reset these definitions (in case someone messes up their Mathematica and needs a way to revert it)?
    $endgroup$
    – Szabolcs
    2 days ago




    $begingroup$
    Do you use this in practice? It feels a bit dangerous to make definitions unconditionally persistent ... Could you add the command to reset these definitions (in case someone messes up their Mathematica and needs a way to revert it)?
    $endgroup$
    – Szabolcs
    2 days ago












    $begingroup$
    @Szabolcs yes I agree, see my edit. Thanks for bringing this up, it was a hurdle for me to get started too.
    $endgroup$
    – Roman
    2 days ago




    $begingroup$
    @Szabolcs yes I agree, see my edit. Thanks for bringing this up, it was a hurdle for me to get started too.
    $endgroup$
    – Roman
    2 days ago











    7












    $begingroup$

    Like in all other systems I am familiar with, variable and function definitions exist in memory (RAM) only and do not persist across sessions.



    If you want a definition to persist, you must save it explicitly. See Save and DumpSave.



    However, what I recommend for cases like yours is not to store such data in DownValue definitions. Store them in a data structure that is easy to serialize, then save them to a file. So, instead of f[1]=a; f[2]=b; f[3]=c use a list a,b,c. If the indices are not contiguous, you can use a SparseArray or Association. You can save any data that is stored as a Mathematica expression into an MX file, which is the most practical and flexible format for short-term storage (not for archiving because of weak cross-version compatibility promises). For archiving or for exchange with other systems, consider JSON: any expression that consists of lists, associations, numbers and strings can be saved to JSON.






    share|improve this answer











    $endgroup$

















      7












      $begingroup$

      Like in all other systems I am familiar with, variable and function definitions exist in memory (RAM) only and do not persist across sessions.



      If you want a definition to persist, you must save it explicitly. See Save and DumpSave.



      However, what I recommend for cases like yours is not to store such data in DownValue definitions. Store them in a data structure that is easy to serialize, then save them to a file. So, instead of f[1]=a; f[2]=b; f[3]=c use a list a,b,c. If the indices are not contiguous, you can use a SparseArray or Association. You can save any data that is stored as a Mathematica expression into an MX file, which is the most practical and flexible format for short-term storage (not for archiving because of weak cross-version compatibility promises). For archiving or for exchange with other systems, consider JSON: any expression that consists of lists, associations, numbers and strings can be saved to JSON.






      share|improve this answer











      $endgroup$















        7












        7








        7





        $begingroup$

        Like in all other systems I am familiar with, variable and function definitions exist in memory (RAM) only and do not persist across sessions.



        If you want a definition to persist, you must save it explicitly. See Save and DumpSave.



        However, what I recommend for cases like yours is not to store such data in DownValue definitions. Store them in a data structure that is easy to serialize, then save them to a file. So, instead of f[1]=a; f[2]=b; f[3]=c use a list a,b,c. If the indices are not contiguous, you can use a SparseArray or Association. You can save any data that is stored as a Mathematica expression into an MX file, which is the most practical and flexible format for short-term storage (not for archiving because of weak cross-version compatibility promises). For archiving or for exchange with other systems, consider JSON: any expression that consists of lists, associations, numbers and strings can be saved to JSON.






        share|improve this answer











        $endgroup$



        Like in all other systems I am familiar with, variable and function definitions exist in memory (RAM) only and do not persist across sessions.



        If you want a definition to persist, you must save it explicitly. See Save and DumpSave.



        However, what I recommend for cases like yours is not to store such data in DownValue definitions. Store them in a data structure that is easy to serialize, then save them to a file. So, instead of f[1]=a; f[2]=b; f[3]=c use a list a,b,c. If the indices are not contiguous, you can use a SparseArray or Association. You can save any data that is stored as a Mathematica expression into an MX file, which is the most practical and flexible format for short-term storage (not for archiving because of weak cross-version compatibility promises). For archiving or for exchange with other systems, consider JSON: any expression that consists of lists, associations, numbers and strings can be saved to JSON.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited yesterday









        Αλέξανδρος Ζεγγ

        4,43011029




        4,43011029










        answered 2 days ago









        SzabolcsSzabolcs

        162k14443941




        162k14443941




















            K. Claesson is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            K. Claesson is a new contributor. Be nice, and check out our Code of Conduct.












            K. Claesson is a new contributor. Be nice, and check out our Code of Conduct.











            K. Claesson is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Mathematica Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f193301%2fhow-can-i-make-assignments-persist-among-sessions%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Adding axes to figuresAdding axes labels to LaTeX figuresLaTeX equivalent of ConTeXt buffersRotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?TikZ scaling graphic and adjust node position and keep font sizeNumerical conditional within tikz keys?adding axes to shapesAlign axes across subfiguresAdding figures with a certain orderLine up nested tikz enviroments or how to get rid of themAdding axes labels to LaTeX figures

            Tähtien Talli Jäsenet | Lähteet | NavigointivalikkoSuomen Hippos – Tähtien Talli

            Do these cracks on my tires look bad? The Next CEO of Stack OverflowDry rot tire should I replace?Having to replace tiresFishtailed so easily? Bad tires? ABS?Filling the tires with something other than air, to avoid puncture hassles?Used Michelin tires safe to install?Do these tyre cracks necessitate replacement?Rumbling noise: tires or mechanicalIs it possible to fix noisy feathered tires?Are bad winter tires still better than summer tires in winter?Torque converter failure - Related to replacing only 2 tires?Why use snow tires on all 4 wheels on 2-wheel-drive cars?