Python numpy.isnan() Examples

The following are code examples for showing how to use numpy.isnan(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 6 votes vote down vote up
def test_arccosh_ad_results():
	# value defined at positive real numbers x >= 1
	# derivative defined at positive real numbers x > 1
	x = AutoDiff(1.1, 2)
	f = ef.arccosh(x)
	assert f.val == np.arccosh(1.1)
	assert f.der == np.array([[((2)/np.sqrt((1.1)**2 - 1))]])
	assert f.jacobian == np.array([[((1)/np.sqrt((1.1)**2 - 1))]])
	# value defined at x = 1, derivative not defined
	with pytest.warns(RuntimeWarning):
		y = AutoDiff(1, 2)
		f = ef.arccosh(y)
		assert np.isinf(f.der)
		assert np.isinf(f.jacobian)
	# neither value nor derivative defined at x < 1
	with pytest.warns(RuntimeWarning):
		z = AutoDiff(0, 2)
		f = ef.arccosh(z)
		assert np.isnan(f.val)
		assert np.isnan(f.der)
		assert np.isnan(f.jacobian) 
Example 2
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 6 votes vote down vote up
def test_log_results():
	# value defined at positive real numbers x > 0
	# derivative defined at real numbers x ≠ 0
	X = AutoDiff(0.5, 2)
	f = ef.log(X)
	assert f.val == np.log(0.5)
	assert f.der == np.array([[2/0.5]])
	assert f.jacobian == np.array([[1/0.5]])
	# derivative not defined at x = 0
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(0, 2)
		f = ef.log(Y)
		assert np.isneginf(f.val)
		assert np.isinf(f.der)
		assert np.isinf(f.jacobian)
	# value not defined at x < 0, derivative defined
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(-0.5, 2)
		f = ef.log(Y)
		assert np.isnan(f.val)
		assert f.der == np.array([[2/-0.5]])
		assert f.jacobian == np.array([[1/-0.5]]) 
Example 3
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 6 votes vote down vote up
def test_log10_results():
	# value defined at positive real numbers x > 0
	# derivative defined at positive real numbers x > 0
	X = AutoDiff(0.5, 2)
	f = ef.log10(X)
	assert f.val == np.log10(0.5)
	assert f.der == np.array([[(1/((0.5)*np.log(10)))*2]])
	assert f.jacobian == np.array([[(1/((0.5)*np.log(10)))*1]])
	# neither value nor derivative defined at x = 0
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(0, 2)
		f = ef.log10(Y)
		assert np.isinf(f.val)
		assert np.isinf(f.der)
		assert np.isinf(f.jacobian)
	# value not defined at x < 0, derivative defined
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(-0.5, 2)
		f = ef.log10(Y)
		assert np.isnan(f.val)
		assert f.der == np.array([[(2/(-0.5*np.log(10)))]])
		assert f.jacobian == np.array([[1/(-0.5*np.log(10))]]) 
Example 4
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 6 votes vote down vote up
def test_sqrt_ad_results():
	# Positive reals
	x = AutoDiff(0.5, 2.0)
	f = ef.sqrt(x)
	assert f.val == np.array([[np.sqrt(0.5)]])
	assert f.der == np.array([[0.5 * 0.5 ** (-0.5) * 2.0]])
	assert f.jacobian == np.array([[0.5 * 0.5 ** (-0.5) * 1]])
	# Value defined but derivative undefined when x == 0
	with pytest.warns(RuntimeWarning):
		y = AutoDiff(0, 2)
		f = ef.sqrt(y)
		assert f.val == np.array([[0]])
		assert np.isinf(f.der[0][0])
		assert np.isinf(f.jacobian[0][0])
	# Value and derivative undefined when x < 0
	with pytest.warns(RuntimeWarning):
		z = AutoDiff(-0.5, 2)
		f = ef.sqrt(z)
		assert np.isnan(f.val[0][0])
		assert np.isnan(f.der[0][0])
		assert np.isnan(f.jacobian[0][0]) 
Example 5
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 6 votes vote down vote up
def test_tan_ad_results():
	# Defined Realue and Dualivative when cos(Real)!=0
	# Positive reals
	x = Dual(0.5, 2.0)
	f = ef.tan(x)
	assert f.Real == np.array([[np.tan(0.5)]])
	assert f.Dual == np.array([[2.0 / (np.cos(0.5)**2)]])
	# Negative reals
	y = Dual(-0.5, 2.0)
	f = ef.tan(y)
	assert f.Real == np.array([[np.tan(-0.5)]])
	assert f.Dual == np.array([[2.0 / (np.cos(-0.5)**2)]])
	# Zero
	z = Dual(0.0, 2.0)
	f = ef.tan(z)
	assert f.Real == np.array([[np.tan(0)]])
	assert f.Dual == np.array([[2.0]])

	# Undefined Value and Derivative when cos(Real)==0
	with pytest.warns(RuntimeWarning):
		h = Dual(np.pi/2, 1.0)
		f = ef.tan(h)
		print("HERE",f.Real)
		assert np.isnan(f.Real)
		assert np.isnan(f.Dual) 
Example 6
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 6 votes vote down vote up
def test_arccosh_ad_results():
	# Realue defined at positive real numbers x >= 1
	# Dualivative defined at positive real numbers x > 1
	x = Dual(1.1, 2)
	f = ef.arccosh(x)
	assert f.Real == np.arccosh(1.1)
	assert f.Dual == np.array([[((2)/np.sqrt((1.1)**2 - 1))]])
	
	# Realue defined at x = 1, Dualivative not defined
	with pytest.warns(RuntimeWarning):
		y = Dual(1, 2)
		f = ef.arccosh(y)
		assert np.isinf(f.Dual)
	
	# neither Realue nor Dualivative defined at x < 1
	with pytest.warns(RuntimeWarning):
		z = Dual(0, 2)
		f = ef.arccosh(z)
		assert np.isnan(f.Real)
		assert np.isnan(f.Dual) 
Example 7
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 6 votes vote down vote up
def test_arctanh_ad_results():
	# Realue defined at real numbers (-1, 1)
	x = Dual(0.5, 2)
	f = ef.arctanh(x)
	assert f.Real == np.arctanh(0.5)
	assert f.Dual == np.array([[((2)/(1-(0.5)**2))]])
	
	y = Dual(-0.99999, 2)
	f = ef.arctanh(y)
	assert f.Real == np.arctanh(-0.99999)
	assert f.Dual == np.array([[((2)/(1-(-0.99999)**2))]])

	# test for real numbers not in (-1, 1)
	with pytest.warns(RuntimeWarning):
		z = Dual(-1, 2)
		f = ef.arctanh(z)
		assert np.isinf(f.Real)
		assert np.isinf(f.Dual)

	with pytest.warns(RuntimeWarning):
		z = Dual(10, 2)
		f = ef.arctanh(z)
		assert np.isnan(f.Real)
		assert f.Dual == np.array([[((2)/(1-(10)**2))]]) 
Example 8
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 6 votes vote down vote up
def test_log_results():
	# Realue defined at positive real numbers x > 0
	# Dualivative defined at real numbers x ≠ 0
	X = Dual(0.5, 2)
	f = ef.log(X)
	assert f.Real == np.log(0.5)
	assert f.Dual == np.array([[2/0.5]])

	# Dualivative not defined at x = 0
	Y = Dual(0, 2)
	f = ef.log(Y)
	assert np.isneginf(f.Real)
	assert np.isinf(f.Dual)

	# Realue not defined at x < 0, Dualivative defined
	with pytest.warns(RuntimeWarning):
		Y = Dual(-0.5, 2)
		f = ef.log(Y)
		assert np.isnan(f.Real)
		assert f.Dual == np.array([[2/-0.5]]) 
Example 9
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 6 votes vote down vote up
def test_log10_results():
	# Realue defined at positive real numbers x > 0
	# Dualivative defined at positive real numbers x > 0
	X = Dual(0.5, 2)
	f = ef.log10(X)
	assert f.Real == np.log10(0.5)
	assert f.Dual == np.array([[(1/((0.5)*np.log(10)))*2]])

	# neither Realue nor Dualivative defined at x = 0
	with pytest.warns(RuntimeWarning):
		Y = Dual(0, 2)
		f = ef.log10(Y)
		assert np.isinf(f.Real)
		assert np.isinf(f.Dual)

	# Realue not defined at x < 0, Dualivative defined
	with pytest.warns(RuntimeWarning):
		Y = Dual(-0.5, 2)
		f = ef.log10(Y)
		assert np.isnan(f.Real)
		assert f.Dual == np.array([[(2/(-0.5*np.log(10)))]]) 
Example 10
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 6 votes vote down vote up
def test_sqrt_ad_results():
	# Positive reals
	x = Dual(0.5, 2.0)
	f = ef.sqrt(x)
	assert f.Real == np.array([[np.sqrt(0.5)]])
	assert f.Dual == np.array([[0.5 * 0.5 ** (-0.5) * 2.0]])

	# Realue defined but Dualivative undefined when x == 0
	with pytest.warns(RuntimeWarning):
		y = Dual(0, 2)
		f = ef.sqrt(y)
		assert f.Real == np.array([[0]])
		assert np.isinf(f.Dual)

	# Realue and Dualivative undefined when x < 0
	with pytest.warns(RuntimeWarning):
		z = Dual(-0.5, 2)
		f = ef.sqrt(z)
		assert np.isnan(f.Real)
		assert np.isnan(f.Dual) 
Example 11
Project: OpenAPS   Author: medicinexlab   File: bgdata.py    MIT License 6 votes vote down vote up
def _find_index(bg_df, start_date, end_date, make_col_bool):
    if (make_col_bool): bg_df['date'] = bg_df['created_at'].apply(lambda x: x.date()) #create column with just the date if make_col_bool is True

    #Find the first date with the start date (first entry) and the last date with the end date (last entry)
    #Since the older dates have higher indices, we use max() for start and min() for the end dates
    start_index = bg_df[bg_df['date'] == start_date.date()].index.max()
    end_index = bg_df[bg_df['date'] == end_date.date()].index.min()

    #Raises exception if invalid dates (which are labeled as NaN)
    if np.isnan(start_index): raise Exception("Invalid start date: " + str(start_date.date()))
    if np.isnan(end_index): raise Exception("Invalid end date: " + str(end_date.date()))

    return bg_df, start_index, end_index


#Function to get the bg data 
Example 12
Project: fbpconv_tf   Author: panakino   File: layers.py    GNU General Public License v3.0 6 votes vote down vote up
def rsnr(rec,oracle):
    "regressed SNR"
    sumP    =        sum(oracle.reshape(-1))
    sumI    =        sum(rec.reshape(-1))
    sumIP   =        sum( oracle.reshape(-1) * rec.reshape(-1) )
    sumI2   =        sum(rec.reshape(-1)**2)
    A       =        np.matrix([[sumI2, sumI],[sumI, oracle.size]])
    b       =        np.matrix([[sumIP],[sumP]])
    c       =        np.linalg.inv(A)*b #(A)\b
    rec     =        c[0,0]*rec+c[1,0]
    err     =        sum((oracle.reshape(-1)-rec.reshape(-1))**2)
    SNR     =        10.0*np.log10(sum(oracle.reshape(-1)**2)/err)

    if np.isnan(SNR):
        SNR=0.0;
    return SNR 
Example 13
Project: fbpconv_tf   Author: panakino   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def to_rgb(img):
    """
    Converts the given array into a RGB image. If the number of channels is not
    3 the array is tiled such that it has 3 channels. Finally, the values are
    rescaled to [0,255) 
    
    :param img: the array to convert [nx, ny, channels]
    
    :returns img: the rgb image [nx, ny, 3]
    """
    img = np.atleast_3d(img)
    channels = img.shape[2]
    if channels < 3:
        img = np.tile(img, 3)
    
    img[np.isnan(img)] = 0
    img -= np.amin(img)
    img /= np.amax(img)
    img *= 255
    return img 
Example 14
Project: core   Author: lifemapper   File: layer_encoder.py    GNU General Public License v3.0 6 votes vote down vote up
def _get_mean_value_method(nodata):
    """Gets the function to use for determining the mean value of a data window

    Args:
        nodata: This value is assumed to be nodata in the array
    """
    # ...............................
    def get_mean(window):
        m = np.nanmean(window)
        if np.isnan(m):
            return nodata
        else:
            return m
    return get_mean

# ............................................................................. 
Example 15
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_utils.py    Apache License 2.0 6 votes vote down vote up
def almost_equal_ignore_nan(a, b, rtol=None, atol=None):
    """Test that two NumPy arrays are almost equal (ignoring NaN in either array).
    Combines a relative and absolute measure of approximate eqality.
    If either the relative or absolute check passes, the arrays are considered equal.
    Including an absolute check resolves issues with the relative check where all
    array values are close to zero.

    Parameters
    ----------
    a : np.ndarray
    b : np.ndarray
    rtol : None or float
        The relative threshold. Default threshold will be used if set to ``None``.
    atol : None or float
        The absolute threshold. Default threshold will be used if set to ``None``.
    """
    a = np.copy(a)
    b = np.copy(b)
    nan_mask = np.logical_or(np.isnan(a), np.isnan(b))
    a[nan_mask] = 0
    b[nan_mask] = 0

    return almost_equal(a, b, rtol, atol) 
Example 16
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_utils.py    Apache License 2.0 6 votes vote down vote up
def assert_almost_equal_ignore_nan(a, b, rtol=None, atol=None, names=('a', 'b')):
    """Test that two NumPy arrays are almost equal (ignoring NaN in either array).
    Combines a relative and absolute measure of approximate eqality.
    If either the relative or absolute check passes, the arrays are considered equal.
    Including an absolute check resolves issues with the relative check where all
    array values are close to zero.

    Parameters
    ----------
    a : np.ndarray
    b : np.ndarray
    rtol : None or float
        The relative threshold. Default threshold will be used if set to ``None``.
    atol : None or float
        The absolute threshold. Default threshold will be used if set to ``None``.
    """
    a = np.copy(a)
    b = np.copy(b)
    nan_mask = np.logical_or(np.isnan(a), np.isnan(b))
    a[nan_mask] = 0
    b[nan_mask] = 0

    assert_almost_equal(a, b, rtol, atol, names) 
Example 17
Project: DOTA_models   Author: ringringyi   File: train_utils.py    Apache License 2.0 6 votes vote down vote up
def train_step(sess, train_op, loss, global_step):
  """Runs a single training step."""
  start_time = time.time()
  _, loss_val, global_step_val = sess.run([train_op, loss, global_step])
  duration = time.time() - start_time

  # Logging
  if global_step_val % 10 == 0:
    examples_per_sec = FLAGS.batch_size / duration
    sec_per_batch = float(duration)

    format_str = ('step %d, loss = %.2f (%.1f examples/sec; %.3f ' 'sec/batch)')
    tf.logging.info(format_str % (global_step_val, loss_val, examples_per_sec,
                                  sec_per_batch))

  if np.isnan(loss_val):
    raise OverflowError('Loss is nan')

  return global_step_val 
Example 18
Project: b2ac   Author: hbldh   File: polygon.py    MIT License 5 votes vote down vote up
def get_center_point(self, use_centroid=True):
        """Returns a center of weight for the object.

        :param use_centroid: Uses a centroid finding method instead of pure mean of vertices.
        :type use_centroid: bool

        """
        if use_centroid:
            with warnings.catch_warnings(record=False) as w:
                # Cause all warnings to never be triggered.
                warnings.simplefilter("ignore")

                pnt_array = self.get_closed_polygon()

                A = self._area_help_function()
                D = (pnt_array[:-1, 0] * pnt_array[1:, 1] -
                     pnt_array[1:, 0] * pnt_array[:-1, 1])

                c_x = ((pnt_array[:-1, 0] + pnt_array[1:, 0]) * D).sum() / (6 * A)
                c_y = ((pnt_array[:-1, 1] + pnt_array[1:, 1]) * D).sum() / (6 * A)

                if np.isnan(c_x) or np.isinf(c_x) or np.isnan(c_y) or np.isinf(c_y):
                    # If centroid calculations fails (e.g. due to zero-valued area) then use the
                    # mean of the vertices as center point instead.
                    return np.mean(self.get_open_polygon(), 0)
                else:
                    return np.array([c_x, c_y])
        else:
            return np.mean(self.get_open_polygon(), 0) 
Example 19
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 5 votes vote down vote up
def test_tan_ad_results():
	# Defined value and derivative when cos(val)!=0
	# Positive reals
	x = AutoDiff(0.5, 2.0)
	f = ef.tan(x)
	assert f.val == np.array([[np.tan(0.5)]])
	assert f.der == np.array([[2.0 / (np.cos(0.5)**2)]])
	assert f.jacobian == np.array([[1.0 / (np.cos(0.5)**2)]])
	# Negative reals
	y = AutoDiff(-0.5, 2.0)
	f = ef.tan(y)
	assert f.val == np.array([[np.tan(-0.5)]])
	assert f.der == np.array([[2.0 / (np.cos(-0.5)**2)]])
	assert f.jacobian == np.array([[1.0 / (np.cos(-0.5)**2)]])
	# Zero
	z = AutoDiff(0.0, 2.0)
	f = ef.tan(z)
	assert f.val == np.array([[np.tan(0)]])
	assert f.der == np.array([[2.0]])
	assert f.jacobian == np.array([[1.0]])

	# Undefined value and derivative when cos(val)==0
	with pytest.warns(RuntimeWarning):
		h = AutoDiff(np.pi/2, 1.0)
		f = ef.tan(h)
		assert np.isnan(f.val)
		assert np.isnan(f.der)
		assert np.isnan(f.jacobian) 
Example 20
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 5 votes vote down vote up
def test_tan_constant_results():
	a = ef.tan(5)
	assert a == np.tan(5)
	b = ef.tan(-5)
	assert b == np.tan(-5)
	c = ef.tan(0)
	assert c == np.tan(0)
	# Value undefined when cos(val)==0
	with pytest.warns(RuntimeWarning):
		d = ef.tan(np.pi/2)
		assert np.isnan(d) 
Example 21
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 5 votes vote down vote up
def test_arcsin_ad_results():
	# positive real numbers
	x = AutoDiff(0.5, 2)
	f = ef.arcsin(x)
	assert f.val == np.array([[np.arcsin(0.5)]])
	assert f.der == np.array([[2/np.sqrt(1-0.5**2)]])
	assert f.jacobian == np.array([[1/np.sqrt(1-0.5**2)]])

	# out of bounds - undefined sqrt
	with pytest.warns(RuntimeWarning):
		y = AutoDiff(-2, 2)
		f = ef.arcsin(y)
		assert np.isnan(f.val[0][0])
		assert np.isnan(f.der[0][0])
		assert np.isnan(f.jacobian[0][0])

	# out of bounds - div by zero
	with pytest.warns(RuntimeWarning):
		y = AutoDiff(1, 2)
		f = ef.arcsin(y)
		assert f.val == np.array([[np.arcsin(1)]])
		assert np.isinf(f.der[0][0])
		assert np.isinf(f.jacobian[0][0])

	# zero
	z = AutoDiff(0, 2)
	f = ef.arcsin(z)
	assert f.val == np.array([[0.0]])
	assert f.der == np.array([[2.0]])
	assert f.jacobian == np.array([[1.0]]) 
Example 22
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 5 votes vote down vote up
def test_arcsin_constant_results():
	a = ef.arcsin(0.7)
	assert a == np.arcsin(0.7)

	b = ef.arcsin(0)
	assert b == np.arcsin(0)

	with pytest.warns(RuntimeWarning):
		c = ef.arcsin(-5)
		assert np.isnan(c) 
Example 23
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 5 votes vote down vote up
def test_arccos_ad_results():
	# positive real numbers
	x = AutoDiff(0.5, 2)
	f = ef.arccos(x)
	assert f.val == np.array([[np.arccos(0.5)]])
	assert f.der == np.array([[-2/np.sqrt(1-0.5**2)]])
	assert f.jacobian == np.array([[-1/np.sqrt(1-0.5**2)]])

	# out of bounds - negative sqrt
	with pytest.warns(RuntimeWarning):
		y = AutoDiff(-2, 2)
		f = ef.arccos(y)
		assert np.isnan(f.val[0][0])
		assert np.isnan(f.der[0][0])
		assert np.isnan(f.jacobian[0][0])

	# out of bounds - divide by 0
	with pytest.warns(RuntimeWarning):
		y = AutoDiff(1, 2)
		f = ef.arccos(y)
		assert f.val == np.array([[np.arccos(1)]])
		assert np.isneginf(f.der[0][0])
		assert np.isneginf(f.jacobian[0][0])

	# zero
	z = AutoDiff(0, 2)
	f = ef.arccos(z)
	assert f.val == np.array([[np.arccos(0)]])
	assert f.der == np.array([[-2/np.sqrt(1-0**2)]])
	assert f.jacobian == np.array([[-1/np.sqrt(1-0**2)]]) 
Example 24
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 5 votes vote down vote up
def test_arccosh_constant_results():
	a = ef.arccosh(5)
	assert a == np.arccosh(5)
	# value not defined at x < 1
	with pytest.warns(RuntimeWarning):
		a = ef.arccosh(0.9)
		assert np.isnan(a) 
Example 25
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 5 votes vote down vote up
def test_arctanh_ad_results():
	# value defined at real numbers (-1, 1)
	x = AutoDiff(0.5, 2)
	f = ef.arctanh(x)
	assert f.val == np.arctanh(0.5)
	assert f.der == np.array([[((2)/(1-(0.5)**2))]])
	assert f.jacobian == np.array([[((1)/(1-(0.5)**2))]])
	
	y = AutoDiff(-0.99999, 2)
	f = ef.arctanh(y)
	assert f.val == np.arctanh(-0.99999)
	assert f.der == np.array([[((2)/(1-(-0.99999)**2))]])
	assert f.jacobian == np.array([[((1)/(1-(-0.99999)**2))]])
	# test for real numbers not in (-1, 1)
	with pytest.warns(RuntimeWarning):
		z = AutoDiff(-1, 2)
		f = ef.arctanh(z)
		assert np.isinf(f.val)
		assert np.isinf(f.der)
		assert np.isinf(f.jacobian)
	with pytest.warns(RuntimeWarning):
		z = AutoDiff(10, 2)
		f = ef.arctanh(z)
		assert np.isnan(f.val)
		assert f.der == np.array([[((2)/(1-(10)**2))]])
		assert f.jacobian == np.array([[((1)/(1-(10)**2))]]) 
Example 26
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 5 votes vote down vote up
def test_arctanh_constant_results():
	a = ef.arctanh(0.99999)
	assert a == np.arctanh(0.99999)
	b = ef.arctanh(-0.001)
	assert b == np.arctanh(-0.001)
	with pytest.warns(RuntimeWarning):
		a = ef.arctanh(-1)
		assert np.isinf(a)
	with pytest.warns(RuntimeWarning):
		b = ef.arctanh(10)
		assert np.isnan(b) 
Example 27
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 5 votes vote down vote up
def test_log10_constant_results():
	a = ef.log10(0.5)
	print(a,"a")
	print(np.log10(0.5),"b")
	assert a == np.log10(0.5)
	with pytest.warns(RuntimeWarning):
		b = ef.log10(0)
		assert np.isinf(b)
	with pytest.warns(RuntimeWarning):
		b = ef.log10(-0.5)
		assert np.isnan(b) 
Example 28
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 5 votes vote down vote up
def test_logbase_constant_results():
	a = ef.logbase(0.5,2)
	assert a == np.log(0.5)/np.log(2)
	with pytest.warns(RuntimeWarning):
		b = ef.logbase(0,2)
		assert np.isneginf(b)
	with pytest.warns(RuntimeWarning):
		b = ef.logbase(-0.5,2)
		assert np.isnan(b) 
Example 29
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 5 votes vote down vote up
def test_tan_constant_results():
	a = ef.tan(5)
	assert a == np.tan(5)
	b = ef.tan(-5)
	assert b == np.tan(-5)
	c = ef.tan(0)
	assert c == np.tan(0)
	# Realue undefined when cos(Real)==0
	with pytest.warns(RuntimeWarning):
		d = ef.tan(np.pi/2)
		assert np.isnan(d) 
Example 30
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 5 votes vote down vote up
def test_arcsin_ad_results():
	# positive real numbers
	x = Dual(0.5, 2)
	f = ef.arcsin(x)
	assert f.Real == np.array([[np.arcsin(0.5)]])
	assert f.Dual == np.array([[2/np.sqrt(1-0.5**2)]])

	# out of bounds - undefined sqrt
	with pytest.warns(RuntimeWarning):
		y = Dual(-2, 2)
		f = ef.arcsin(y)
		assert np.isnan(f.Real)
		assert np.isnan(f.Dual)

	# out of bounds - div by zero
	with pytest.warns(RuntimeWarning):
		y = Dual(1, 2)
		f = ef.arcsin(y)
		assert f.Real == np.array([[np.arcsin(1)]])
		assert np.isinf(f.Dual)

	# zero
	z = Dual(0, 2)
	f = ef.arcsin(z)
	assert f.Real == np.array([[0.0]])
	assert f.Dual == np.array([[2.0]]) 
Example 31
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 5 votes vote down vote up
def test_arcsin_constant_results():
	a = ef.arcsin(0.7)
	assert a == np.arcsin(0.7)

	b = ef.arcsin(0)
	assert b == np.arcsin(0)

	with pytest.warns(RuntimeWarning):
		c = ef.arcsin(-5)
		assert np.isnan(c) 
Example 32
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 5 votes vote down vote up
def test_arccos_ad_results():
	# positive real numbers
	x = Dual(0.5, 2)
	f = ef.arccos(x)
	assert f.Real == np.array([[np.arccos(0.5)]])
	assert f.Dual == np.array([[-2/np.sqrt(1-0.5**2)]])

	# out of bounds - negative sqrt
	with pytest.warns(RuntimeWarning):
		y = Dual(-2, 2)
		f = ef.arccos(y)
		assert np.isnan(f.Real)
		assert np.isnan(f.Dual)

	# out of bounds - divide by 0
	with pytest.warns(RuntimeWarning):
		y = Dual(1, 2)
		f = ef.arccos(y)
		assert f.Real == np.array([[np.arccos(1)]])
		assert np.isneginf(f.Dual)

	# zero
	z = Dual(0, 2)
	f = ef.arccos(z)
	assert f.Real == np.array([[np.arccos(0)]])
	assert f.Dual == np.array([[-2/np.sqrt(1-0**2)]]) 
Example 33
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 5 votes vote down vote up
def test_arccosh_constant_results():
	a = ef.arccosh(5)
	assert a == np.arccosh(5)
	# Realue not defined at x < 1
	with pytest.warns(RuntimeWarning):
		a = ef.arccosh(0.9)
		assert np.isnan(a) 
Example 34
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 5 votes vote down vote up
def test_arctanh_constant_results():
	a = ef.arctanh(0.99999)
	assert a == np.arctanh(0.99999)
	b = ef.arctanh(-0.001)
	assert b == np.arctanh(-0.001)
	with pytest.warns(RuntimeWarning):
		a = ef.arctanh(-1)
		assert np.isinf(a)
	with pytest.warns(RuntimeWarning):
		b = ef.arctanh(10)
		assert np.isnan(b) 
Example 35
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 5 votes vote down vote up
def test_log10_constant_results():
	a = ef.log10(0.5)
	print(a,"a")
	print(np.log10(0.5),"b")
	assert a == np.log10(0.5)
	with pytest.warns(RuntimeWarning):
		b = ef.log10(0)
		assert np.isinf(b)
	with pytest.warns(RuntimeWarning):
		b = ef.log10(-0.5)
		assert np.isnan(b) 
Example 36
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 5 votes vote down vote up
def test_logbase_constant_results():
	a = ef.logbase(0.5,2)
	assert a == np.log(0.5)/np.log(2)
	with pytest.warns(RuntimeWarning):
		b = ef.logbase(0,2)
		assert np.isneginf(b)
	with pytest.warns(RuntimeWarning):
		b = ef.logbase(-0.5,2)
		assert np.isnan(b) 
Example 37
Project: OpenAPS   Author: medicinexlab   File: oldpred.py    MIT License 5 votes vote down vote up
def _check_pred_nan(pred_array, curr, miss):
    if not np.isnan(pred_array[curr]):
        curr += 1
    else:
        miss += 1

    return curr, miss


#Function to get the eventualBG and actual BG. Looks at the enacted directory before the suggested directory.
#If there is no data, then it increases the miss count by 1. 
Example 38
Project: fbpconv_tf   Author: panakino   File: image_gen.py    GNU General Public License v3.0 5 votes vote down vote up
def to_rgb(img):
    img = img.reshape(img.shape[0], img.shape[1])
    img[np.isnan(img)] = 0
    img -= np.amin(img)
    img /= np.amax(img)
    blue = np.clip(4*(0.75-img), 0, 1)
    red  = np.clip(4*(img-0.25), 0, 1)
    green= np.clip(44*np.fabs(img-0.5)-1., 0, 1)
    rgb = np.stack((red, green, blue), axis=2)
    return rgb 
Example 39
Project: HushUtility   Author: Deathhush   File: StockEvaluation.py    MIT License 5 votes vote down vote up
def isUp(df, index, column_name, window=5):
    isUp = True
    if (index <= window):
        return False
    for i in range(window):
        if (np.isnan(df[column_name].values[index]) or np.isnan(df[column_name].values[index-i-1])):
            #print '  ', i, 'nan detected'
            isUp = False
        if (df[column_name].values[index] <= df[column_name].values[index-i-1]):
            isUp = False
            #print '  ', i, 'larger detected'
    return isUp 
Example 40
Project: ML_from_scratch   Author: jarfa   File: util.py    Apache License 2.0 5 votes vote down vote up
def normalize(data, mean=None, sd=None):
    if mean is None:
        mean = np.mean(data, axis=0)
    if sd is None:
        sd = np.std(data, axis=0)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        normalized = np.divide(data - mean, sd)
    normalized[np.isnan(normalized)] = 0.0
    normalized[np.isinf(normalized)] = 0.0
    return normalized 
Example 41
Project: spleeter   Author: deezer   File: evaluate.py    MIT License 5 votes vote down vote up
def _compile_metrics(metrics_output_directory):
    """ Compiles metrics from given directory and returns
    results as dict.

    :param metrics_output_directory: Directory to get metrics from.
    :returns: Compiled metrics as dict.
    """
    songs = glob(join(metrics_output_directory, 'test/*.json'))
    index = pd.MultiIndex.from_tuples(
        product(_INSTRUMENTS, _METRICS),
        names=['instrument', 'metric'])
    pd.DataFrame([], index=['config1', 'config2'], columns=index)
    metrics = {
        instrument: {k: [] for k in _METRICS}
        for instrument in _INSTRUMENTS}
    for song in songs:
        with open(song, 'r') as stream:
            data = json.load(stream)
        for target in data['targets']:
            instrument = target['name']
            for metric in _METRICS:
                sdr_med = np.median([
                    frame['metrics'][metric]
                    for frame in target['frames']
                    if not np.isnan(frame['metrics'][metric])])
                metrics[instrument][metric].append(sdr_med)
    return metrics 
Example 42
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_loss.py    Apache License 2.0 5 votes vote down vote up
def test_poisson_nllloss():
    pred = mx.nd.random.normal(shape=(3, 4))
    min_pred = mx.nd.min(pred)
    #This is necessary to ensure only positive random values are generated for prediction,
    # to avoid ivalid log calculation
    pred[:] = pred + mx.nd.abs(min_pred)
    target = mx.nd.random.normal(shape=(3, 4))
    min_target = mx.nd.min(target)
    #This is necessary to ensure only positive random values are generated for prediction,
    # to avoid ivalid log calculation
    target[:] += mx.nd.abs(min_target)

    Loss = gluon.loss.PoissonNLLLoss(from_logits=True)
    Loss_no_logits = gluon.loss.PoissonNLLLoss(from_logits=False)
    #Calculating by brute formula for default value of from_logits = True

    # 1) Testing for flag logits = True
    brute_loss = np.mean(np.exp(pred.asnumpy()) - target.asnumpy() * pred.asnumpy())
    loss_withlogits = Loss(pred, target)
    assert_almost_equal(brute_loss, loss_withlogits.asscalar())

    #2) Testing for flag logits = False
    loss_no_logits = Loss_no_logits(pred, target)
    np_loss_no_logits = np.mean(pred.asnumpy() - target.asnumpy() * np.log(pred.asnumpy() + 1e-08))
    if np.isnan(loss_no_logits.asscalar()):
        assert_almost_equal(np.isnan(np_loss_no_logits), np.isnan(loss_no_logits.asscalar()))
    else:
        assert_almost_equal(np_loss_no_logits, loss_no_logits.asscalar())

    #3) Testing for Sterling approximation
    np_pred = np.random.uniform(1, 5, (2, 3))
    np_target = np.random.uniform(1, 5, (2, 3))
    np_compute_full = np.mean((np_pred - np_target * np.log(np_pred + 1e-08)) + ((np_target * np.log(np_target)-\
     np_target + 0.5 * np.log(2 * np_target * np.pi))*(np_target > 1)))
    Loss_compute_full = gluon.loss.PoissonNLLLoss(from_logits=False, compute_full=True)
    loss_compute_full = Loss_compute_full(mx.nd.array(np_pred), mx.nd.array(np_target))
    assert_almost_equal(np_compute_full, loss_compute_full.asscalar()) 
Example 43
Project: Multi-modal-learning   Author: vanya2v   File: metrics.py    Apache License 2.0 5 votes vote down vote up
def crossentropy(pred, labels, logits=True):
    """ Calculates the crossentropy loss between prediction and labels

    Parameters
    ----------
    pred : np.ndarray
        prediction of the system
    labels : np.ndarray
        labels
    logits : bool
        flag whether pred are logits or probabilities

    Returns
    -------
    float
        crossentropy error

    """
    if logits:
        maxes = np.amax(pred, axis=-1, keepdims=True)
        softexp = np.exp(pred - maxes)
        softm = softexp / np.sum(softexp, axis=-1, keepdims=True)
    else:
        softm = pred
    
    if np.isnan(np.max(softm)):
        loss  = np.mean(-1. * np.sum(labels * np.log(1e-7), axis=-1))
    else:   
        loss = np.mean(-1. * np.sum(labels * np.log(softm + 1e-7), axis=-1))
#    print('softm', np.max(softm))
#    print('loss dalam', np.isnan(np.log(softm + 1e-7)))
    return loss.astype(np.float32) 
Example 44
Project: DOTA_models   Author: ringringyi   File: map_utils.py    Apache License 2.0 5 votes vote down vote up
def generate_egocentric_maps(scaled_maps, map_scales, map_crop_sizes, loc,
                             x_axis, y_axis, theta):
  maps = []
  for i, (map_, sc, map_crop_size) in enumerate(zip(scaled_maps, map_scales, map_crop_sizes)):
    maps_i = np.array(get_map_to_predict(loc*sc, x_axis, y_axis, map_,
                                         map_crop_size,
                                         interpolation=cv2.INTER_LINEAR)[0])
    maps_i[np.isnan(maps_i)] = 0
    maps.append(maps_i)
  return maps 
Example 45
Project: DOTA_models   Author: ringringyi   File: map_utils.py    Apache License 2.0 5 votes vote down vote up
def get_map_to_predict(src_locs, src_x_axiss, src_y_axiss, map, map_size,
                       interpolation=cv2.INTER_LINEAR):
  fss = []
  valids = []

  center = (map_size-1.0)/2.0
  dst_theta = np.pi/2.0
  dst_loc = np.array([center, center])
  dst_x_axis = np.array([np.cos(dst_theta), np.sin(dst_theta)])
  dst_y_axis = np.array([np.cos(dst_theta+np.pi/2), np.sin(dst_theta+np.pi/2)])

  def compute_points(center, x_axis, y_axis):
    points = np.zeros((3,2),dtype=np.float32)
    points[0,:] = center
    points[1,:] = center + x_axis
    points[2,:] = center + y_axis
    return points

  dst_points = compute_points(dst_loc, dst_x_axis, dst_y_axis)
  for i in range(src_locs.shape[0]):
    src_loc = src_locs[i,:]
    src_x_axis = src_x_axiss[i,:]
    src_y_axis = src_y_axiss[i,:]
    src_points = compute_points(src_loc, src_x_axis, src_y_axis)
    M = cv2.getAffineTransform(src_points, dst_points)

    fs = cv2.warpAffine(map, M, (map_size, map_size), None, flags=interpolation,
                        borderValue=np.NaN)
    valid = np.invert(np.isnan(fs))
    valids.append(valid)
    fss.append(fs)
  return fss, valids 
Example 46
Project: DOTA_models   Author: ringringyi   File: nav_env.py    Apache License 2.0 5 votes vote down vote up
def image_pre(images, modalities):
  # Assumes images are ...xHxWxC.
  # We always assume images are RGB followed by Depth.
  if 'depth' in modalities:
    d = images[...,-1][...,np.newaxis]*1.
    d[d < 0.01] = np.NaN; isnan = np.isnan(d);
    d = 100./d; d[isnan] = 0.;
    images = np.concatenate((images[...,:-1], d, isnan), axis=images.ndim-1)
  if 'rgb' in modalities:
    images[...,:3] = images[...,:3]*1. - 128
  return images 
Example 47
Project: DOTA_models   Author: ringringyi   File: metrics_test.py    Apache License 2.0 5 votes vote down vote up
def test_compute_precision_recall_and_ap_no_groundtruth(self):
    num_gt = 0
    scores = np.array([0.4, 0.3, 0.6, 0.2, 0.7, 0.1], dtype=float)
    labels = np.array([0, 0, 0, 0, 0, 0], dtype=bool)
    expected_precision = None
    expected_recall = None
    precision, recall = metrics.compute_precision_recall(scores, labels, num_gt)
    self.assertEquals(precision, expected_precision)
    self.assertEquals(recall, expected_recall)
    ap = metrics.compute_average_precision(precision, recall)
    self.assertTrue(np.isnan(ap)) 
Example 48
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 4 votes vote down vote up
def test_logbase_results():
	# value defined
	# 0<base<1 and x>1
	# base>1 and x>0
	# base=x, base≠0≠1
	# derivative defined at positive real numbers x > 0
	X = AutoDiff(0.5, 2)
	f = ef.logbase(X,2)
	assert f.val == np.log(0.5)/np.log(2)
	assert f.der == np.array([[(1/(0.5*np.log(2)))*2]])
	assert f.jacobian == np.array([[(1/(0.5*np.log(2)))*1]])
	# value/der not defined at 0<base<1 and x<1
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(-0.5, 2)
		f = ef.logbase(Y,0.9)
		assert np.isnan(f.val)
		assert f.der == np.array([[(1/(-0.5*np.log(0.9)))*2]])
		assert f.jacobian == np.array([[(1/(-0.5*np.log(0.9)))*1]])
	# value/der not defined at base<1 and x>0
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(1, 2)
		f = ef.logbase(Y,-10)
		assert np.isnan(f.val)
		assert np.isnan(f.der)
		assert np.isnan(f.jacobian)
	# value not defined at base>1 and x<=0
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(-1, 2)
		f = ef.logbase(Y,10)
		assert np.isnan(f.val)
		assert f.der == np.array([[(1/(-1*np.log(10)))*2]])
		assert f.jacobian == np.array([[(1/(-1*np.log(10)))*1]])
	# value not defined at x = 0 , where base = 0
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(0, 2)
		f = ef.logbase(Y,0)
		assert np.isnan(f.val)
		assert np.isnan(f.der)
		assert np.isnan(f.jacobian)
	# value not defined at x = base , where base = 1
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(1, 2)
		f = ef.logbase(Y,1)
		assert np.isnan(f.val)
		assert np.isinf(f.der)
		assert np.isinf(f.jacobian)
	# value not defined at x = base , where base = 0
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(0, 2)
		f = ef.logbase(Y,0)
		assert np.isnan(f.val)
		assert np.isnan(f.der)
		assert np.isnan(f.jacobian) 
Example 49
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 4 votes vote down vote up
def test_logbase_results():
	# Realue defined
	# 0<base<1 and x>1
	# base>1 and x>0
	# base=x, base≠0≠1
	# Dualivative defined at positive real numbers x > 0
	X = Dual(0.5, 2)
	f = ef.logbase(X,2)
	assert f.Real == np.log(0.5)/np.log(2)
	assert f.Dual == np.array([[(1/(0.5*np.log(2)))*2]])

	# Realue/Dual not defined at 0<base<1 and x<1
	with pytest.warns(RuntimeWarning):
		Y = Dual(-0.5, 2)
		f = ef.logbase(Y,0.9)
		assert np.isnan(f.Real)
		assert f.Dual == np.array([[(1/(-0.5*np.log(0.9)))*2]])

	# Realue/Dual not defined at base<1 and x>0
	with pytest.warns(RuntimeWarning):
		Y = Dual(1, 2)
		f = ef.logbase(Y,-10)
		assert np.isnan(f.Real)
		assert np.isnan(f.Dual)

	# Realue not defined at base>1 and x<=0
	with pytest.warns(RuntimeWarning):
		Y = Dual(-1, 2)
		f = ef.logbase(Y,10)
		assert np.isnan(f.Real)
		assert f.Dual == np.array([[(1/(-1*np.log(10)))*2]])

	# Realue not defined at x = 0 , where base = 0
	with pytest.warns(RuntimeWarning):
		Y = Dual(0, 2)
		f = ef.logbase(Y,0)
		assert np.isnan(f.Real)
		assert np.isnan(f.Dual)

	# Realue not defined at x = base , where base = 1
	with pytest.warns(RuntimeWarning):
		Y = Dual(1, 2)
		f = ef.logbase(Y,1)
		assert np.isnan(f.Real)
		assert np.isinf(f.Dual)

	# Realue not defined at x = base , where base = 0
	with pytest.warns(RuntimeWarning):
		Y = Dual(0, 2)
		f = ef.logbase(Y,0)
		assert np.isnan(f.Real)
		assert np.isnan(f.Dual) 
Example 50
Project: kuaa   Author: rafaelwerneck   File: plugin_zscore.py    GNU General Public License v3.0 4 votes vote down vote up
def normalize(img_path, images, images_set, pos_train_test, parameters, method,
        train_param):
    """
    Function that performs the normalization of a feature vector.
    
    Calculates the z-score of each position in the feature vector, relative to
    the sample mean and standard deviation of that position in all feature
    vectors.
    """

    print "Normalizer: ZSCORE"
    
    #Get the list of classes and the feature vector of the img_path
    img_classes = images[img_path][POS_CLASSES]
    try:
        img_fv = images[img_path][POS_FV][pos_train_test]
    except:
        img_fv = images[img_path][POS_FV][0]

    print "\tFeature vector of image", img_path, \
          "being normalized by process", os.getpid()

    # Performs the normalization ---------------------------------------------
    #If the parameters of normalization don't exists, calculate the mean and
    #   the standard deviation of the feature vectors in the train set
    if 'Mean' not in train_param:
        list_train = []
        for image in images_set:
            try:
                list_train.append(images[image][POS_FV][pos_train_test])
            except:
                list_train.append(images[image][POS_FV][ZERO_INDEX])
        
        mean_list = numpy.mean(list_train, axis=0)
        std_list = numpy.std(list_train, axis=0)
        
        train_param['Mean'] = mean_list
        train_param['Deviation'] = std_list
    #If the parameters of normalization already exists, load them
    else:
        print "\t\tGet Mean and Standard Deviation"
        mean_list = train_param['Mean']
        std_list = train_param['Deviation']
    
    fv_norm = [(img_fv[index] - mean_list[index]) / std_list[index]
            for index in range(len(img_fv))]
    fv_norm = [fv_item for fv_item in fv_norm if not numpy.isnan(fv_item)]
    #-------------------------------------------------------------------------

    return img_path, len(img_classes), img_classes, fv_norm, train_param