11"""demag_functions"""
22
3- # +
4- # pylint: disable=invalid-name, redefined-outer-name, protected-access
53from __future__ import annotations
64
75import sys
1816
1917config = {
2018 "handlers" : [
21- dict (
22- sink = sys .stdout ,
23- colorize = True ,
24- format = (
19+ {
20+ " sink" : sys .stdout ,
21+ " colorize" : True ,
22+ " format" : (
2523 "<magenta>{time:YYYY-MM-DD at HH:mm:ss}</magenta>"
2624 " | <level>{level:^8}</level>"
2725 " | <cyan>{function}</cyan>"
2826 " | <yellow>{extra}</yellow> {level.icon:<2} {message}"
2927 ),
30- ) ,
28+ } ,
3129 ],
3230}
3331logger .configure (** config )
3432
3533
3634def get_susceptibilities (sources , susceptibility ):
3735 """Return a list of length (len(sources)) with susceptibility values
38- Priority is given at the source level, hovever if value is not found, it is searched
36+ Priority is given at the source level, however if value is not found, it is searched
3937 up the parent tree, if available. Raises an error if no value is found when reached
4038 the top level of the tree."""
4139 n = len (sources )
@@ -47,31 +45,31 @@ def get_susceptibilities(sources, susceptibility):
4745 susceptibility = getattr (src , "susceptibility" , None )
4846 if susceptibility is None :
4947 if src .parent is None :
50- raise ValueError (
51- "No susceptibility defined in any parent collection"
52- )
48+ msg = "No susceptibility defined in any parent collection"
49+ raise ValueError (msg )
5350 susis .extend (get_susceptibilities (src .parent ))
5451 elif not hasattr (susceptibility , "__len__" ):
5552 susis .append ((susceptibility , susceptibility , susceptibility ))
5653 elif len (susceptibility ) == 3 :
5754 susis .append (susceptibility )
5855 else :
59- raise ValueError ("susceptibility is not scalar or array fo length 3" )
56+ msg = "susceptibility is not scalar or array of length 3"
57+ raise ValueError (msg )
6058 # susceptibilities as input to demag function
6159 elif np .isscalar (susceptibility ):
6260 susis = np .ones ((n , 3 )) * susceptibility
6361 elif len (susceptibility ) == 3 :
6462 susis = np .tile (susceptibility , (n , 1 ))
6563 if n == 3 :
66- raise ValueError (
64+ msg = (
6765 "Apply_demag input susceptibility is ambiguous - either scalar list or vector single entry. "
6866 "Please choose different means of input or change the number of cells in the Collection."
6967 )
68+ raise ValueError (msg )
7069 else :
7170 if len (susceptibility ) != n :
72- raise ValueError (
73- "Apply_demag input susceptibility must be scalar, 3-vector, or same length as input Collection."
74- )
71+ msg = "Apply_demag input susceptibility must be scalar, 3-vector, or same length as input Collection."
72+ raise ValueError (msg )
7573 susis = np .array (susceptibility )
7674 if susis .ndim == 1 :
7775 susis = np .repeat (susis , 3 ).reshape (n , 3 )
@@ -82,7 +80,7 @@ def get_susceptibilities(sources, susceptibility):
8280
8381def get_H_ext (* sources , H_ext = None ):
8482 """Return a list of length (len(sources)) with H_ext values
85- Priority is given at the source level, hovever if value is not found, it is searched up the
83+ Priority is given at the source level, however if value is not found, it is searched up the
8684 the parent tree, if available. Sets H_ext to zero if no value is found when reached the top
8785 level of the tree"""
8886 H_exts = []
@@ -120,7 +118,7 @@ def demag_tensor(
120118 calculated only once and copied to duplicates.
121119
122120 split: int
123- Number of times the sources list is splitted before getH calculation ind demag
121+ Number of times the sources list is split before getH calculation ind demag
124122 tensor calculation
125123
126124 min_log_time:
@@ -141,7 +139,8 @@ def demag_tensor(
141139 nof_src = len (src_list )
142140
143141 if pairs_matching and split != 1 :
144- raise ValueError ("Pairs matching does not support splitting" )
142+ msg = "Pairs matching does not support splitting"
143+ raise ValueError (msg )
145144 if max_dist != 0 :
146145 mask_inds , getH_params , pos0 , rot0 = filter_distance (
147146 src_list , max_dist , return_params = False , return_base_geo = True
@@ -192,9 +191,7 @@ def demag_tensor(
192191 H_point .append (H_unit_pol ) # shape (n_cells, n_pos, 3_xyz)
193192
194193 # shape (3_unit_pol, n_cells, n_pos, 3_xyz)
195- T = np .array (H_point ).reshape ((3 , nof_src , nof_src , 3 ))
196-
197- return T
194+ return np .array (H_point ).reshape ((3 , nof_src , nof_src , 3 ))
198195
199196
200197def filter_distance (
@@ -208,9 +205,8 @@ def filter_distance(
208205 with timelog ("Distance filter" , min_log_time = min_log_time ):
209206 all_cuboids = all (isinstance (src , Cuboid ) for src in src_list )
210207 if not all_cuboids :
211- raise ValueError (
212- "filter_distance only implemented if all sources are Cuboids"
213- )
208+ msg = "filter_distance only implemented if all sources are Cuboids"
209+ raise ValueError (msg )
214210 pos0 = np .array ([getattr (src , "barycenter" , src .position ) for src in src_list ])
215211 rotQ0 = [src .orientation .as_quat () for src in src_list ]
216212 rot0 = R .from_quat (rotQ0 )
@@ -222,12 +218,14 @@ def filter_distance(
222218 maxdim2 = np .concatenate (dim2 , axis = 1 ).max (axis = 1 )
223219 mask = (dist2 / maxdim2 ) < max_dist
224220 if return_params :
225- params = dict (
226- observers = np .tile (pos0 , (len (src_list ), 1 ))[mask ],
227- position = np .repeat (pos0 , len (src_list ), axis = 0 )[mask ],
228- orientation = R .from_quat (np .repeat (rotQ0 , len (src_list ), axis = 0 ))[mask ],
229- dimension = np .repeat (dim0 , len (src_list ), axis = 0 )[mask ],
230- )
221+ params = {
222+ "observers" : np .tile (pos0 , (len (src_list ), 1 ))[mask ],
223+ "position" : np .repeat (pos0 , len (src_list ), axis = 0 )[mask ],
224+ "orientation" : R .from_quat (np .repeat (rotQ0 , len (src_list ), axis = 0 ))[
225+ mask
226+ ],
227+ "dimension" : np .repeat (dim0 , len (src_list ), axis = 0 )[mask ],
228+ }
231229 dsf = sum (mask ) / len (mask ) * 100
232230 log_msg = (
233231 "Interaction pairs left after distance factor filtering: "
@@ -252,9 +250,8 @@ def match_pairs(src_list, min_log_time=1):
252250 with timelog ("Pairs matching" , min_log_time = min_log_time ):
253251 all_cuboids = all (isinstance (src , Cuboid ) for src in src_list )
254252 if not all_cuboids :
255- raise ValueError (
256- "Pairs matching only implemented if all sources are Cuboids"
257- )
253+ msg = "Pairs matching only implemented if all sources are Cuboids"
254+ raise ValueError (msg )
258255 pos0 = np .array ([getattr (src , "barycenter" , src .position ) for src in src_list ])
259256 rotQ0 = [src .orientation .as_quat () for src in src_list ]
260257 rot0 = R .from_quat (rotQ0 )
@@ -283,12 +280,12 @@ def match_pairs(src_list, min_log_time=1):
283280 f"<blue>{ perc :.2f} %</blue>"
284281 )
285282
286- params = dict (
287- observers = np .tile (pos0 , (len (src_list ), 1 ))[unique_inds ],
288- position = np .repeat (pos0 , len (src_list ), axis = 0 )[unique_inds ],
289- orientation = R .from_quat (rotQ2b )[unique_inds ],
290- dimension = np .repeat (dim0 , len (src_list ), axis = 0 )[unique_inds ],
291- )
283+ params = {
284+ " observers" : np .tile (pos0 , (len (src_list ), 1 ))[unique_inds ],
285+ " position" : np .repeat (pos0 , len (src_list ), axis = 0 )[unique_inds ],
286+ " orientation" : R .from_quat (rotQ2b )[unique_inds ],
287+ " dimension" : np .repeat (dim0 , len (src_list ), axis = 0 )[unique_inds ],
288+ }
292289 return params , unique_inds , unique_inv_inds , pos0 , rot0
293290
294291
@@ -331,7 +328,7 @@ def apply_demag(
331328 `pairs_matching` or `split` and applies only cuboid cells.
332329
333330 split: int
334- Number of times the sources list is splitted before getH calculation ind demag
331+ Number of times the sources list is split before getH calculation ind demag
335332 tensor calculation. This parameter is not compatible with `pairs_matching` or
336333 `max_dist`.
337334
@@ -353,10 +350,11 @@ def apply_demag(
353350 srcs = collection .sources_all
354351 src_with_paths = [src for src in srcs if src .position .ndim != 1 ]
355352 if src_with_paths :
356- raise ValueError (
353+ msg = (
357354 f"{ len (src_with_paths )} objects with paths, found. Demagnetization of "
358355 "objects with paths is not yet supported"
359356 )
357+ raise ValueError (msg )
360358 magnets_list = [src for src in srcs if isinstance (src , BaseMagnet )]
361359 currents_list = [src for src in srcs if isinstance (src , BaseCurrent )]
362360 others_list = [
@@ -365,16 +363,17 @@ def apply_demag(
365363 if not isinstance (src , (BaseMagnet , BaseCurrent , magpy .Sensor ))
366364 ]
367365 if others_list :
368- raise TypeError (
366+ msg = (
369367 "Only Magnet and Current sources supported. "
370368 "Incompatible objects found: "
371369 f"{ Counter (s .__class__ .__name__ for s in others_list )} "
372370 )
371+ raise TypeError (msg )
373372 n = len (magnets_list )
374373 counts = Counter (s .__class__ .__name__ for s in magnets_list )
375374 inplace_str = f"""{ " (inplace)" if inplace else "" } """
376375 lbl = collection .style .label
377- coll_str = str ( collection ) if not lbl else lbl
376+ coll_str = lbl if lbl else str ( collection )
378377 demag_msg = (
379378 f"Demagnetization{ inplace_str } of <blue>{ coll_str } </blue>"
380379 f" with { n } cells - { counts } "
@@ -399,9 +398,8 @@ def apply_demag(
399398 H_ext = get_H_ext (* magnets_list )
400399 H_ext = np .array (H_ext )
401400 if len (H_ext ) != n :
402- raise ValueError (
403- "Apply_demag input collection and H_ext must have same length."
404- )
401+ msg = "Apply_demag input collection and H_ext must have same length."
402+ raise ValueError (msg )
405403 H_ext = np .reshape (H_ext , (3 * n , 1 ), order = "F" )
406404
407405 # set up T (3 pol unit, n cells, n positions, 3 Bxyz)
@@ -442,3 +440,4 @@ def apply_demag(
442440
443441 if not inplace :
444442 return collection
443+ return None
0 commit comments