#!/usr/bin/env python # coding: utf-8 # # Reading and writing Cosmology objects # # In this notebook, we show a few usage examples for how to read and write `Cosmology` objects to disk. # In[1]: from pyccl import Cosmology # In[2]: cosmo = Cosmology(Omega_c=0.25, Omega_b=0.05, sigma8=0.8, h=0.7, n_s=0.96) print(cosmo.__doc__) # ## Serialization (writing parameters to disk) # # Cosmology objects can be saved to a YAML format using the `write_yaml` method. This format is not currently very robust -- the exact order of the parameters must be maintained or the object cannot be read back in. # In[3]: cosmo.write_yaml('example_params.yaml') get_ipython().system('cat example_params.yaml') # ## Deserialization (reading parameters from disk) # # The parameters can be read back in using the `read_yaml` *class method*. Note that this must be called on the `Cosmology` class itself, as shown below, and not an instance of the class. # In[4]: cosmo2 = Cosmology.read_yaml("example_params.yaml") # In[5]: print(cosmo2) # This `Cosmology` object can then be used to obtain cosmological predictions. See the other examples in this directory, for example *Distance Calculations Example.ipynb* or the more comprehensive demo *SLAC Feb2018 Demo.ipynb*. # # Using Python Pickle # # `Cosmology` objects are also pickle-able, to make them easy to store on disk and to pass around in MPI environments. # In[6]: import pickle with open('cosmo.pkl', 'wb') as fp: pickle.dump(cosmo2, fp) # In[7]: with open('cosmo.pkl', 'rb') as fp: cosmo3 = pickle.load(fp) print(cosmo3) # In[ ]: