# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import numpy as np
import xarray as xr

import netCDF4 as nc


# -

def f(x, omega=1):
    """simple sine function"""
    return np.sin(2 * np.pi * omega *x)


times = np.linspace(0, 10, 100)

sine = f(times)

# +
# create DataArray with metadata

metadata = {'timestep': times[1] - times[0], 'creation_data': '19-07-17', 'list': ['a', 'b', 2, 3]}

df = xr.DataArray(sine, dims='time', coords={'time': times}, name='sine', attrs=metadata)
df.attrs
# -

df.to_netcdf('sine.nc')
new_df = xr.open_dataarray('sine.nc')
new_df.attrs

all(new_df == df)

# ## Open with netCDF

nc_df = nc.Dataset('sine.nc')

nc_df.variables

new_sine = np.asarray(nc_df['sine'][:])

sum(sine - new_sine)

nc_df['sine'].__dict__['timestep']



StarcoderdataJupyterScriptsDedupFiltered