Save model- what do the Pickle as Python?

I am trying to save the model and results in StocasticPrograms. I tried write_to_file(sp, "Models/model_1.mps") but I faced an error:
NaNERROR: LoadError: MethodError: no method matching write_to_file(::StochasticProgram

If it was in Python I just Pickle the model. How should I do in Julia?

Many thanks!

The Serialization standard library package is probably what you’re looking for.

using Serialization
my_data = Dict(:a => 1, :b => [1, 2, 3])
serialize("my_data.jls", my_data)
my_data_from_serialized = deserialize("my_data.jls")
@assert my_data == my_data_from_serialized

Also of note, if the object you want to serialize has any custom data types contained within it, you’ll want to load up the modules with those data types prior to deserializing them.

1 Like

It works!

Be aware that the Serialization package is (analogue to Python Pickle) not intended for long-term storage - their main use case are inter-process communication.
Especially it is not guaranteed that you can still access your data after upgrading either Julia itself or any used package.
An alternative is

1 Like

We do actually promise that all future 1.x releases will be able to read serialized data from previous releases since RFC: document compatibility properties of `serialize` by JeffBezanson · Pull Request #41520 · JuliaLang/julia · GitHub. It doesn’t work the other way however, you can’t read data serialized with a more recent release from an older one.

1 Like

Good to know!

This part of the documentation is then outdated?

serialize(stream::IO, value)
In general, this process will not work if the reading and writing are done by different versions of Julia, or an instance of Julia with a different system image.

1 Like

I believe that PR was merged after 1.7 was already branches, so it didn’t update the 1.7 docs. Perhaps it’s worth backporting though