Here are the examples of the python api numpy.testing.utils.assert_array_equal taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
45 Examples
3
Example 1
Project: py-earth Source File: test_knot_search.py
def test_knot_candidates():
np.random.seed(10)
m = 1000
x = np.random.normal(size=m)
p = np.random.normal(size=m)
p[np.random.binomial(p=.1, n=1, size=m) == 1] = 0.
x[np.random.binomial(p=.1, n=1, size=m) == 1] = 0.
predictor = PredictorDependentData.alloc(x)
candidates, candidates_idx = predictor.knot_candidates(
p, 5, 10, 0, 0, set())
assert_array_equal(candidates, x[candidates_idx])
assert_equal(len(candidates), len(set(candidates)))
3
Example 2
Project: pims Source File: test_factories.py
def test_customize_image_sequence():
dummy = lambda filename, **kwargs: np.zeros((1, 1))
reader = customize_image_sequence(dummy)
result = reader(['a', 'b', 'c'])
actual_len = len(result)
assert_equal(actual_len, 3)
for frame in result:
assert_array_equal(frame, np.zeros((1, 1)))
reader2 = customize_image_sequence(dummy, 'my_name')
assert_equal(reader2.__name__, 'my_name')
3
Example 3
Project: dask-learn Source File: test_grid_search.py
def test_grid_search_one_grid_point():
X, y = make_classification(n_samples=200, n_features=100, random_state=0)
param_dict = {"C": [1.0], "kernel": ["rbf"], "gamma": [0.1]}
clf = SVC()
cv = GridSearchCV(clf, param_dict)
cv.fit(X, y)
clf = SVC(C=1.0, kernel="rbf", gamma=0.1)
clf.fit(X, y)
tm.assert_array_equal(clf.dual_coef_, cv.best_estimator_.dual_coef_)
3
Example 4
def test_strictly_increasing(self):
data = np.linspace(1, 10, 10)
result = zigzag.peak_valley_pivots(data, 0.1, -0.1)
expected_result = np.zeros_like(data)
expected_result[0], expected_result[-1] = VALLEY, PEAK
assert_array_equal(result, expected_result)
3
Example 5
Project: ZigZag Source File: test_tsgeom.py
def test_strictly_increasing_but_less_than_threshold(self):
data = np.linspace(1.0, 1.05, 10)
result = zigzag.peak_valley_pivots(data, 0.1, -0.1)
expected_result = np.zeros_like(data)
expected_result[0], expected_result[-1] = VALLEY, PEAK
self.assertTrue(data[0] < data[len(data)-1])
assert_array_equal(result, expected_result)
3
Example 6
def test_strictly_decreasing(self):
data = np.linspace(10, 0, 10)
result = zigzag.peak_valley_pivots(data, 0.1, -0.1)
expected_result = np.zeros_like(data)
expected_result[0], expected_result[-1] = PEAK, VALLEY
assert_array_equal(result, expected_result)
3
Example 7
Project: ZigZag Source File: test_tsgeom.py
def test_strictly_decreasing_but_less_than_threshold(self):
data = np.linspace(1.05, 1.0, 10)
result = zigzag.peak_valley_pivots(data, 0.1, -0.1)
expected_result = np.zeros_like(data)
expected_result[0], expected_result[-1] = PEAK, VALLEY
assert_array_equal(result, expected_result)
3
Example 8
Project: ZigZag Source File: test_tsgeom.py
def test_single_peaked(self):
data = np.array([1.0, 1.2, 1.05])
result = zigzag.peak_valley_pivots(data, 0.1, -0.1)
expected_result = np.array([VALLEY, PEAK, VALLEY])
assert_array_equal(result, expected_result)
3
Example 9
Project: ZigZag Source File: test_tsgeom.py
def test_single_valleyed(self):
data = np.array([1.0, 0.9, 1.2])
result = zigzag.peak_valley_pivots(data, 0.1, -0.1)
expected_result = np.array([PEAK, VALLEY, PEAK])
assert_array_equal(result, expected_result)
3
Example 10
def test_increasing_kinked(self):
data = np.array([1.0, 0.99, 1.1])
result = zigzag.peak_valley_pivots(data, 0.1, -0.1)
expected_result = np.array([PEAK, VALLEY, PEAK])
assert_array_equal(result, expected_result)
3
Example 11
def test_decreasing_kinked(self):
data = np.array([1.0, 1.01, 0.9])
result = zigzag.peak_valley_pivots(data, 0.1, -0.1)
expected_result = np.array([VALLEY, PEAK, VALLEY])
assert_array_equal(result, expected_result)
3
Example 12
Project: ZigZag Source File: test_tsgeom.py
def test_pivots_to_modes(self):
data = np.array([1, 0, 0, 0, -1, 0, 0, 1, -1, 0, 1])
result = zigzag.pivots_to_modes(data)
expected_result = np.array([1, -1, -1, -1, -1, 1, 1, 1, -1, 1, 1])
assert_array_equal(result, expected_result)
3
Example 13
Project: rawpy Source File: basic_tests.py
def testBufferOpen():
with open(rawTestPath, 'rb') as rawfile:
with rawpy.imread(rawfile) as raw:
assert_array_equal(raw.raw_image.shape, [2844, 4288])
rgb = raw.postprocess()
print_stats(rgb)
save('test_buffer.tiff', rgb)
3
Example 14
def testProperties():
raw = rawpy.imread(rawTestPath)
print('black_level_per_channel:', raw.black_level_per_channel)
print('color_matrix:', raw.color_matrix)
print('rgb_xyz_matrix:', raw.rgb_xyz_matrix)
print('tone_curve:', raw.tone_curve)
assert_array_equal(raw.black_level_per_channel, [0,0,0,0])
# older versions have zeros at the end, was probably a bug
if rawpy.libraw_version >= (0,16):
assert_array_equal(raw.tone_curve, np.arange(65536))
3
Example 15
Project: arctic Source File: test_ts_read.py
def test_date_range_end_not_in_range(tickstore_lib):
DUMMY_DATA = [
{'a': 1.,
'b': 2.,
'index': dt(2013, 1, 1, tzinfo=mktz('Europe/London'))
},
{'b': 3.,
'c': 4.,
'index': dt(2013, 1, 2, 10, 1, tzinfo=mktz('Europe/London'))
},
]
tickstore_lib._chunk_size = 1
tickstore_lib.write('SYM', DUMMY_DATA)
with patch.object(tickstore_lib._collection, 'find', side_effect=tickstore_lib._collection.find) as f:
df = tickstore_lib.read('SYM', date_range=DateRange(20130101, dt(2013, 1, 2, 9, 0)), columns=None)
assert_array_equal(df['b'].values, np.array([2.]))
assert tickstore_lib._collection.find(f.call_args_list[-1][0][0]).count() == 1
3
Example 16
Project: neural-network-animation Source File: test_cbook.py
def test_string_seq(self):
actual = dmp(self.arr_s, self.arr1)
ind = [0, 1, 2, 5]
expected = (self.arr_s2.take(ind), self.arr2.take(ind))
assert_array_equal(actual[0], expected[0])
assert_array_equal(actual[1], expected[1])
3
Example 17
def test_datetime(self):
actual = dmp(self.arr_dt, self.arr3)
ind = [0, 1, 5]
expected = (self.arr_dt2.take(ind),
self.arr3.take(ind).compressed())
assert_array_equal(actual[0], expected[0])
assert_array_equal(actual[1], expected[1])
3
Example 18
def test_rgba(self):
actual = dmp(self.arr3, self.arr_rgba)
ind = [0, 1, 5]
expected = (self.arr3.take(ind).compressed(),
self.arr_rgba.take(ind, axis=0))
assert_array_equal(actual[0], expected[0])
assert_array_equal(actual[1], expected[1])
3
Example 19
Project: neural-network-animation Source File: test_colors.py
def test_colormap_endian():
"""
Github issue #1005: a bug in putmask caused erroneous
mapping of 1.0 when input from a non-native-byteorder
array.
"""
cmap = cm.get_cmap("jet")
# Test under, over, and invalid along with values 0 and 1.
a = [-0.5, 0, 0.5, 1, 1.5, np.nan]
for dt in ["f2", "f4", "f8"]:
anative = np.ma.masked_invalid(np.array(a, dtype=dt))
aforeign = anative.byteswap().newbyteorder()
#print(anative.dtype.isnative, aforeign.dtype.isnative)
assert_array_equal(cmap(anative), cmap(aforeign))
3
Example 20
Project: neural-network-animation Source File: test_colors.py
def test_BoundaryNorm():
"""
Github issue #1258: interpolation was failing with numpy
1.7 pre-release.
"""
# TODO: expand this into a more general test of BoundaryNorm.
boundaries = [0, 1.1, 2.2]
vals = [-1, 0, 2, 2.2, 4]
expected = [-1, 0, 2, 3, 3]
# ncolors != len(boundaries) - 1 triggers interpolation
ncolors = len(boundaries)
bn = mcolors.BoundaryNorm(boundaries, ncolors)
assert_array_equal(bn(vals), expected)
3
Example 21
Project: neural-network-animation Source File: test_colors.py
def test_LogNorm():
"""
LogNorm ignored clip, now it has the same
behavior as Normalize, e.g., values > vmax are bigger than 1
without clip, with clip they are 1.
"""
ln = mcolors.LogNorm(clip=True, vmax=5)
assert_array_equal(ln([1, 6]), [0, 1.0])
3
Example 22
Project: neural-network-animation Source File: test_colors.py
def _mask_tester(norm_instance, vals):
"""
Checks mask handling
"""
masked_array = np.ma.array(vals)
masked_array[0] = np.ma.masked
assert_array_equal(masked_array.mask, norm_instance(masked_array).mask)
3
Example 23
Project: elephant Source File: test_spike_train_correlation.py
def test_covariance_binned_same_spiketrains(self):
'''
Test if the covariation between two identical binned spike
trains evaluates to the expected 2x2 matrix.
'''
# Calculate correlation
binned_st = conv.BinnedSpikeTrain(
[self.st_0, self.st_0], t_start=0 * pq.ms, t_stop=50. * pq.ms,
binsize=1 * pq.ms)
target = sc.covariance(binned_st)
# Check dimensions
self.assertEqual(len(target), 2)
# Check result
assert_array_equal(target[0][0], target[1][1])
3
Example 24
Project: elephant Source File: test_spike_train_correlation.py
def test_corrcoef_binned_same_spiketrains(self):
'''
Test if the correlation coefficient between two identical binned spike
trains evaluates to a 2x2 matrix of ones.
'''
# Calculate correlation
binned_st = conv.BinnedSpikeTrain(
[self.st_0, self.st_0], t_start=0 * pq.ms, t_stop=50. * pq.ms,
binsize=1 * pq.ms)
target = sc.corrcoef(binned_st)
# Check dimensions
self.assertEqual(len(target), 2)
# Check result
assert_array_equal(target, 1.)
3
Example 25
Project: elephant Source File: test_statistics.py
def test_time_histogram_tstart_tstop(self):
# Start, stop short range
targ = np.array([2, 1])
histogram = es.time_histogram(self.spiketrains, binsize=pq.s,
t_start=5 * pq.s, t_stop=7 * pq.s)
assert_array_equal(targ, histogram[:, 0].magnitude)
# Test without t_stop
targ = np.array([4, 2, 1, 1, 2, 2, 1, 0, 1, 0])
histogram = es.time_histogram(self.spiketrains, binsize=1 * pq.s,
t_start=0 * pq.s)
assert_array_equal(targ, histogram[:, 0].magnitude)
# Test without t_start
histogram = es.time_histogram(self.spiketrains, binsize=1 * pq.s,
t_stop=10 * pq.s)
assert_array_equal(targ, histogram[:, 0].magnitude)
3
Example 26
Project: elephant Source File: test_statistics.py
def test_time_histogram_output(self):
# Normalization mean
histogram = es.time_histogram(self.spiketrains, binsize=pq.s,
output='mean')
targ = np.array([4, 2, 1, 1, 2, 2, 1, 0, 1, 0], dtype=float) / 2
assert_array_equal(targ.reshape(targ.size, 1), histogram.magnitude)
# Normalization rate
histogram = es.time_histogram(self.spiketrains, binsize=pq.s,
output='rate')
assert_array_equal(histogram.view(pq.Quantity),
targ.reshape(targ.size, 1) * 1 / pq.s)
# Normalization unspecified, raises error
self.assertRaises(ValueError, es.time_histogram, self.spiketrains,
binsize=pq.s, output=' ')
3
Example 27
Project: elephant Source File: test_statistics.py
def test_complexity_pdf(self):
targ = np.array([0.92, 0.01, 0.01, 0.06])
complexity = es.complexity_pdf(self.spiketrains, binsize=0.1*pq.s)
assert_array_equal(targ, complexity[:, 0].magnitude)
self.assertEqual(1, complexity[:, 0].magnitude.sum())
self.assertEqual(len(self.spiketrains)+1, len(complexity))
self.assertIsInstance(complexity, neo.AnalogSignalArray)
self.assertEqual(complexity.units, 1*pq.dimensionless)
0
Example 28
Project: dask-learn Source File: test_grid_search.py
def test_grid_search_dask_inputs():
# Test that the best estimator contains the right value for foo_param
dX = da.from_array(X, chunks=2)
dy = da.from_array(y, chunks=2)
clf = MockClassifier()
grid_search = GridSearchCV(clf, {'foo_param': [1, 2, 3]})
# make sure it selects the smallest parameter in case of ties
grid_search.fit(dX, dy)
assert grid_search.best_estimator_.foo_param == 2
for i, foo_i in enumerate([1, 2, 3]):
assert grid_search.grid_scores_[i][0] == {'foo_param': foo_i}
y_pred = grid_search.predict(dX)
assert isinstance(y_pred, da.Array)
tm.assert_array_equal(y_pred, X.sum(axis=1))
y_pred = grid_search.predict(X)
assert isinstance(y_pred, np.ndarray)
tm.assert_array_equal(y_pred, X.sum(axis=1))
0
Example 29
Project: rawpy Source File: basic_tests.py
def testFileOpenAndPostProcess():
raw = rawpy.imread(rawTestPath)
assert_array_equal(raw.raw_image.shape, [2844, 4288])
rgb = raw.postprocess(no_auto_bright=True, user_wb=raw.daylight_whitebalance)
assert_array_equal(rgb.shape, [2844, 4284, 3])
print_stats(rgb)
save('test_8daylight.tiff', rgb)
print('daylight white balance multipliers:', raw.daylight_whitebalance)
rgb = raw.postprocess(no_auto_bright=True, user_wb=raw.daylight_whitebalance)
print_stats(rgb)
save('test_8daylight2.tiff', rgb)
rgb = raw.postprocess(no_auto_bright=True, user_wb=raw.daylight_whitebalance,
output_bps=16)
print_stats(rgb)
save('test_16daylight.tiff', rgb)
# linear images are more useful for science (=no gamma correction)
# see http://www.mit.edu/~kimo/blog/linear.html
rgb = raw.postprocess(no_auto_bright=True, user_wb=raw.daylight_whitebalance,
gamma=(1,1), output_bps=16)
print_stats(rgb)
save('test_16daylight_linear.tiff', rgb)
0
Example 30
def testContextManager():
with rawpy.imread(rawTestPath) as raw:
assert_array_equal(raw.raw_image.shape, [2844, 4288])
0
Example 31
def testManualClose():
raw = rawpy.imread(rawTestPath)
assert_array_equal(raw.raw_image.shape, [2844, 4288])
raw.close()
0
Example 32
Project: rawpy Source File: basic_tests.py
def testWindowsFileLockRelease():
# see https://github.com/neothemachine/rawpy/issues/10
# we make a copy of the raw file which we will later remove
copyPath = rawTestPath + '-copy'
shutil.copyfile(rawTestPath, copyPath)
with rawpy.imread(copyPath) as raw:
rgb = raw.postprocess()
assert_array_equal(rgb.shape, [2844, 4284, 3])
print_stats(rgb)
# if the following does not throw an exception on Windows,
# then the file is not locked anymore, which is how it should be
os.remove(copyPath)
# we test the same using .close() instead of a context manager
shutil.copyfile(rawTestPath, copyPath)
raw = rawpy.imread(copyPath)
rgb = raw.postprocess()
raw.close()
os.remove(copyPath)
assert_array_equal(rgb.shape, [2844, 4284, 3])
0
Example 33
Project: rawpy Source File: basic_tests.py
def testSegfaultBug():
# https://github.com/neothemachine/rawpy/issues/7
im = rawpy.imread(rawTestPath).raw_image
assert_array_equal(im.shape, [2844, 4288])
print(im)
0
Example 34
def test_read(tickstore_lib):
data = [{'ASK': 1545.25,
'ASKSIZE': 1002.0,
'BID': 1545.0,
'BIDSIZE': 55.0,
'CUMVOL': 2187387.0,
'DELETED_TIME': 0,
'INSTRTYPE': 'FUT',
'PRICE': 1545.0,
'SIZE': 1.0,
'TICK_STATUS': 0,
'TRADEHIGH': 1561.75,
'TRADELOW': 1537.25,
'index': 1185076787070},
{'CUMVOL': 354.0,
'DELETED_TIME': 0,
'PRICE': 1543.75,
'SIZE': 354.0,
'TRADEHIGH': 1543.75,
'TRADELOW': 1543.75,
'index': 1185141600600}]
tickstore_lib.write('FEED::SYMBOL', data)
df = tickstore_lib.read('FEED::SYMBOL', columns=['BID', 'ASK', 'PRICE'])
assert_array_equal(df['ASK'].values, np.array([1545.25, np.nan]))
assert_array_equal(df['BID'].values, np.array([1545, np.nan]))
assert_array_equal(df['PRICE'].values, np.array([1545, 1543.75]))
assert_array_equal(df.index.values.astype('object'), np.array([1185076787070000000, 1185141600600000000]))
assert tickstore_lib._collection.find_one()['c'] == 2
0
Example 35
Project: arctic Source File: test_ts_read.py
def test_read_allow_secondary(tickstore_lib):
data = [{'ASK': 1545.25,
'ASKSIZE': 1002.0,
'BID': 1545.0,
'BIDSIZE': 55.0,
'CUMVOL': 2187387.0,
'DELETED_TIME': 0,
'INSTRTYPE': 'FUT',
'PRICE': 1545.0,
'SIZE': 1.0,
'TICK_STATUS': 0,
'TRADEHIGH': 1561.75,
'TRADELOW': 1537.25,
'index': 1185076787070},
{'CUMVOL': 354.0,
'DELETED_TIME': 0,
'PRICE': 1543.75,
'SIZE': 354.0,
'TRADEHIGH': 1543.75,
'TRADELOW': 1543.75,
'index': 1185141600600}]
tickstore_lib.write('FEED::SYMBOL', data)
with patch('pymongo.collection.Collection.find', side_effect=tickstore_lib._collection.find) as find:
with patch('pymongo.collection.Collection.with_options', side_effect=tickstore_lib._collection.with_options) as with_options:
with patch.object(tickstore_lib, '_read_preference', side_effect=tickstore_lib._read_preference) as read_pref:
df = tickstore_lib.read('FEED::SYMBOL', columns=['BID', 'ASK', 'PRICE'], allow_secondary=True)
assert read_pref.call_args_list == [call(True)]
assert with_options.call_args_list == [call(read_preference=ReadPreference.NEAREST)]
assert find.call_args_list == [call({'sy': 'FEED::SYMBOL'}, sort=[('s', 1)], projection={'s': 1, '_id': 0}),
call({'sy': 'FEED::SYMBOL', 's': {'$lte': dt(2007, 8, 21, 3, 59, 47, 70000)}},
projection={'sy': 1, 'cs.PRICE': 1, 'i': 1, 'cs.BID': 1, 's': 1, 'im': 1, 'v': 1, 'cs.ASK': 1})]
assert_array_equal(df['ASK'].values, np.array([1545.25, np.nan]))
assert tickstore_lib._collection.find_one()['c'] == 2
0
Example 36
Project: arctic Source File: test_ts_read.py
def test_read_multiple_symbols(tickstore_lib):
data1 = [{'ASK': 1545.25,
'ASKSIZE': 1002.0,
'BID': 1545.0,
'BIDSIZE': 55.0,
'CUMVOL': 2187387.0,
'DELETED_TIME': 0,
'INSTRTYPE': 'FUT',
'PRICE': 1545.0,
'SIZE': 1.0,
'TICK_STATUS': 0,
'TRADEHIGH': 1561.75,
'TRADELOW': 1537.25,
'index': 1185076787070}, ]
data2 = [{'CUMVOL': 354.0,
'DELETED_TIME': 0,
'PRICE': 1543.75,
'SIZE': 354.0,
'TRADEHIGH': 1543.75,
'TRADELOW': 1543.75,
'index': 1185141600600}]
tickstore_lib.write('BAR', data2)
tickstore_lib.write('FOO', data1)
df = tickstore_lib.read(['FOO', 'BAR'], columns=['BID', 'ASK', 'PRICE'])
assert all(df['SYMBOL'].values == ['FOO', 'BAR'])
assert_array_equal(df['ASK'].values, np.array([1545.25, np.nan]))
assert_array_equal(df['BID'].values, np.array([1545, np.nan]))
assert_array_equal(df['PRICE'].values, np.array([1545, 1543.75]))
assert_array_equal(df.index.values.astype('object'), np.array([1185076787070000000, 1185141600600000000]))
assert tickstore_lib._collection.find_one()['c'] == 1
0
Example 37
Project: arctic Source File: test_ts_read.py
def test_date_range(tickstore_lib):
tickstore_lib.write('SYM', DUMMY_DATA)
df = tickstore_lib.read('SYM', date_range=DateRange(20130101, 20130103), columns=None)
assert_array_equal(df['a'].values, np.array([1, np.nan, np.nan]))
assert_array_equal(df['b'].values, np.array([2., 3., 5.]))
assert_array_equal(df['c'].values, np.array([np.nan, 4., 6.]))
tickstore_lib.delete('SYM')
# Chunk every 3 symbols and lets have some fun
tickstore_lib._chunk_size = 3
tickstore_lib.write('SYM', DUMMY_DATA)
with patch('pymongo.collection.Collection.find', side_effect=tickstore_lib._collection.find) as f:
df = tickstore_lib.read('SYM', date_range=DateRange(20130101, 20130103), columns=None)
assert_array_equal(df['b'].values, np.array([2., 3., 5.]))
assert tickstore_lib._collection.find(f.call_args_list[-1][0][0]).count() == 1
df = tickstore_lib.read('SYM', date_range=DateRange(20130102, 20130103), columns=None)
assert_array_equal(df['b'].values, np.array([3., 5.]))
assert tickstore_lib._collection.find(f.call_args_list[-1][0][0]).count() == 1
df = tickstore_lib.read('SYM', date_range=DateRange(20130103, 20130103), columns=None)
assert_array_equal(df['b'].values, np.array([5.]))
assert tickstore_lib._collection.find(f.call_args_list[-1][0][0]).count() == 1
df = tickstore_lib.read('SYM', date_range=DateRange(20130102, 20130104), columns=None)
assert_array_equal(df['b'].values, np.array([3., 5., 7.]))
assert tickstore_lib._collection.find(f.call_args_list[-1][0][0]).count() == 2
df = tickstore_lib.read('SYM', date_range=DateRange(20130102, 20130105), columns=None)
assert_array_equal(df['b'].values, np.array([3., 5., 7., 9.]))
assert tickstore_lib._collection.find(f.call_args_list[-1][0][0]).count() == 2
df = tickstore_lib.read('SYM', date_range=DateRange(20130103, 20130104), columns=None)
assert_array_equal(df['b'].values, np.array([5., 7.]))
assert tickstore_lib._collection.find(f.call_args_list[-1][0][0]).count() == 2
df = tickstore_lib.read('SYM', date_range=DateRange(20130103, 20130105), columns=None)
assert_array_equal(df['b'].values, np.array([5., 7., 9.]))
assert tickstore_lib._collection.find(f.call_args_list[-1][0][0]).count() == 2
df = tickstore_lib.read('SYM', date_range=DateRange(20130104, 20130105), columns=None)
assert_array_equal(df['b'].values, np.array([7., 9.]))
assert tickstore_lib._collection.find(f.call_args_list[-1][0][0]).count() == 1
# Test the different open-closed behaviours
df = tickstore_lib.read('SYM', date_range=DateRange(20130104, 20130105, CLOSED_CLOSED), columns=None)
assert_array_equal(df['b'].values, np.array([7., 9.]))
df = tickstore_lib.read('SYM', date_range=DateRange(20130104, 20130105, CLOSED_OPEN), columns=None)
assert_array_equal(df['b'].values, np.array([7.]))
df = tickstore_lib.read('SYM', date_range=DateRange(20130104, 20130105, OPEN_CLOSED), columns=None)
assert_array_equal(df['b'].values, np.array([9.]))
df = tickstore_lib.read('SYM', date_range=DateRange(20130104, 20130105, OPEN_OPEN), columns=None)
assert_array_equal(df['b'].values, np.array([]))
0
Example 38
Project: arctic Source File: test_ts_read.py
def test_date_range_no_bounds(tickstore_lib):
DUMMY_DATA = [
{'a': 1.,
'b': 2.,
'index': dt(2013, 1, 1, tzinfo=mktz('Europe/London'))
},
{'a': 3.,
'b': 4.,
'index': dt(2013, 1, 30, tzinfo=mktz('Europe/London'))
},
{'b': 5.,
'c': 6.,
'index': dt(2013, 2, 2, 10, 1, tzinfo=mktz('Europe/London'))
},
]
tickstore_lib._chunk_size = 1
tickstore_lib.write('SYM', DUMMY_DATA)
# 1) No start, no end
df = tickstore_lib.read('SYM', columns=None)
assert_array_equal(df['b'].values, np.array([2., 4.]))
# 1.2) Start before the real start
df = tickstore_lib.read('SYM', date_range=DateRange(20121231), columns=None)
assert_array_equal(df['b'].values, np.array([2., 4.]))
# 2.1) Only go one month out
df = tickstore_lib.read('SYM', date_range=DateRange(20130101), columns=None)
assert_array_equal(df['b'].values, np.array([2., 4.]))
# 2.2) Only go one month out
df = tickstore_lib.read('SYM', date_range=DateRange(20130102), columns=None)
assert_array_equal(df['b'].values, np.array([4.]))
# 3) No start
df = tickstore_lib.read('SYM', date_range=DateRange(end=20130102), columns=None)
assert_array_equal(df['b'].values, np.array([2.]))
# 4) Outside bounds
df = tickstore_lib.read('SYM', date_range=DateRange(end=20131212), columns=None)
assert_array_equal(df['b'].values, np.array([2., 4., 5.]))
0
Example 39
Project: arctic Source File: test_ts_read.py
def test_date_range_BST(tickstore_lib):
DUMMY_DATA = [
{'a': 1.,
'b': 2.,
'index': dt(2013, 6, 1, 12, 00, tzinfo=mktz('Europe/London'))
},
{'a': 3.,
'b': 4.,
'index': dt(2013, 6, 1, 13, 00, tzinfo=mktz('Europe/London'))
},
]
tickstore_lib._chunk_size = 1
tickstore_lib.write('SYM', DUMMY_DATA)
df = tickstore_lib.read('SYM', columns=None)
assert_array_equal(df['b'].values, np.array([2., 4.]))
# df = tickstore_lib.read('SYM', columns=None, date_range=DateRange(dt(2013, 6, 1, 12),
# dt(2013, 6, 1, 13)))
# assert_array_equal(df['b'].values, np.array([2., 4.]))
df = tickstore_lib.read('SYM', columns=None, date_range=DateRange(dt(2013, 6, 1, 12, tzinfo=mktz('Europe/London')),
dt(2013, 6, 1, 13, tzinfo=mktz('Europe/London'))))
assert_array_equal(df['b'].values, np.array([2., 4.]))
df = tickstore_lib.read('SYM', columns=None, date_range=DateRange(dt(2013, 6, 1, 12, tzinfo=mktz('UTC')),
dt(2013, 6, 1, 13, tzinfo=mktz('UTC'))))
assert_array_equal(df['b'].values, np.array([4., ]))
0
Example 40
Project: arctic Source File: test_ts_read.py
def test_read_with_image(tickstore_lib):
DUMMY_DATA = [
{'a': 1.,
'index': dt(2013, 1, 1, 11, 00, tzinfo=mktz('Europe/London'))
},
{
'b': 4.,
'index': dt(2013, 1, 1, 12, 00, tzinfo=mktz('Europe/London'))
},
]
# Add an image
tickstore_lib.write('SYM', DUMMY_DATA)
tickstore_lib._collection.update_one({},
{'$set':
{'im': {'i':
{'a': 37.,
'c': 2.,
},
't': dt(2013, 1, 1, 10, tzinfo=mktz('Europe/London'))
}
}
}
)
dr = DateRange(dt(2013, 1, 1), dt(2013, 1, 2))
# tickstore_lib.read('SYM', columns=None)
df = tickstore_lib.read('SYM', columns=None, date_range=dr)
assert df['a'][0] == 1
# Read with the image as well - all columns
df = tickstore_lib.read('SYM', columns=None, date_range=dr, include_images=True)
assert set(df.columns) == set(('a', 'b', 'c'))
assert_array_equal(df['a'].values, np.array([37, 1, np.nan]))
assert_array_equal(df['b'].values, np.array([np.nan, np.nan, 4]))
assert_array_equal(df['c'].values, np.array([2, np.nan, np.nan]))
assert df.index[0] == dt(2013, 1, 1, 10, tzinfo=mktz('Europe/London'))
assert df.index[1] == dt(2013, 1, 1, 11, tzinfo=mktz('Europe/London'))
assert df.index[2] == dt(2013, 1, 1, 12, tzinfo=mktz('Europe/London'))
# Read just columns from the updates
df = tickstore_lib.read('SYM', columns=('a', 'b'), date_range=dr, include_images=True)
assert set(df.columns) == set(('a', 'b'))
assert_array_equal(df['a'].values, np.array([37, 1, np.nan]))
assert_array_equal(df['b'].values, np.array([np.nan, np.nan, 4]))
assert df.index[0] == dt(2013, 1, 1, 10, tzinfo=mktz('Europe/London'))
assert df.index[1] == dt(2013, 1, 1, 11, tzinfo=mktz('Europe/London'))
assert df.index[2] == dt(2013, 1, 1, 12, tzinfo=mktz('Europe/London'))
# Read one column from the updates
df = tickstore_lib.read('SYM', columns=('a',), date_range=dr, include_images=True)
assert set(df.columns) == set(('a',))
assert_array_equal(df['a'].values, np.array([37, 1, np.nan]))
assert df.index[0] == dt(2013, 1, 1, 10, tzinfo=mktz('Europe/London'))
assert df.index[1] == dt(2013, 1, 1, 11, tzinfo=mktz('Europe/London'))
assert df.index[2] == dt(2013, 1, 1, 12, tzinfo=mktz('Europe/London'))
# Read just the image column
df = tickstore_lib.read('SYM', columns=['c'], date_range=dr, include_images=True)
assert set(df.columns) == set(['c'])
assert_array_equal(df['c'].values, np.array([2, np.nan, np.nan]))
assert df.index[0] == dt(2013, 1, 1, 10, tzinfo=mktz('Europe/London'))
assert df.index[1] == dt(2013, 1, 1, 11, tzinfo=mktz('Europe/London'))
assert df.index[2] == dt(2013, 1, 1, 12, tzinfo=mktz('Europe/London'))
0
Example 41
Project: neural-network-animation Source File: test_colors.py
def test_cmap_and_norm_from_levels_and_colors2():
levels = [-1, 2, 2.5, 3]
colors = ['red', (0, 1, 0), 'blue', (0.5, 0.5, 0.5), (0.0, 0.0, 0.0, 1.0)]
clr = mcolors.colorConverter.to_rgba_array(colors)
bad = (0.1, 0.1, 0.1, 0.1)
no_color = (0.0, 0.0, 0.0, 0.0)
masked_value = 'masked_value'
# Define the test values which are of interest.
# Note: levels are lev[i] <= v < lev[i+1]
tests = [('both', None, {-2: clr[0],
-1: clr[1],
2: clr[2],
2.25: clr[2],
3: clr[4],
3.5: clr[4],
masked_value: bad}),
('min', -1, {-2: clr[0],
-1: clr[1],
2: clr[2],
2.25: clr[2],
3: no_color,
3.5: no_color,
masked_value: bad}),
('max', -1, {-2: no_color,
-1: clr[0],
2: clr[1],
2.25: clr[1],
3: clr[3],
3.5: clr[3],
masked_value: bad}),
('neither', -2, {-2: no_color,
-1: clr[0],
2: clr[1],
2.25: clr[1],
3: no_color,
3.5: no_color,
masked_value: bad}),
]
for extend, i1, cases in tests:
cmap, norm = mcolors.from_levels_and_colors(levels, colors[0:i1],
extend=extend)
cmap.set_bad(bad)
for d_val, expected_color in cases.items():
if d_val == masked_value:
d_val = np.ma.array([1], mask=True)
else:
d_val = [d_val]
assert_array_equal(expected_color, cmap(norm(d_val))[0],
'Wih extend={0!r} and data '
'value={1!r}'.format(extend, d_val))
assert_raises(ValueError, mcolors.from_levels_and_colors, levels, colors)
0
Example 42
Project: elephant Source File: test_spike_train_correlation.py
def test_cross_correlation_histogram(self):
'''
Test generic result of a cross-correlation histogram between two binned
spike trains.
'''
# Calculate CCH using Elephant (normal and binary version) with
# mode equal to 'full' (whole spike trains are correlated)
cch_clipped, bin_ids_clipped = sc.cross_correlation_histogram(
self.binned_st1, self.binned_st2, window='full',
binary=True)
cch_unclipped, bin_ids_unclipped = sc.cross_correlation_histogram(
self.binned_st1, self.binned_st2, window='full', binary=False)
cch_clipped_mem, bin_ids_clipped_mem = sc.cross_correlation_histogram(
self.binned_st1, self.binned_st2, window='full',
binary=True, method='memory')
cch_unclipped_mem, bin_ids_unclipped_mem = sc.cross_correlation_histogram(
self.binned_st1, self.binned_st2, window='full',
binary=False, method='memory')
# Check consistency two methods
assert_array_equal(
np.squeeze(cch_clipped.magnitude), np.squeeze(
cch_clipped_mem.magnitude))
assert_array_equal(
np.squeeze(cch_clipped.times), np.squeeze(
cch_clipped_mem.times))
assert_array_equal(
np.squeeze(cch_unclipped.magnitude), np.squeeze(
cch_unclipped_mem.magnitude))
assert_array_equal(
np.squeeze(cch_unclipped.times), np.squeeze(
cch_unclipped_mem.times))
assert_array_almost_equal(bin_ids_clipped, bin_ids_clipped_mem)
assert_array_almost_equal(bin_ids_unclipped, bin_ids_unclipped_mem)
# Check normal correlation Note: Use numpy correlate to verify result.
# Note: numpy conventions for input array 1 and input array 2 are
# swapped compared to Elephant!
mat1 = self.binned_st1.to_array()[0]
mat2 = self.binned_st2.to_array()[0]
target_numpy = np.correlate(mat2, mat1, mode='full')
assert_array_equal(
target_numpy, np.squeeze(cch_unclipped.magnitude))
# Check correlation using binary spike trains
mat1 = np.array(self.binned_st1.to_bool_array()[0], dtype=int)
mat2 = np.array(self.binned_st2.to_bool_array()[0], dtype=int)
target_numpy = np.correlate(mat2, mat1, mode='full')
assert_array_equal(
target_numpy, np.squeeze(cch_clipped.magnitude))
# Check the time axis and bin IDs of the resulting AnalogSignalArray
assert_array_almost_equal(
(bin_ids_clipped - 0.5) * self.binned_st1.binsize,
cch_unclipped.times)
assert_array_almost_equal(
(bin_ids_clipped - 0.5) * self.binned_st1.binsize,
cch_clipped.times)
# Calculate CCH using Elephant (normal and binary version) with
# mode equal to 'valid' (only completely overlapping intervals of the
# spike trains are correlated)
cch_clipped, bin_ids_clipped = sc.cross_correlation_histogram(
self.binned_st1, self.binned_st2, window='valid',
binary=True)
cch_unclipped, bin_ids_unclipped = sc.cross_correlation_histogram(
self.binned_st1, self.binned_st2, window='valid',
binary=False)
cch_clipped_mem, bin_ids_clipped_mem = sc.cross_correlation_histogram(
self.binned_st1, self.binned_st2, window='valid',
binary=True, method='memory')
cch_unclipped_mem, bin_ids_unclipped_mem = sc.cross_correlation_histogram(
self.binned_st1, self.binned_st2, window='valid',
binary=False, method='memory')
# Check consistency two methods
assert_array_equal(
np.squeeze(cch_clipped.magnitude), np.squeeze(
cch_clipped_mem.magnitude))
assert_array_equal(
np.squeeze(cch_clipped.times), np.squeeze(
cch_clipped_mem.times))
assert_array_equal(
np.squeeze(cch_unclipped.magnitude), np.squeeze(
cch_unclipped_mem.magnitude))
assert_array_equal(
np.squeeze(cch_unclipped.times), np.squeeze(
cch_unclipped_mem.times))
assert_array_equal(bin_ids_clipped, bin_ids_clipped_mem)
assert_array_equal(bin_ids_unclipped, bin_ids_unclipped_mem)
# Check normal correlation Note: Use numpy correlate to verify result.
# Note: numpy conventions for input array 1 and input array 2 are
# swapped compared to Elephant!
mat1 = self.binned_st1.to_array()[0]
mat2 = self.binned_st2.to_array()[0]
target_numpy = np.correlate(mat2, mat1, mode='valid')
assert_array_equal(
target_numpy, np.squeeze(cch_unclipped.magnitude))
# Check correlation using binary spike trains
mat1 = np.array(self.binned_st1.to_bool_array()[0], dtype=int)
mat2 = np.array(self.binned_st2.to_bool_array()[0], dtype=int)
target_numpy = np.correlate(mat2, mat1, mode='valid')
assert_array_equal(
target_numpy, np.squeeze(cch_clipped.magnitude))
# Check the time axis and bin IDs of the resulting AnalogSignalArray
assert_array_equal(
(bin_ids_clipped - 0.5) * self.binned_st1.binsize,
cch_unclipped.times)
assert_array_equal(
(bin_ids_clipped - 0.5) * self.binned_st1.binsize,
cch_clipped.times)
# Check for wrong window parameter setting
self.assertRaises(
KeyError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window='dsaij')
self.assertRaises(
KeyError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window='dsaij', method='memory')
0
Example 43
Project: elephant Source File: test_spike_train_correlation.py
def test_window(self):
'''Test if the window parameter is correctly interpreted.'''
cch_win, bin_ids = sc.cch(
self.binned_st1, self.binned_st2, window=[-30, 30])
cch_win_mem, bin_ids_mem = sc.cch(
self.binned_st1, self.binned_st2, window=[-30, 30])
assert_array_equal(bin_ids, np.arange(-30, 31, 1))
assert_array_equal(
(bin_ids - 0.5) * self.binned_st1.binsize, cch_win.times)
assert_array_equal(bin_ids_mem, np.arange(-30, 31, 1))
assert_array_equal(
(bin_ids_mem - 0.5) * self.binned_st1.binsize, cch_win.times)
assert_array_equal(cch_win, cch_win_mem)
cch_unclipped, _ = sc.cross_correlation_histogram(
self.binned_st1, self.binned_st2, window='full', binary=False)
assert_array_equal(cch_win, cch_unclipped[19:80])
cch_win, bin_ids = sc.cch(
self.binned_st1, self.binned_st2, window=[-25*pq.ms, 25*pq.ms])
cch_win_mem, bin_ids_mem = sc.cch(
self.binned_st1, self.binned_st2, window=[-25*pq.ms, 25*pq.ms],
method='memory')
assert_array_equal(bin_ids, np.arange(-25, 26, 1))
assert_array_equal(
(bin_ids - 0.5) * self.binned_st1.binsize, cch_win.times)
assert_array_equal(bin_ids_mem, np.arange(-25, 26, 1))
assert_array_equal(
(bin_ids_mem - 0.5) * self.binned_st1.binsize, cch_win.times)
assert_array_equal(cch_win, cch_win_mem)
_, bin_ids = sc.cch(
self.binned_st1, self.binned_st2, window=[20, 30])
_, bin_ids_mem = sc.cch(
self.binned_st1, self.binned_st2, window=[20, 30], method='memory')
assert_array_equal(bin_ids, np.arange(20, 31, 1))
assert_array_equal(bin_ids_mem, np.arange(20, 31, 1))
_, bin_ids = sc.cch(
self.binned_st1, self.binned_st2, window=[-30, -20])
_, bin_ids_mem = sc.cch(
self.binned_st1, self.binned_st2, window=[-30, -20],
method='memory')
assert_array_equal(bin_ids, np.arange(-30, -19, 1))
assert_array_equal(bin_ids_mem, np.arange(-30, -19, 1))
# Cehck for wrong assignments to the window parameter
self.assertRaises(
ValueError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window=[-60, 50])
self.assertRaises(
ValueError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window=[-60, 50], method='memory')
self.assertRaises(
ValueError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window=[-50, 60])
self.assertRaises(
ValueError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window=[-50, 60], method='memory')
self.assertRaises(
ValueError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window=[-25.5*pq.ms, 25*pq.ms])
self.assertRaises(
ValueError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window=[-25.5*pq.ms, 25*pq.ms], method='memory')
self.assertRaises(
ValueError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window=[-25*pq.ms, 25.5*pq.ms])
self.assertRaises(
ValueError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window=[-25*pq.ms, 25.5*pq.ms], method='memory')
self.assertRaises(
ValueError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window=[-60*pq.ms, 50*pq.ms])
self.assertRaises(
ValueError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window=[-60*pq.ms, 50*pq.ms], method='memory')
self.assertRaises(
ValueError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window=[-50*pq.ms, 60*pq.ms])
self.assertRaises(
ValueError, sc.cross_correlation_histogram, self.binned_st1,
self.binned_st2, window=[-50*pq.ms, 60*pq.ms], method='memory')
0
Example 44
Project: elephant Source File: test_statistics.py
def test_time_histogram(self):
targ = np.array([4, 2, 1, 1, 2, 2, 1, 0, 1, 0])
histogram = es.time_histogram(self.spiketrains, binsize=pq.s)
assert_array_equal(targ, histogram[:, 0].magnitude)
0
Example 45
Project: elephant Source File: test_statistics.py
def test_time_histogram_binary(self):
targ = np.array([2, 2, 1, 1, 2, 2, 1, 0, 1, 0])
histogram = es.time_histogram(self.spiketrains, binsize=pq.s,
binary=True)
assert_array_equal(targ, histogram[:, 0].magnitude)