Skip to content

Commit

Permalink
STY: remove plain asserts from constants, spatial, io and optimize mo…
Browse files Browse the repository at this point in the history
…dules.
  • Loading branch information
rgommers committed Jun 4, 2011
1 parent bde6957 commit 56ad534
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 25 deletions.
7 changes: 2 additions & 5 deletions scipy/constants/codata.py
Expand Up @@ -619,10 +619,7 @@ def find(sub=None, disp=False):


#sanity check #sanity check
for key in exact_values: for key in exact_values:
assert (exact_values[key][0]-value(key)) / value(key) < 1e-9 if not (exact_values[key][0]-value(key)) / value(key) < 1e-9:
raise ValueError("Constants.codata: exact values too far off.")


physical_constants.update(exact_values) physical_constants.update(exact_values)

#check update
for key in exact_values:
assert (exact_values[key][0]-value(key)) / value(key) == 0
8 changes: 7 additions & 1 deletion scipy/constants/tests/test_codata.py
@@ -1,6 +1,6 @@
import warnings import warnings


from scipy.constants import constants, codata, find from scipy.constants import constants, codata, find, value
from numpy.testing import assert_equal, assert_, run_module_suite, \ from numpy.testing import assert_equal, assert_, run_module_suite, \
assert_almost_equal assert_almost_equal


Expand Down Expand Up @@ -47,5 +47,11 @@ def test_2002_vs_2006():
assert_almost_equal(codata.value('magn. flux quantum'), assert_almost_equal(codata.value('magn. flux quantum'),
codata.value('mag. flux quantum')) codata.value('mag. flux quantum'))


def test_exact_values():
"""Check that updating stored values with exact ones worked."""
for key in codata.exact_values:
assert_((codata.exact_values[key][0] - value(key)) / value(key) == 0)


if __name__ == "__main__": if __name__ == "__main__":
run_module_suite() run_module_suite()
6 changes: 4 additions & 2 deletions scipy/io/matlab/mio5.py
Expand Up @@ -209,7 +209,8 @@ def read_var_header(self):
position in stream of next variable position in stream of next variable
''' '''
mdtype, byte_count = self._file_reader.read_full_tag() mdtype, byte_count = self._file_reader.read_full_tag()
assert byte_count > 0 if not byte_count > 0:
raise ValueError("Did not read any bytes")
next_pos = self.mat_stream.tell() + byte_count next_pos = self.mat_stream.tell() + byte_count
if mdtype == miCOMPRESSED: if mdtype == miCOMPRESSED:
# make new stream from compressed data # make new stream from compressed data
Expand All @@ -222,7 +223,8 @@ def read_var_header(self):
dcor = zlib.decompressobj() dcor = zlib.decompressobj()
stream = BytesIO(dcor.decompress(data)) stream = BytesIO(dcor.decompress(data))
# Check the stream is not so broken as to leave cruft behind # Check the stream is not so broken as to leave cruft behind
assert dcor.flush() == asbytes('') if not dcor.flush() == asbytes(''):
raise ValueError("Something wrong with byte stream.")
del data del data
self._matrix_reader.set_stream(stream) self._matrix_reader.set_stream(stream)
mdtype, byte_count = self._matrix_reader.read_full_tag() mdtype, byte_count = self._matrix_reader.read_full_tag()
Expand Down
24 changes: 15 additions & 9 deletions scipy/io/mmio.py
Expand Up @@ -184,24 +184,28 @@ def info(self, source):
[asstr(part.strip().lower()) for part in line.split()] [asstr(part.strip().lower()) for part in line.split()]
if not mmid.startswith('%%matrixmarket'): if not mmid.startswith('%%matrixmarket'):
raise ValueError('source is not in Matrix Market format') raise ValueError('source is not in Matrix Market format')

if not matrix == 'matrix':
assert matrix == 'matrix',`line` raise ValueError("Problem reading file header: " + line)


# ??? Is this necessary? I don't see 'dense' or 'sparse' in the spec # ??? Is this necessary? I don't see 'dense' or 'sparse' in the spec
# http://math.nist.gov/MatrixMarket/formats.html # http://math.nist.gov/MatrixMarket/formats.html
if format == 'dense': format = self.FORMAT_ARRAY if format == 'dense':
elif format == 'sparse': format = self.FORMAT_COORDINATE format = self.FORMAT_ARRAY
elif format == 'sparse':
format = self.FORMAT_COORDINATE


# skip comments # skip comments
while line.startswith(asbytes('%')): line = source.readline() while line.startswith(asbytes('%')): line = source.readline()


line = line.split() line = line.split()
if format == self.FORMAT_ARRAY: if format == self.FORMAT_ARRAY:
assert len(line)==2,`line` if not len(line) == 2:
raise ValueError("Header line not of length 2: " + line)
rows,cols = map(float, line) rows,cols = map(float, line)
entries = rows*cols entries = rows*cols
else: else:
assert len(line)==3,`line` if not len(line) == 3:
raise ValueError("Header line not of length 3: " + line)
rows, cols, entries = map(float, line) rows, cols, entries = map(float, line)


return (rows, cols, entries, format, field, symmetry) return (rows, cols, entries, format, field, symmetry)
Expand Down Expand Up @@ -380,7 +384,8 @@ def _parse_body(self, stream):
i = 0 i = 0
else: else:
i = j i = j
assert i in [0,j] and j==cols,`i,j,rows,cols` if not (i in [0,j] and j == cols):
raise ValueError("Parse error, did not read all lines.")


