Store a model or metamodel in the database Thie function takes a model or metamodel, checks whether the appropriate calculations have been completed, and then stores that model. The data is stored in two tables: 1) first the aggregate statistics about the risk are st
(self, model_or_metamodel)
| 139 | return model |
| 140 | |
| 141 | def store(self, model_or_metamodel): |
| 142 | """Store a model or metamodel in the database |
| 143 | |
| 144 | Thie function takes a model or metamodel, checks whether the |
| 145 | appropriate calculations have been completed, and then stores that |
| 146 | model. The data is stored in two tables: 1) first the aggregate |
| 147 | statistics about the risk are stored in the 'results' table, and 2) |
| 148 | the model data is stored in the 'models' table. |
| 149 | |
| 150 | Raises |
| 151 | ------ |
| 152 | FairException |
| 153 | If model or metamodel is not yet calculated |
| 154 | |
| 155 | """ |
| 156 | m = model_or_metamodel |
| 157 | # If incomplete and not ready for storage, throw error |
| 158 | if not m.calculation_completed(): |
| 159 | raise FairException("Model is uncalculated and won't be stored.") |
| 160 | # Export from model |
| 161 | meta = json.loads(m.to_json()) |
| 162 | json_data = m.to_json() |
| 163 | results = m.export_results()['Risk'] |
| 164 | # Write to database |
| 165 | with sqlite3.connect(self._path) as conn: |
| 166 | cursor = conn.cursor() |
| 167 | # Write model data |
| 168 | cursor.execute( |
| 169 | """INSERT OR REPLACE INTO models VALUES(?, ?, ?, ?)""", |
| 170 | ( |
| 171 | meta['model_uuid'], |
| 172 | meta['name'], |
| 173 | meta['creation_date'], |
| 174 | json_data |
| 175 | ) |
| 176 | ) |
| 177 | # Write cached results |
| 178 | cursor.execute( |
| 179 | """INSERT OR REPLACE INTO results VALUES(?, ?, ?, ?, ?)""", |
| 180 | ( |
| 181 | meta['model_uuid'], |
| 182 | results.mean(axis=0), |
| 183 | results.std(axis=0), |
| 184 | results.min(axis=0), |
| 185 | results.max(axis=0) |
| 186 | ) |
| 187 | ) |
| 188 | # Vacuum database |
| 189 | conn = sqlite3.connect(self._path) |
| 190 | conn.execute("VACUUM") |
| 191 | conn.commit() |
| 192 | conn.close() |
| 193 | |
| 194 | def query(self, query, params=None): |
| 195 | """Function for querying the underlying database. |