11"""OTEAPI strategy for parsing OPTIMADE structure resources to DLite instances."""
2+ from __future__ import annotations
3+
24import logging
35from pathlib import Path
46from typing import TYPE_CHECKING
1719from oteapi_optimade .strategies .parse import OPTIMADEParseStrategy
1820
1921if TYPE_CHECKING : # pragma: no cover
20- from typing import Any , Dict , Optional , Union
22+ from typing import Any
2123
2224
2325LOGGER = logging .getLogger ("oteapi_optimade.dlite" )
@@ -40,9 +42,7 @@ class OPTIMADEDLiteParseStrategy:
4042
4143 parse_config : OPTIMADEDLiteParseConfig
4244
43- def initialize (
44- self , session : "Optional[Dict[str, Any]]" = None
45- ) -> DLiteSessionUpdate :
45+ def initialize (self , session : dict [str , Any ] | None = None ) -> DLiteSessionUpdate :
4646 """Initialize strategy.
4747
4848 This method will be called through the `/initialize` endpoint of the OTE-API
@@ -59,7 +59,7 @@ def initialize(
5959 return DLiteSessionUpdate (collection_id = get_collection (session ).uuid )
6060
6161 def get (
62- self , session : "Optional[Union[ SessionUpdate, Dict [str, Any]]]" = None
62+ self , session : SessionUpdate | dict [str , Any ] | None = None
6363 ) -> OPTIMADEParseSession :
6464 """Request and parse an OPTIMADE response using OPT.
6565
@@ -110,14 +110,19 @@ def get(
110110 f"yaml://{ entities_path } /OPTIMADEStructureSpecies.yaml"
111111 )
112112
113+ error_message_supporting_only_structures = (
114+ "The DLite OPTIMADE Parser currently only supports structures entities."
115+ )
116+
113117 if self .parse_config .configuration .return_object :
114118 # The response is given as a "proper" pydantic data model instance
115119
116120 if "optimade_response_object" not in session :
117- raise ValueError (
121+ error_message = (
118122 "'optimade_response_object' was expected to be present in the "
119123 "session."
120124 )
125+ raise ValueError (error_message )
121126
122127 # Currently, only "structures" entries are supported and handled
123128 if isinstance (session .optimade_response_object , StructureResponseMany ):
@@ -152,26 +157,23 @@ def get(
152157 "Could not determine what to do with `data`. Type %s." ,
153158 type (session .optimade_response_object .data ),
154159 )
155- raise OPTIMADEParseError (
156- "Could not parse `data` entry in response."
157- )
160+ error_message = "Could not parse `data` entry in response."
161+ raise OPTIMADEParseError (error_message )
158162 else :
159163 LOGGER .debug (
160164 "Got currently unsupported response type %s. Only structures are "
161165 "supported." ,
162166 session .optimade_response_object .__class__ .__name__ ,
163167 )
164- raise OPTIMADEParseError (
165- "The DLite OPTIMADE Parser currently only supports structures "
166- "entities."
167- )
168+ raise OPTIMADEParseError (error_message_supporting_only_structures )
168169 else :
169170 # The response is given as pure Python dictionary
170171
171172 if "optimade_response" not in session :
172- raise ValueError (
173+ error_message = (
173174 "'optimade_response' was expected to be present in the session."
174175 )
176+ raise ValueError (error_message )
175177
176178 if not session .optimade_response or "data" not in session .optimade_response :
177179 LOGGER .debug ("Not a successful response - no 'data' entry found." )
@@ -187,30 +189,25 @@ def get(
187189 "Could not parse list of 'data' entries as structures."
188190 )
189191 raise OPTIMADEParseError (
190- "The DLite OPTIMADE Parser currently only supports structures "
191- "entities."
192+ error_message_supporting_only_structures
192193 ) from exc
193194 elif session .optimade_response is not None :
194195 try :
195196 structures = [Structure (session .optimade_response ["data" ])]
196197 except ValidationError as exc :
197198 LOGGER .debug ("Could not parse single 'data' entry as a structure." )
198199 raise OPTIMADEParseError (
199- "The DLite OPTIMADE Parser currently only supports structures "
200- "entities."
200+ error_message_supporting_only_structures
201201 ) from exc
202202 else :
203- LOGGER .debug ("Could not parse 'data' entries as structures." )
204- raise OPTIMADEParseError (
205- "The DLite OPTIMADE Parser currently only supports structures "
206- "entities."
207- )
203+ LOGGER .debug ("Could not parse 'data' entries as structures." ) # type: ignore[unreachable]
204+ raise OPTIMADEParseError (error_message_supporting_only_structures )
208205
209206 dlite_collection = get_collection (session )
210207
211208 # DLite-fy OPTIMADE structures
212209 for structure in structures :
213- new_structure_attributes : dict [str , " Any" ] = {}
210+ new_structure_attributes : dict [str , Any ] = {}
214211
215212 # Most inner layer: assemblies & species
216213 if structure .attributes .assemblies :
@@ -221,19 +218,21 @@ def get(
221218
222219 for assembly in structure .attributes .assemblies :
223220 # Ensure we're dealing with a normal Python dict
224- assembly = (
221+ assembly_dict = (
225222 assembly .dict (exclude_none = True )
226223 if isinstance (assembly , BaseModel )
227224 else assembly
228225 )
229226
230227 dimensions = {
231- "ngroups" : len (assembly .get ("group_probabilities" , []) or []),
232- "nsites" : len (assembly .get ("sites_in_groups" , []) or []),
228+ "ngroups" : len (
229+ assembly_dict .get ("group_probabilities" , []) or []
230+ ),
231+ "nsites" : len (assembly_dict .get ("sites_in_groups" , []) or []),
233232 }
234233 new_structure_attributes ["assemblies" ].append (
235234 OPTIMADEStructureAssembly (
236- dimensions = dimensions , properties = assembly
235+ dimensions = dimensions , properties = assembly_dict
237236 )
238237 )
239238
@@ -245,24 +244,24 @@ def get(
245244
246245 for species_individual in structure .attributes .species :
247246 # Ensure we're dealing with a normal Python dict
248- species_individual = (
247+ species_individual_dict = (
249248 species_individual .dict (exclude_none = True )
250249 if isinstance (species_individual , BaseModel )
251250 else species_individual
252251 )
253252
254253 dimensions = {
255254 "nelements" : len (
256- species_individual .get ("chemical_symbols" , []) or []
255+ species_individual_dict .get ("chemical_symbols" , []) or []
257256 ),
258257 "nattached_elements" : len (
259- species_individual .get ("attached" , []) or []
258+ species_individual_dict .get ("attached" , []) or []
260259 ),
261260 }
262261 new_structure_attributes ["species" ].append (
263262 OPTIMADEStructureSpecies (
264263 dimensions = dimensions ,
265- properties = species_individual ,
264+ properties = species_individual_dict ,
266265 )
267266 )
268267
0 commit comments