8
8
9
9
from typing import (
10
10
Optional ,
11
- List ,
12
- Dict ,
13
- Any ,
14
- Union ,
15
11
Tuple ,
16
- Type ,
17
- TypeVar ,
18
- Callable ,
19
- Iterable ,
20
12
)
21
13
22
14
from docstring_parser import parse
29
21
30
22
from typing import Union , List , Dict , Any
31
23
32
- from attr import has , field , fields
33
- from attr .validators import optional , instance_of , in_
34
-
35
- from cattr .gen import make_dict_unstructure_fn , make_dict_structure_fn , override
24
+ from cattr .gen import make_dict_unstructure_fn , override
36
25
from cattr .preconf .pyyaml import make_converter as make_yaml_converter
37
26
38
-
39
- from collections import OrderedDict
40
27
from tabulate import tabulate
41
28
42
29
verbose = False
48
35
49
36
class EvaluableExpression (str ):
50
37
"""
51
- EvaluableExpression is a string that can be evaluated to a value during MDF execution. This class inherits from
38
+ EvaluableExpression is a string that can be evaluated to a value during modelspec execution. This class inherits from
52
39
str, so it can be used as a string.
53
40
"""
54
41
@@ -139,13 +126,13 @@ def from_dict(cls, d: Dict[str, Any]) -> "Base":
139
126
140
127
@classmethod
141
128
def from_json (cls , json_str : str ) -> "Base" :
142
- """Instantiate an MDF object from a JSON string"""
129
+ """Instantiate an modelspec object from a JSON string"""
143
130
return cls .from_dict (json .loads (json_str ))
144
131
145
132
def to_json_file (
146
133
self , filename : Optional [str ] = None , include_metadata : bool = True
147
134
) -> str :
148
- """Convert the MDF model to JSON format and save to a file.
135
+ """Convert the modelspec model to JSON format and save to a file.
149
136
150
137
.. note::
151
138
JSON is standard file format uses human-readable text to store and transmit data objects consisting of
@@ -180,10 +167,10 @@ def to_yaml(self, include_metadata: bool = True) -> str:
180
167
return yaml .dump (yaml_converter .unstructure (self .to_dict ()), sort_keys = False )
181
168
182
169
def to_yaml_file (self , filename : str , include_metadata : bool = True ) -> str :
183
- """Convert file in MDF format to yaml format
170
+ """Convert modelspec format to yaml format
184
171
185
172
Args:
186
- filename: File in MDF format (Filename extension: .mdf )
173
+ filename: File in modelspec format (Filename extension: .yaml )
187
174
include_metadata: Contains contact information, citations, acknowledgements, pointers to sample data,
188
175
benchmark results, and environments in which the specified model was originally implemented
189
176
Returns:
@@ -203,52 +190,52 @@ def to_yaml_file(self, filename: str, include_metadata: bool = True) -> str:
203
190
return filename
204
191
205
192
@classmethod
206
- def from_file (cls , filename : str ) -> "Model " :
193
+ def from_file (cls , filename : str ) -> "Base " :
207
194
"""
208
- Create a :class:`.Model ` from its representation stored in a file. Auto-detect the correct deserialization code
195
+ Create a :class:`.Base ` from its representation stored in a file. Auto-detect the correct deserialization code
209
196
based on file extension. Currently supported formats are; JSON(.json) and YAML (.yaml or .yml)
210
197
211
198
Args:
212
199
filename: The name of the file to load.
213
200
214
201
Returns:
215
- An MDF :class:`.Model ` for this file.
202
+ An modelspec :class:`.Base ` for this file.
216
203
"""
217
204
if filename .endswith (".yaml" ) or filename .endswith (".yml" ):
218
205
return cls .from_yaml_file (filename )
219
206
elif filename .endswith (".json" ):
220
207
return cls .from_json_file (filename )
221
208
else :
222
209
raise ValueError (
223
- f"Cannot auto-detect MDF serialization format from filename ({ filename } ). The filename "
210
+ f"Cannot auto-detect modelspec serialization format from filename ({ filename } ). The filename "
224
211
f"must have one of the following extensions: .json, .yml, or .yaml."
225
212
)
226
213
227
214
@classmethod
228
- def from_json_file (cls , filename : str ) -> "Model " :
215
+ def from_json_file (cls , filename : str ) -> "Base " :
229
216
"""
230
- Create a :class:`.Model ` from its JSON representation stored in a file.
217
+ Create a :class:`.Base ` from its JSON representation stored in a file.
231
218
232
219
Args:
233
220
filename: The file from which to load the JSON data.
234
221
235
222
Returns:
236
- An MDF :class:`.Model ` for this JSON
223
+ An modelspec :class:`.Base ` for this JSON
237
224
"""
238
225
with open (filename ) as infile :
239
226
d = json .load (infile )
240
227
return cls .from_dict (d )
241
228
242
229
@classmethod
243
- def from_yaml_file (cls , filename : str ) -> "Model " :
230
+ def from_yaml_file (cls , filename : str ) -> "Base " :
244
231
"""
245
- Create a :class:`.Model ` from its YAML representation stored in a file.
232
+ Create a :class:`.Base ` from its YAML representation stored in a file.
246
233
247
234
Args:
248
235
filename: The file from which to load the YAML data.
249
236
250
237
Returns:
251
- An MDF :class:`.Model ` for this YAML
238
+ An modelspec :class:`.Base ` for this YAML
252
239
"""
253
240
with open (filename ) as infile :
254
241
d = yaml .safe_load (infile )
@@ -269,7 +256,7 @@ def get_child(self, id: str, type_: str) -> Any:
269
256
"""
270
257
271
258
# We can't find the container for this type of child object.
272
- if not type_ in [f .name for f in attr .fields (self .__class__ )]:
259
+ if type_ not in [f .name for f in attr .fields (self .__class__ )]:
273
260
return None
274
261
275
262
children = self .__getattribute__ (type_ )
@@ -462,7 +449,7 @@ def _is_base_type(
462
449
or (can_be_list and value == list )
463
450
or (can_be_dict and value == dict )
464
451
or (can_be_ndarray and value == numpy .ndarray )
465
- or (can_be_none and value is type ( None ) )
452
+ or (can_be_none and value is None )
466
453
or (can_be_eval_expr and cls ._is_evaluable_expression (value ))
467
454
or value == Union
468
455
)
@@ -485,7 +472,6 @@ def _type_to_str(type_: Any) -> str:
485
472
486
473
# If its a Generic type
487
474
elif get_origin (type_ ) is not None :
488
- collection_arg = None
489
475
if get_origin (type_ ) == list and len (get_args (type_ )) > 0 :
490
476
return Base ._type_to_str (get_args (type_ )[0 ])
491
477
elif get_origin (type_ ) == dict and len (get_args (type_ )) > 0 :
@@ -532,7 +518,7 @@ def _cls_generate_documentation(cls, format: str = MARKDOWN_FORMAT):
532
518
rst_url_format = "`%s <%s>`_"
533
519
534
520
def insert_links (text , format = MARKDOWN_FORMAT ):
535
- if not "_" in text :
521
+ if "_" not in text :
536
522
return text
537
523
if '"' in text :
538
524
return text # Assume it's a quoted string containing an underscore...
@@ -811,13 +797,13 @@ def f(obj_list):
811
797
return f
812
798
813
799
814
- def _structure_list_mdfbase (cl ):
800
+ def _structure_list_base (cl ):
815
801
"""Deserialize list of dict of Base objects as a list if all of their elements have ids"""
816
- mdf_class = get_args (cl )[0 ]
802
+ base_class = get_args (cl )[0 ]
817
803
818
804
def f (obj_dict , t ):
819
805
try :
820
- obj_list = [converter .structure (v , mdf_class ) for v in obj_dict .values ()]
806
+ obj_list = [converter .structure (v , base_class ) for v in obj_dict .values ()]
821
807
822
808
# Give each object the id that is its key in the dict.
823
809
for id , obj in zip (obj_dict .keys (), obj_list ):
@@ -845,7 +831,7 @@ def _is_list_base(cl):
845
831
_base_unstruct_hook_factory ,
846
832
)
847
833
848
- converter .register_structure_hook_factory (_is_list_base , _structure_list_mdfbase )
834
+ converter .register_structure_hook_factory (_is_list_base , _structure_list_base )
849
835
converter .register_structure_hook_factory (
850
836
lambda cl : issubclass (cl , Base ) and "id" in [a .name for a in fields (cl )],
851
837
_base_struct_hook_factory ,
0 commit comments