Skip to content

decorators

Functions:

Name Description
save

Decorator for saving output to NetCDF or CSV format

dscim.menu.decorators.save

save(name)

Decorator for saving output to NetCDF or CSV format

Parameters:

Name Type Description Default
name

Name of file. The file will be modified by class elements

required

Returns:

Type Description
None
Source code in src/dscim/menu/decorators.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def save(name):
    """Decorator for saving output to NetCDF or CSV format

    Parameters
    ----------
    name str
        Name of file. The file will be modified by class elements

    Returns
    -------
        None
    """

    def decorator_save(func):
        @functools.wraps(func)
        def save_wrap(self, *args, **kwargs):
            out = func(self, *args, **kwargs)
            save = out

            if (self.save_path is not None) and (name in self.save_files):
                if not os.path.exists(self.save_path):
                    os.makedirs(self.save_path)

                filename = f"{self.NAME}_{self.discounting_type}_eta{self.eta}_rho{self.rho}_{name}{self.filename_suffix}"
                filename_path = os.path.join(self.save_path, filename)

                if isinstance(save, xr.DataArray):
                    save = save.rename(name).to_dataset()
                    save.attrs = self.output_attrs

                    # change `None` object to str(None)
                    for att in save.attrs:
                        if save.attrs[att] is None:
                            save.attrs.update({att: "None"})

                    self.logger.info(f"Saving {filename_path}.nc4")
                    save.to_netcdf(f"{filename_path}.nc4")

                elif isinstance(save, xr.Dataset):
                    save.attrs = self.output_attrs

                    # change `None` object to str(None)
                    for att in save.attrs:
                        if save.attrs[att] is None:
                            save.attrs.update({att: "None"})

                    self.logger.info(f"Saving {filename_path}.nc4")
                    save.to_netcdf(f"{filename_path}.nc4")

                elif isinstance(save, pd.DataFrame):
                    self.logger.info(f"Saving {filename_path}.csv")
                    save.to_csv(f"{filename_path}.csv", index=False)

            return out

        return save_wrap

    return decorator_save