|
| 1 | +import importlib.util |
| 2 | +import sys |
1 | 3 | from copy import deepcopy |
2 | 4 | from glob import glob |
3 | 5 | from os import path |
@@ -1062,6 +1064,32 @@ def from_xarray_dataset(cls, ds, variables, dimensions, mesh='spherical', allow_ |
1062 | 1064 | v = fields.pop('V', None) |
1063 | 1065 | return cls(u, v, fields=fields) |
1064 | 1066 |
|
| 1067 | + @classmethod |
| 1068 | + def from_modulefile(cls, filename, modulename="create_fieldset", **kwargs): |
| 1069 | + """Initialises FieldSet data from a file containing a python module file with a create_fieldset() function. |
| 1070 | +
|
| 1071 | + Parameters |
| 1072 | + ---------- |
| 1073 | + filename: path to a python file containing at least a function which returns a FieldSet object. |
| 1074 | + modulename: name of the function in the python file that returns a FieldSet object. Default is "create_fieldset". |
| 1075 | + """ |
| 1076 | + # check if filename exists |
| 1077 | + if not path.exists(filename): |
| 1078 | + raise IOError(f"FieldSet module file {filename} does not exist") |
| 1079 | + |
| 1080 | + # Importing the source file directly (following https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly) |
| 1081 | + spec = importlib.util.spec_from_file_location(modulename, filename) |
| 1082 | + fieldset_module = importlib.util.module_from_spec(spec) |
| 1083 | + sys.modules[modulename] = fieldset_module |
| 1084 | + spec.loader.exec_module(fieldset_module) |
| 1085 | + |
| 1086 | + if not hasattr(fieldset_module, modulename): |
| 1087 | + raise IOError(f"{filename} does not contain a {modulename} function") |
| 1088 | + fieldset = getattr(fieldset_module, modulename)(**kwargs) |
| 1089 | + if not isinstance(fieldset, FieldSet): |
| 1090 | + raise IOError(f"Module {filename}.{modulename} does not return a FieldSet object") |
| 1091 | + return fieldset |
| 1092 | + |
1065 | 1093 | def get_fields(self): |
1066 | 1094 | """Returns a list of all the :class:`parcels.field.Field` and :class:`parcels.field.VectorField` |
1067 | 1095 | objects associated with this FieldSet. |
|
0 commit comments