elif format == self.FORMAT_COORDINATE and coo_matrix is None: elif format == self.FORMAT_COORDINATE and coo_matrix is None:
# Read sparse matrix to dense when coo_matrix is not available. # Read sparse matrix to dense when coo_matrix is not available.
Expand All @@ -407,11 +412,12 @@ def _parse_body(self, stream):
else: else:
a[j,i] = aij a[j,i] = aij
k = k + 1 k = k + 1
assert k==entries,`k,entries` if not k == entries:
ValueError("Did not read all entries")


elif format == self.FORMAT_COORDINATE: elif format == self.FORMAT_COORDINATE:
# Read sparse COOrdinate format # Read sparse COOrdinate format

if entries == 0: if entries == 0:
# empty matrix # empty matrix
return coo_matrix((rows, cols), dtype=dtype) return coo_matrix((rows, cols), dtype=dtype)
Expand Down
9 changes: 6 additions & 3 deletions scipy/io/netcdf.py
Expand Up @@ -496,7 +496,8 @@ def _read_numrecs(self):


def _read_dim_array(self): def _read_dim_array(self):
header = self.fp.read(4) header = self.fp.read(4)
assert header in [ZERO, NC_DIMENSION] if not header in [ZERO, NC_DIMENSION]:
raise ValueError("Unexpected header.")
count = self._unpack_int() count = self._unpack_int()


for dim in range(count): for dim in range(count):
Expand All @@ -511,7 +512,8 @@ def _read_gatt_array(self):


def _read_att_array(self): def _read_att_array(self):
header = self.fp.read(4) header = self.fp.read(4)
assert header in [ZERO, NC_ATTRIBUTE] if not header in [ZERO, NC_ATTRIBUTE]:
raise ValueError("Unexpected header.")
count = self._unpack_int() count = self._unpack_int()


attributes = {} attributes = {}
Expand All @@ -522,7 +524,8 @@ def _read_att_array(self):


def _read_var_array(self): def _read_var_array(self):
header = self.fp.read(4) header = self.fp.read(4)
assert header in [ZERO, NC_VARIABLE] if not header in [ZERO, NC_VARIABLE]:
raise ValueError("Unexpected header.")


begin = 0 begin = 0
dtypes = {'names': [], 'formats': []} dtypes = {'names': [], 'formats': []}
Expand Down
12 changes: 8 additions & 4 deletions scipy/optimize/optimize.py
Expand Up @@ -1094,11 +1094,13 @@ def get_bracket_info(self):
xa,xb,xc = brack xa,xb,xc = brack
if (xa > xc): # swap so xa < xc can be assumed if (xa > xc): # swap so xa < xc can be assumed
dum = xa; xa=xc; xc=dum dum = xa; xa=xc; xc=dum
assert ((xa < xb) and (xb < xc)), "Not a bracketing interval." if not ((xa < xb) and (xb < xc)):
raise ValueError("Not a bracketing interval.")
fa = func(*((xa,)+args)) fa = func(*((xa,)+args))
fb = func(*((xb,)+args)) fb = func(*((xb,)+args))
fc = func(*((xc,)+args)) fc = func(*((xc,)+args))
assert ((fb<fa) and (fb < fc)), "Not a bracketing interval." if not ((fb<fa) and (fb < fc)):
raise ValueError("Not a bracketing interval.")
funcalls = 3 funcalls = 3
else: else:
raise ValueError("Bracketing interval must be " \ raise ValueError("Bracketing interval must be " \
Expand Down Expand Up @@ -1278,11 +1280,13 @@ def golden(func, args=(), brack=None, tol=_epsilon, full_output=0):
xa,xb,xc = brack xa,xb,xc = brack
if (xa > xc): # swap so xa < xc can be assumed if (xa > xc): # swap so xa < xc can be assumed
dum = xa; xa=xc; xc=dum dum = xa; xa=xc; xc=dum
assert ((xa < xb) and (xb < xc)), "Not a bracketing interval." if not ((xa < xb) and (xb < xc)):
raise ValueError("Not a bracketing interval.")
fa = func(*((xa,)+args)) fa = func(*((xa,)+args))
fb = func(*((xb,)+args)) fb = func(*((xb,)+args))
fc = func(*((xc,)+args)) fc = func(*((xc,)+args))
assert ((fb<fa) and (fb < fc)), "Not a bracketing interval." if not ((fb<fa) and (fb < fc)):
raise ValueError("Not a bracketing interval.")
funcalls = 3 funcalls = 3
else: else:
raise ValueError("Bracketing interval must be length 2 or 3 sequence.") raise ValueError("Bracketing interval must be length 2 or 3 sequence.")
Expand Down
3 changes: 2 additions & 1 deletion scipy/spatial/kdtree.py
Expand Up @@ -222,7 +222,8 @@ def __build(self, idx, maxes, mins):
greater_idx = np.nonzero(data>=split)[0] greater_idx = np.nonzero(data>=split)[0]
if len(less_idx)==0: if len(less_idx)==0:
# _still_ zero? all must have the same value # _still_ zero? all must have the same value
assert np.all(data==data[0]), "Troublesome data array: %s" % data if not np.all(data==data[0]):
raise ValueError("Troublesome data array: %s" % data)
split = data[0] split = data[0]
less_idx = np.arange(len(data)-1) less_idx = np.arange(len(data)-1)
greater_idx = np.array([len(data)-1]) greater_idx = np.array([len(data)-1])
Expand Down

0 comments on commit 56ad534

Please sign in to comment.