Skip to content
Thomas Saillour edited this page Mar 1, 2024 · 5 revisions

xarray backend for Selafin formats

Dev guide

to have the backend working in xarray, follow these steps

pip install xarray-selafin

Read selafin

import xarray as xr
ds = xr.open_dataset("input_file.slf", engine='selafin')

Write selafin

ds.selafin.write('output_file.slf')

Create a selafin from scratch

import xarray as xr
import numpy as np
import pandas as pd
from scipy.spatial import Delaunay
from xarray_selafin.xarray_backend import SelafinAccessor

x= np.random.rand(100)
y= np.random.rand(100)

ikle = Delaunay(np.vstack((x, y)).T).simplices

# Creating a minimal dataset
ds = xr.Dataset(
    {
        "S": (("time", "node", "plan"), np.random.rand(10, 100,1)),
        # Add other variables as needed
    },
    coords={
        "x": ("node", x), 
        "y": ("node", y), 
        "time": pd.date_range("2020-01-01", periods=10),
        'ikle2':  (('nelem2', 'ndp2'), ikle),
        'ikle3':  (('nelem3', 'ndp3'), ikle),
        # Add "ikle2" or "ikle3" as required by your mesh
    }
)

# Setting required attributes
ds.attrs["title"] = "Example Dataset"
ds.attrs["date_start"] = (2020, 1, 1, 0, 0, 0)
ds.attrs["meshx"] = x  # Example value, adjust as necessary
ds.attrs["meshy"] = y  # Example value, adjust as necessary
ds.attrs["ipob2"] = np.zeros(len(x), dtype=np.int64)  # Example value, adjust as necessary
ds.attrs["ipob3"] = np.zeros(len(x), dtype=np.int64)  # Example value, adjust as necessary
ds.attrs["meshy"] = y  # Example value, adjust as necessary
ds.attrs["nelem3"] = len(ikle)  # Example value, adjust as necessary
ds.attrs["npoin3"] = len(x)  # Example value, adjust as necessary
ds.attrs["ndp3"] = 3  # Example value, adjust as necessary for 3D
ds.attrs["npoin2"] = len(x)  # Example value, adjust as necessary for 2D
ds.attrs["iparam"] = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)  # Example values, adjust as necessary
ds.attrs["var_IDs"] = ["S"]  # List of variable IDs present in the dataset
ds.attrs["varnames"] = ["FREE SURFACE"]  # List of variable IDs present in the dataset
ds.attrs["varunits"] = ["M"]  # List of variable IDs present in the dataset
print(ds)

# Writing to a SELAFIN file
ds.selafin.write("path_to_output.slf")
Clone this wiki locally