@@ -181,6 +181,26 @@ def get_sphCoord_axes(arg_r):
181181 x2y2 = arg_r [0 ] ** 2 + arg_r [1 ] ** 2
182182 r2 = x2y2 + arg_r [2 ] ** 2
183183
184+ # Check for division by zero
185+ if r2 == 0.0 :
186+ raise ValueError ("r2 is zero, cannot compute spherical coordinates." )
187+
188+ if x2y2 == 0.0 :
189+ raise ValueError ("x2y2 is zero, cannot compute sin_phi and cos_phi." )
190+
191+ # Check for non-negative values inside the square root
192+ if x2y2 / r2 < 0 :
193+ raise ValueError (
194+ f"Negative value encountered for sin_theta calculation: { x2y2 / r2 } . "
195+ f"Cannot take square root."
196+ )
197+
198+ if x2y2 < 0 :
199+ raise ValueError (
200+ f"Negative value encountered for sin_phi and cos_phi calculation: { x2y2 } . "
201+ f"Cannot take square root."
202+ )
203+
184204 if x2y2 != 0.0 :
185205 sin_theta = np .sqrt (x2y2 / r2 )
186206 cos_theta = arg_r [2 ] / np .sqrt (r2 )
@@ -259,6 +279,13 @@ def get_weighted_forces(
259279 # divide the sum of forces by the mass of the bead to get the weighted forces
260280 mass = bead .total_mass ()
261281
282+ # Check that mass is positive to avoid division by 0 or negative values inside sqrt
283+ if mass <= 0 :
284+ raise ValueError (
285+ f"Invalid mass value: { mass } . Mass must be positive to compute the square "
286+ f"root."
287+ )
288+
262289 weighted_force = forces_trans / np .sqrt (mass )
263290
264291 return weighted_force
@@ -309,14 +336,18 @@ def get_weighted_torques(data_container, bead, rot_axes, force_partitioning=0.5)
309336 moment_of_inertia = bead .moment_of_inertia ()
310337
311338 for dimension in range (3 ):
312- # cannot divide by zero
313- if np .isclose (moment_of_inertia [dimension , dimension ], 0 ):
314- weighted_torque [dimension ] = torques [dimension ]
315- else :
316- weighted_torque [dimension ] = torques [dimension ] / np .sqrt (
317- moment_of_inertia [dimension , dimension ]
339+ # Check if the moment of inertia is valid for square root calculation
340+ inertia_value = moment_of_inertia [dimension , dimension ]
341+
342+ if np .isclose (inertia_value , 0 ):
343+ raise ValueError (
344+ f"Invalid moment of inertia value: { inertia_value } . "
345+ f"Cannot compute weighted torque."
318346 )
319347
348+ # compute weighted torque if moment of inertia is valid
349+ weighted_torque [dimension ] = torques [dimension ] / np .sqrt (inertia_value )
350+
320351 return weighted_torque
321352
322353
0 commit comments