Static method to create a model from a JSON string Parameters ---------- param_json : str a UTF-8 encoded JSON string containing model data Returns ------- pyfair.model.FairModel A model instance using the JSON parameters supp
(param_json)
| 118 | |
| 119 | @staticmethod |
| 120 | def read_json(param_json): |
| 121 | """Static method to create a model from a JSON string |
| 122 | |
| 123 | Parameters |
| 124 | ---------- |
| 125 | param_json : str |
| 126 | a UTF-8 encoded JSON string containing model data |
| 127 | |
| 128 | Returns |
| 129 | ------- |
| 130 | pyfair.model.FairModel |
| 131 | A model instance using the JSON parameters supplied |
| 132 | |
| 133 | Raises |
| 134 | ------ |
| 135 | pyfair.fair_exception.FairException |
| 136 | If metamodel JSON is supplied erroneously |
| 137 | |
| 138 | Example |
| 139 | ------- |
| 140 | >>> with open('serialized_model.json') as f: |
| 141 | ... json_text = f.read() |
| 142 | ... |
| 143 | >>> model = FairModel.read_json(json_text) |
| 144 | |
| 145 | """ |
| 146 | data = json.loads(param_json) |
| 147 | # Check type of JSON |
| 148 | if data['type'] != 'FairModel': |
| 149 | raise FairException('Failed JSON parse attempt. This is not a FairModel.') |
| 150 | model = FairModel( |
| 151 | name=data['name'], |
| 152 | n_simulations=data['n_simulations'], |
| 153 | random_seed=data['random_seed'], |
| 154 | model_uuid=data['model_uuid'], |
| 155 | creation_date=data['creation_date'] |
| 156 | ) |
| 157 | # Be lazy |
| 158 | drop_params = [ |
| 159 | 'name', |
| 160 | 'n_simulations', |
| 161 | 'random_seed', |
| 162 | 'creation_date', |
| 163 | 'model_uuid', |
| 164 | 'type' |
| 165 | ] |
| 166 | # Load params one-by-one. |
| 167 | for param_name, param_value in data.items(): |
| 168 | # If it's not in the drop list, load it. |
| 169 | if param_name not in drop_params: |
| 170 | # Input params must be treated differently if raw |
| 171 | contains_raw = 'raw' in param_value.keys() |
| 172 | if param_name.startswith('multi'): |
| 173 | model.input_multi_data(param_name, param_value) |
| 174 | # Raw needs a different way |
| 175 | elif contains_raw: |
| 176 | model.input_raw_data(param_name, param_value['raw']) |
| 177 | # Otherwise standard input |