Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warns and errors #272

Draft
wants to merge 10 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 11 additions & 12 deletions pyCalculations/cutthrough.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,7 @@ def get_cellids_coordinates_distances( vlsvReader, xmax, xmin, xcells, ymax, ymi
# Get the cell id
cellid = vlsvReader.get_cellid(iterator)
if cellid == 0:
logging.info("ERROR, invalid cell id!")
return
raise ValueError("invalid cell id!")
# Get the max and min boundaries:
min_bounds = vlsvReader.get_cell_coordinates(cellid) - 0.5 * cell_lengths
max_bounds = np.array([min_bounds[i] + cell_lengths[i] for i in range(0,3)])
Expand Down Expand Up @@ -152,9 +151,9 @@ def cut_through( vlsvReader, point1, point2 ):

# Make sure point1 and point2 are inside bounds
if vlsvReader.get_cellid(point1) == 0:
logging.info("ERROR, POINT1 IN CUT-THROUGH OUT OF BOUNDS!")
raise ValueError("point1 in cut_through out of bounds!")
if vlsvReader.get_cellid(point2) == 0:
logging.info("ERROR, POINT2 IN CUT-THROUGH OUT OF BOUNDS!")
raise ValueError("point2 in cut_through out of bounds!")

#Calculate cell lengths:
cell_lengths = np.array([(xmax - xmin)/(float)(xcells), (ymax - ymin)/(float)(ycells), (zmax - zmin)/(float)(zcells)])
Expand All @@ -168,7 +167,7 @@ def cut_through_swath(vlsvReader, point1, point2, width, normal):
init_cut = cut_through(vlsvReader, point1, point2)
init_cids = init_cut[0].data

logging.info('swath initial CellIds' + str(init_cids))
# logging.info('swath initial CellIds', init_cids)

#find the other vector spanning the swath
s = np.array(point2)-np.array(point1)
Expand All @@ -184,7 +183,7 @@ def cut_through_swath(vlsvReader, point1, point2, width, normal):
out_cids.append(temp_cut[0].data)

init_cut[0] = np.array(out_cids)
logging.info(init_cut[0])
# logging.info(init_cut[0])
return init_cut

def cut_through_step( vlsvReader, point1, point2 ):
Expand Down Expand Up @@ -213,9 +212,10 @@ def cut_through_step( vlsvReader, point1, point2 ):

# Make sure point1 and point2 are inside bounds
if vlsvReader.get_cellid(point1) == 0:
logging.info("ERROR, POINT1 IN CUT-THROUGH OUT OF BOUNDS!")
# logging.info("ERROR, POINT1 IN CUT-THROUGH OUT OF BOUNDS!")
raise ValueError("point1 in cut_through_step out of bounds!")
if vlsvReader.get_cellid(point2) == 0:
logging.info("ERROR, POINT2 IN CUT-THROUGH OUT OF BOUNDS!")
raise ValueError("point2 in cut_through_step out of bounds!")

# Find path
distances = point2-point1
Expand Down Expand Up @@ -306,8 +306,7 @@ def cut_through_curve(vlsvReader, curve):
cell_lengths = np.array([(xmax - xmin)/(float)(xcells), (ymax - ymin)/(float)(ycells), (zmax - zmin)/(float)(zcells)])

if(len(curve) < 2):
logging.info("ERROR, less than 2 points in a curve")
return None
raise ValueError("less than 2 points in a curve")

cellIds = []
edges = []
Expand All @@ -317,9 +316,9 @@ def cut_through_curve(vlsvReader, curve):
point2 = np.array(curve[i+1])
# Make sure point1 and point2 are inside bounds
if vlsvReader.get_cellid(point1) == 0:
logging.info("ERROR, POINT1 IN CUT-THROUGH-CURVE OUT OF BOUNDS!")
raise ValueError('point1 in cut_through_curve out of bounds')
if vlsvReader.get_cellid(point2) == 0:
logging.info("ERROR, POINT2 IN CUT-THROUGH-CURVE OUT OF BOUNDS!")
raise ValueError('point1 in cut_through_curve out of bounds')
cut = get_cellids_coordinates_distances( vlsvReader, xmax, xmin, xcells, ymax, ymin, ycells, zmax, zmin, zcells, cell_lengths, point1, point2)
ccid = cut[0].data
cedges = cut[1].data
Expand Down
18 changes: 6 additions & 12 deletions pyCalculations/fieldtracer.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,7 @@ def static_field_tracer( vlsvReader, x0, max_iterations, dx, direction='+', bvar
z = np.arange(mins[2], maxs[2], dcell[2]) + 0.5*dcell[2]
coordinates = np.array([x,y,z])
# Debug:
if( len(x) != sizes[0] ):
logging.info("SIZE WRONG: " + str(len(x)) + " " + str(sizes[0]))
assert len(x) == sizes[0]

# Create grid interpolation
interpolator_face_B_0 = interpolate.RectBivariateSpline(coordinates[indices[0]] - 0.5*dcell[indices[0]], coordinates[indices[1]], face_B[indices[0]], kx=2, ky=2, s=0)
Expand All @@ -144,19 +143,16 @@ def static_field_tracer( vlsvReader, x0, max_iterations, dx, direction='+', bvar
z = np.arange(mins[2], maxs[2], dcell[2]) + 0.5*dcell[2]
coordinates = np.array([x,y,z])
# Debug:
if( len(x) != sizes[0] ):
logging.info("SIZE WRONG: " + str(len(x)) + " " + str(sizes[0]))
assert len(x) == sizes[0]

# Create grid interpolation
interpolator_vol_B_0 = interpolate.RectBivariateSpline(coordinates[indices[0]], coordinates[indices[1]], vol_B[indices[0]], kx=2, ky=2, s=0)
interpolator_vol_B_1 = interpolate.RectBivariateSpline(coordinates[indices[0]], coordinates[indices[1]], vol_B[indices[1]], kx=2, ky=2, s=0)
interpolators = [interpolator_vol_B_0, interpolator_vol_B_1]#, interpolator_face_B_2]
elif centering == 'node':
logging.info("Nodal variables not implemented")
return
raise ValueError("Nodal variables not implemented")
else:
logging.info("Unrecognized centering: "+ str(centering))
return
raise ValueError("Unrecognized centering: " + str(centering))

#######################################################
if direction == '-':
Expand Down Expand Up @@ -216,10 +212,6 @@ def fg_trace(vlsvReader, fg, seed_coords, max_iterations, dx, multiplier, stop_c
x = np.arange(mins[0], maxs[0], dcell[0]) + 0.5*dcell[0]
y = np.arange(mins[1], maxs[1], dcell[1]) + 0.5*dcell[1]
z = np.arange(mins[2], maxs[2], dcell[2]) + 0.5*dcell[2]

if centering is None:
logging.info("centering keyword not set! Aborting.")
return False

# Create grid interpolation object for vector field (V). Feed the object the component data and locations of measurements.
if centering == 'face':
Expand All @@ -230,6 +222,8 @@ def fg_trace(vlsvReader, fg, seed_coords, max_iterations, dx, multiplier, stop_c
interpolator_V_0 = interpolate.RegularGridInterpolator((x, y-0.5*dcell[1], z-0.5*dcell[2]), fg[:,:,:,0], bounds_error = False, fill_value = np.nan)
interpolator_V_1 = interpolate.RegularGridInterpolator((x-0.5*dcell[0], y, z-0.5*dcell[2]), fg[:,:,:,1], bounds_error = False, fill_value = np.nan)
interpolator_V_2 = interpolate.RegularGridInterpolator((x-0.5*dcell[0], y-0.5*dcell[1], z), fg[:,:,:,2], bounds_error = False, fill_value = np.nan)
else:
raise NotImplementedError("Unknown centering kword ("+str(centering)+").")

interpolators = [interpolator_V_0, interpolator_V_1, interpolator_V_2]

Expand Down
3 changes: 1 addition & 2 deletions pyCalculations/intpol_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ def vlsv_intpol_file(file_vlsv,file_orbit,varlist,file_output):
if points.shape[1] == 4:
points = np.delete(points,0,1) # remove time column
if points.shape[1] != 3:
logging.info("ERROR: orbit file must have 3 (x,y,z) or 4 (t,x,y,z) columns")
return
raise ValueError("Orbit file must have 3 (x,y,z) or 4 (t,x,y,z) columns")
[crd,cellids,params,hstr]=pt.calculations.vlsv_intpol_points(f,points,varlist)
d=np.concatenate((crd,cellids,params),axis=1)
np.savetxt(file_output,d,"% 05e",header=hstr,comments="% ")
Expand Down
12 changes: 4 additions & 8 deletions pyCalculations/intpol_points.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,21 +60,17 @@ def vlsv_intpol_points(vlsvReader,points,varlist,operator="pass",interpolation_o
varlist = vlsvReader.get_all_variables()
N_vars = len(varlist)
if N_vars <= 0:
logging.info("ERROR: len(varlist) = 0")
return
raise ValueError("len(varlist) = 0")
if N_points < 0:
logging.info("ERROR: len(points) = 0")
return
raise ValueError("len(points) = 0")
header = "x y z cellid " # header string
for i in range(N_vars): # loop variable list
var = varlist[i]
if vlsvReader.check_variable(var) == False:
logging.info("ERROR: variable " + var + " does not exist in file " + vlsvReader.file_name)
return
raise ValueError("variable " + var + " does not exist in file " + vlsvReader.file_name)
dim=len(np.atleast_1d(vlsvReader.read_interpolated_variable(var,points[0],operator))) # variable dimensions
if dim <= 0:
logging.info("ERROR: bad variable dimension (dim=" + str(dim) + ")")
return
raise ValueError("bad variable dimension (dim=" + str(dim) + ")")
values=np.zeros((N_points,dim))
crds=np.zeros((N_points,3)) # coordinates
cellids=np.zeros((N_points,1)) # cell ids
Expand Down
4 changes: 2 additions & 2 deletions pyCalculations/lineout.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ def lineout( vlsvReader, point1, point2, variable, operator="pass",interpolation

# Make sure point1 and point2 are inside bounds
if vlsvReader.get_cellid(point1) == 0:
logging.info("ERROR, POINT1 IN CUT-THROUGH OUT OF BOUNDS!")
raise ValueError("point1 in lineout out of bounds!")
if vlsvReader.get_cellid(point2) == 0:
logging.info("ERROR, POINT2 IN CUT-THROUGH OUT OF BOUNDS!")
raise ValueError("point1 in lineout out of bounds!")

value_len=len(np.atleast_1d(vlsvReader.read_interpolated_variable( variable, point1, operator)))

Expand Down
10 changes: 6 additions & 4 deletions pyCalculations/non_maxwellianity.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def epsilon_M(f,cell,pop="proton",m=m_p, bulk=None, B=None,
:kword threshold: Disregard vspace cells under this threshold [0]
:kword dummy: If not None, generate dummy data for e.g. integration.

:returns: scalar, non-Maxwellianity parameter for given model and norm
:returns: scalar, non-Maxwellianity parameter for given model and norm; -1 for missing VDF/other bad data

The definition is given by Graham et al. (2021):
(1/2n) * integral(|f_i - g_M|) d^3v
Expand Down Expand Up @@ -92,8 +92,10 @@ def epsilon_M(f,cell,pop="proton",m=m_p, bulk=None, B=None,
except:
logging.info("Could not load vg_b_vol from bulk file "+bulk)
if B is None:
warnings.warn("No B found, cannot proceed at cellid "+str(cell))
return -1
if model == "maxwellian":
B = np.array([0,0,1]) # Use a dummy B for the simple maxwellian, here we can proceed
else:
raise ValueError("No B found and "+str(model)+" requires B, cannot proceed at cellid "+str(cell)+". Either use 'maxwellian' or find B from somewhere.")

if bulk is not None:
try:
Expand Down Expand Up @@ -156,7 +158,7 @@ def epsilon_M(f,cell,pop="proton",m=m_p, bulk=None, B=None,
-((vb[:,1] - v0_perp)**2 + vb[:,2]**2)/(vT_para**2 * (T_perp/T_para))
)
else:
raise NameError("Unknown VDF model '"+model+"', aborting")
raise ValueError("Unknown VDF model '"+model+"', aborting")

epsilon = np.linalg.norm(distribution - model_f, ord=normorder)
epsilon *= dV / (norm * n)
Expand Down
3 changes: 1 addition & 2 deletions pyCalculations/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ def output_1d( arrays, names, units="" ):
if units == "":
units = ["" for i in range(len(arrays))]
if( (len(arrays) != len(names)) or (len(arrays) != len(units)) ):
logging.info("BAD ARRAY AND NAME LENGTH IN OUTPUT_1D (pyCalculations/output.py)")
return []
raise ValueError("Bad array and name length in output_1d (pyCalculations/output.py)")
new_format = []
from variable import VariableInfo
for i in range(len(arrays)):
Expand Down
13 changes: 5 additions & 8 deletions pyCalculations/pitchangle.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def pitch_angles( vlsvReader,
elif vlsvReader.check_variable(pop+"/vg_V"):
frame = vlsvReader.read_variable(pop+'/vg_V', cellid)
else:
logging.info("Error extracting plasma frame velocity!")
raise ValueError("Error extracting plasma frame velocity! Please supply a vector instead.")
elif len(plasmaframe)==3: # Assume it's a vector
frame = plasmaframe

Expand All @@ -124,12 +124,10 @@ def pitch_angles( vlsvReader,
pop="avgs"
#logging.info("Auto-switched to population avgs")
else:
logging.info("Unable to detect population "+pop+" in .vlsv file!")
sys.exit()
raise ValueError("Unable to detect population "+pop+" in .vlsv file!")
else:
if not vlsvReader.check_population(pop):
logging.info("Unable to detect population "+pop+" in .vlsv file!")
sys.exit()
raise ValueError("Unable to detect population "+pop+" in .vlsv file!")

# Read temperature for thermal speed
if (vcut is True or vcutmax is True):
Expand Down Expand Up @@ -196,7 +194,7 @@ def pitch_angles( vlsvReader,
cond1 = (v_norms > vcutoff)
cond2 = (v_norms < vcutoffmax)
condition = np.logical_and(cond1,cond2)
logging.info(cond1.shape,cond2.shape,condition.shape)
# logging.info(cond1.shape,cond2.shape,condition.shape)
# Get the velocity cells above cutoff speed
#vcellids_nonsphere = np.extract(condition, vcellids)
# Get the avgs
Expand Down Expand Up @@ -233,8 +231,7 @@ def pitch_angles( vlsvReader,
except:
pass
if not os.access(outputdir, os.W_OK):
logging.info("No write access for directory "+outputdir+"! Exiting.")
return
raise IOError("No write access for directory "+outputdir+"! Exiting.")


outfilewrite=open(outputfile,'w')
Expand Down
5 changes: 3 additions & 2 deletions pyCalculations/spectra.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import numpy as np
import pytools
import logging
import warnings
# Function to reduce the velocity space in a spatial cell to an omnidirectional energy spectrum
# Weighted by particle flux/none
def get_spectrum_energy(vlsvReader,
Expand Down Expand Up @@ -50,7 +51,7 @@ def get_spectrum_energy(vlsvReader,
if not vlsvReader.read_variable('vg_f_saved',cid):
return (False,np.zeros(nBins), EkinBinEdges)
else:
logging.info("Error finding cells with VDFs!")
warnings.warn("Trouble finding cells with VDFs - pending new handling of these checks, the function may work or crash.")

if vlsvReader.check_variable('MinValue'):
fMin = vlsvReader.read_variable('MinValue',cid)
Expand Down Expand Up @@ -177,7 +178,7 @@ def get_spectrum_alongaxis_vel(vlsvReader,
if not vlsvReader.read_variable('vg_f_saved',cid):
return (False,np.zeros(nBins), VBinEdges)
else:
logging.info("Error finding cells with VDFs!")
warnings.warn("Trouble finding cells with VDFs - pending new handling of these checks, the function may work or crash.")

if vlsvReader.check_variable('MinValue'):
fMin = vlsvReader.read_variable('MinValue',cid)
Expand Down
Loading