1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245 |
- import tempfile
- from numpy.testing import (assert_allclose, assert_almost_equal,
- assert_array_equal, assert_array_almost_equal_nulp)
- import numpy as np
- import datetime as datetime
- import pytest
- import matplotlib.mlab as mlab
- from matplotlib.cbook.deprecation import MatplotlibDeprecationWarning
- def _stride_repeat(*args, **kwargs):
- with pytest.warns(MatplotlibDeprecationWarning):
- return mlab.stride_repeat(*args, **kwargs)
- class TestStride:
- def get_base(self, x):
- y = x
- while y.base is not None:
- y = y.base
- return y
- def calc_window_target(self, x, NFFT, noverlap=0, axis=0):
- '''This is an adaptation of the original window extraction
- algorithm. This is here to test to make sure the new implementation
- has the same result'''
- step = NFFT - noverlap
- ind = np.arange(0, len(x) - NFFT + 1, step)
- n = len(ind)
- result = np.zeros((NFFT, n))
- # do the ffts of the slices
- for i in range(n):
- result[:, i] = x[ind[i]:ind[i]+NFFT]
- if axis == 1:
- result = result.T
- return result
- @pytest.mark.parametrize('shape', [(), (10, 1)], ids=['0D', '2D'])
- def test_stride_windows_invalid_input_shape(self, shape):
- x = np.arange(np.prod(shape)).reshape(shape)
- with pytest.raises(ValueError):
- mlab.stride_windows(x, 5)
- @pytest.mark.parametrize('n, noverlap',
- [(0, None), (11, None), (2, 2), (2, 3)],
- ids=['n less than 1', 'n greater than input',
- 'noverlap greater than n',
- 'noverlap equal to n'])
- def test_stride_windows_invalid_params(self, n, noverlap):
- x = np.arange(10)
- with pytest.raises(ValueError):
- mlab.stride_windows(x, n, noverlap)
- @pytest.mark.parametrize('shape', [(), (10, 1)], ids=['0D', '2D'])
- def test_stride_repeat_invalid_input_shape(self, shape):
- x = np.arange(np.prod(shape)).reshape(shape)
- with pytest.raises(ValueError):
- _stride_repeat(x, 5)
- @pytest.mark.parametrize('axis', [-1, 2],
- ids=['axis less than 0',
- 'axis greater than input shape'])
- def test_stride_repeat_invalid_axis(self, axis):
- x = np.array(0)
- with pytest.raises(ValueError):
- _stride_repeat(x, 5, axis=axis)
- def test_stride_repeat_n_lt_1_ValueError(self):
- x = np.arange(10)
- with pytest.raises(ValueError):
- _stride_repeat(x, 0)
- @pytest.mark.parametrize('axis', [0, 1], ids=['axis0', 'axis1'])
- @pytest.mark.parametrize('n', [1, 5], ids=['n1', 'n5'])
- def test_stride_repeat(self, n, axis):
- x = np.arange(10)
- y = _stride_repeat(x, n, axis=axis)
- expected_shape = [10, 10]
- expected_shape[axis] = n
- yr = np.repeat(np.expand_dims(x, axis), n, axis=axis)
- assert yr.shape == y.shape
- assert_array_equal(yr, y)
- assert tuple(expected_shape) == y.shape
- assert self.get_base(y) is x
- @pytest.mark.parametrize('axis', [0, 1], ids=['axis0', 'axis1'])
- @pytest.mark.parametrize('n, noverlap',
- [(1, 0), (5, 0), (15, 2), (13, -3)],
- ids=['n1-noverlap0', 'n5-noverlap0',
- 'n15-noverlap2', 'n13-noverlapn3'])
- def test_stride_windows(self, n, noverlap, axis):
- x = np.arange(100)
- y = mlab.stride_windows(x, n, noverlap=noverlap, axis=axis)
- expected_shape = [0, 0]
- expected_shape[axis] = n
- expected_shape[1 - axis] = 100 // (n - noverlap)
- yt = self.calc_window_target(x, n, noverlap=noverlap, axis=axis)
- assert yt.shape == y.shape
- assert_array_equal(yt, y)
- assert tuple(expected_shape) == y.shape
- assert self.get_base(y) is x
- @pytest.mark.parametrize('axis', [0, 1], ids=['axis0', 'axis1'])
- def test_stride_windows_n32_noverlap0_unflatten(self, axis):
- n = 32
- x = np.arange(n)[np.newaxis]
- x1 = np.tile(x, (21, 1))
- x2 = x1.flatten()
- y = mlab.stride_windows(x2, n, axis=axis)
- if axis == 0:
- x1 = x1.T
- assert y.shape == x1.shape
- assert_array_equal(y, x1)
- def test_stride_ensure_integer_type(self):
- N = 100
- x = np.full(N + 20, np.nan)
- y = x[10:-10]
- y[:] = 0.3
- # previous to #3845 lead to corrupt access
- y_strided = mlab.stride_windows(y, n=33, noverlap=0.6)
- assert_array_equal(y_strided, 0.3)
- # previous to #3845 lead to corrupt access
- y_strided = mlab.stride_windows(y, n=33.3, noverlap=0)
- assert_array_equal(y_strided, 0.3)
- # even previous to #3845 could not find any problematic
- # configuration however, let's be sure it's not accidentally
- # introduced
- y_strided = _stride_repeat(y, n=33.815)
- assert_array_equal(y_strided, 0.3)
- @pytest.fixture
- def tempcsv():
- with tempfile.TemporaryFile(suffix='csv', mode="w+", newline='') as fd:
- yield fd
- def test_csv2rec_names_with_comments(tempcsv):
- tempcsv.write('# comment\n1,2,3\n4,5,6\n')
- tempcsv.seek(0)
- array = mlab._csv2rec(tempcsv, names='a,b,c')
- assert len(array) == 2
- assert len(array.dtype) == 3
- @pytest.mark.parametrize('input, kwargs', [
- ('01/11/14\n'
- '03/05/76 12:00:01 AM\n'
- '07/09/83 5:17:34 PM\n'
- '06/20/2054 2:31:45 PM\n'
- '10/31/00 11:50:23 AM\n',
- {}),
- ('11/01/14\n'
- '05/03/76 12:00:01 AM\n'
- '09/07/83 5:17:34 PM\n'
- '20/06/2054 2:31:45 PM\n'
- '31/10/00 11:50:23 AM\n',
- {'dayfirst': True}),
- ('14/01/11\n'
- '76/03/05 12:00:01 AM\n'
- '83/07/09 5:17:34 PM\n'
- '2054/06/20 2:31:45 PM\n'
- '00/10/31 11:50:23 AM\n',
- {'yearfirst': True}),
- ], ids=['usdate', 'dayfirst', 'yearfirst'])
- def test_csv2rec_dates(tempcsv, input, kwargs):
- tempcsv.write(input)
- expected = [datetime.datetime(2014, 1, 11, 0, 0),
- datetime.datetime(1976, 3, 5, 0, 0, 1),
- datetime.datetime(1983, 7, 9, 17, 17, 34),
- datetime.datetime(2054, 6, 20, 14, 31, 45),
- datetime.datetime(2000, 10, 31, 11, 50, 23)]
- tempcsv.seek(0)
- array = mlab._csv2rec(tempcsv, names='a', **kwargs)
- assert_array_equal(array['a'].tolist(), expected)
- def _apply_window(*args, **kwargs):
- with pytest.warns(MatplotlibDeprecationWarning):
- return mlab.apply_window(*args, **kwargs)
- class TestWindow:
- def setup(self):
- np.random.seed(0)
- n = 1000
- self.sig_rand = np.random.standard_normal(n) + 100.
- self.sig_ones = np.ones(n)
- def check_window_apply_repeat(self, x, window, NFFT, noverlap):
- '''This is an adaptation of the original window application
- algorithm. This is here to test to make sure the new implementation
- has the same result'''
- step = NFFT - noverlap
- ind = np.arange(0, len(x) - NFFT + 1, step)
- n = len(ind)
- result = np.zeros((NFFT, n))
- if np.iterable(window):
- windowVals = window
- else:
- windowVals = window(np.ones(NFFT, x.dtype))
- # do the ffts of the slices
- for i in range(n):
- result[:, i] = windowVals * x[ind[i]:ind[i]+NFFT]
- return result
- def test_window_none_rand(self):
- res = mlab.window_none(self.sig_ones)
- assert_array_equal(res, self.sig_ones)
- def test_window_none_ones(self):
- res = mlab.window_none(self.sig_rand)
- assert_array_equal(res, self.sig_rand)
- def test_window_hanning_rand(self):
- targ = np.hanning(len(self.sig_rand)) * self.sig_rand
- res = mlab.window_hanning(self.sig_rand)
- assert_allclose(targ, res, atol=1e-06)
- def test_window_hanning_ones(self):
- targ = np.hanning(len(self.sig_ones))
- res = mlab.window_hanning(self.sig_ones)
- assert_allclose(targ, res, atol=1e-06)
- def test_apply_window_1D_axis1_ValueError(self):
- x = self.sig_rand
- window = mlab.window_hanning
- with pytest.raises(ValueError):
- _apply_window(x, window, axis=1, return_window=False)
- def test_apply_window_1D_els_wrongsize_ValueError(self):
- x = self.sig_rand
- window = mlab.window_hanning(np.ones(x.shape[0]-1))
- with pytest.raises(ValueError):
- _apply_window(x, window)
- def test_apply_window_0D_ValueError(self):
- x = np.array(0)
- window = mlab.window_hanning
- with pytest.raises(ValueError):
- _apply_window(x, window, axis=1, return_window=False)
- def test_apply_window_3D_ValueError(self):
- x = self.sig_rand[np.newaxis][np.newaxis]
- window = mlab.window_hanning
- with pytest.raises(ValueError):
- _apply_window(x, window, axis=1, return_window=False)
- def test_apply_window_hanning_1D(self):
- x = self.sig_rand
- window = mlab.window_hanning
- window1 = mlab.window_hanning(np.ones(x.shape[0]))
- y, window2 = _apply_window(x, window, return_window=True)
- yt = window(x)
- assert yt.shape == y.shape
- assert x.shape == y.shape
- assert_allclose(yt, y, atol=1e-06)
- assert_array_equal(window1, window2)
- def test_apply_window_hanning_1D_axis0(self):
- x = self.sig_rand
- window = mlab.window_hanning
- y = _apply_window(x, window, axis=0, return_window=False)
- yt = window(x)
- assert yt.shape == y.shape
- assert x.shape == y.shape
- assert_allclose(yt, y, atol=1e-06)
- def test_apply_window_hanning_els_1D_axis0(self):
- x = self.sig_rand
- window = mlab.window_hanning(np.ones(x.shape[0]))
- window1 = mlab.window_hanning
- y = _apply_window(x, window, axis=0, return_window=False)
- yt = window1(x)
- assert yt.shape == y.shape
- assert x.shape == y.shape
- assert_allclose(yt, y, atol=1e-06)
- def test_apply_window_hanning_2D_axis0(self):
- x = np.random.standard_normal([1000, 10]) + 100.
- window = mlab.window_hanning
- y = _apply_window(x, window, axis=0, return_window=False)
- yt = np.zeros_like(x)
- for i in range(x.shape[1]):
- yt[:, i] = window(x[:, i])
- assert yt.shape == y.shape
- assert x.shape == y.shape
- assert_allclose(yt, y, atol=1e-06)
- def test_apply_window_hanning_els1_2D_axis0(self):
- x = np.random.standard_normal([1000, 10]) + 100.
- window = mlab.window_hanning(np.ones(x.shape[0]))
- window1 = mlab.window_hanning
- y = _apply_window(x, window, axis=0, return_window=False)
- yt = np.zeros_like(x)
- for i in range(x.shape[1]):
- yt[:, i] = window1(x[:, i])
- assert yt.shape == y.shape
- assert x.shape == y.shape
- assert_allclose(yt, y, atol=1e-06)
- def test_apply_window_hanning_els2_2D_axis0(self):
- x = np.random.standard_normal([1000, 10]) + 100.
- window = mlab.window_hanning
- window1 = mlab.window_hanning(np.ones(x.shape[0]))
- y, window2 = _apply_window(x, window, axis=0, return_window=True)
- yt = np.zeros_like(x)
- for i in range(x.shape[1]):
- yt[:, i] = window1*x[:, i]
- assert yt.shape == y.shape
- assert x.shape == y.shape
- assert_allclose(yt, y, atol=1e-06)
- assert_array_equal(window1, window2)
- def test_apply_window_hanning_els3_2D_axis0(self):
- x = np.random.standard_normal([1000, 10]) + 100.
- window = mlab.window_hanning
- window1 = mlab.window_hanning(np.ones(x.shape[0]))
- y, window2 = _apply_window(x, window, axis=0, return_window=True)
- yt = _apply_window(x, window1, axis=0, return_window=False)
- assert yt.shape == y.shape
- assert x.shape == y.shape
- assert_allclose(yt, y, atol=1e-06)
- assert_array_equal(window1, window2)
- def test_apply_window_hanning_2D_axis1(self):
- x = np.random.standard_normal([10, 1000]) + 100.
- window = mlab.window_hanning
- y = _apply_window(x, window, axis=1, return_window=False)
- yt = np.zeros_like(x)
- for i in range(x.shape[0]):
- yt[i, :] = window(x[i, :])
- assert yt.shape == y.shape
- assert x.shape == y.shape
- assert_allclose(yt, y, atol=1e-06)
- def test_apply_window_hanning_2D__els1_axis1(self):
- x = np.random.standard_normal([10, 1000]) + 100.
- window = mlab.window_hanning(np.ones(x.shape[1]))
- window1 = mlab.window_hanning
- y = _apply_window(x, window, axis=1, return_window=False)
- yt = np.zeros_like(x)
- for i in range(x.shape[0]):
- yt[i, :] = window1(x[i, :])
- assert yt.shape == y.shape
- assert x.shape == y.shape
- assert_allclose(yt, y, atol=1e-06)
- def test_apply_window_hanning_2D_els2_axis1(self):
- x = np.random.standard_normal([10, 1000]) + 100.
- window = mlab.window_hanning
- window1 = mlab.window_hanning(np.ones(x.shape[1]))
- y, window2 = _apply_window(x, window, axis=1, return_window=True)
- yt = np.zeros_like(x)
- for i in range(x.shape[0]):
- yt[i, :] = window1 * x[i, :]
- assert yt.shape == y.shape
- assert x.shape == y.shape
- assert_allclose(yt, y, atol=1e-06)
- assert_array_equal(window1, window2)
- def test_apply_window_hanning_2D_els3_axis1(self):
- x = np.random.standard_normal([10, 1000]) + 100.
- window = mlab.window_hanning
- window1 = mlab.window_hanning(np.ones(x.shape[1]))
- y = _apply_window(x, window, axis=1, return_window=False)
- yt = _apply_window(x, window1, axis=1, return_window=False)
- assert yt.shape == y.shape
- assert x.shape == y.shape
- assert_allclose(yt, y, atol=1e-06)
- def test_apply_window_stride_windows_hanning_2D_n13_noverlapn3_axis0(self):
- x = self.sig_rand
- window = mlab.window_hanning
- yi = mlab.stride_windows(x, n=13, noverlap=2, axis=0)
- y = _apply_window(yi, window, axis=0, return_window=False)
- yt = self.check_window_apply_repeat(x, window, 13, 2)
- assert yt.shape == y.shape
- assert x.shape != y.shape
- assert_allclose(yt, y, atol=1e-06)
- def test_apply_window_hanning_2D_stack_axis1(self):
- ydata = np.arange(32)
- ydata1 = ydata+5
- ydata2 = ydata+3.3
- ycontrol1 = _apply_window(ydata1, mlab.window_hanning)
- ycontrol2 = mlab.window_hanning(ydata2)
- ydata = np.vstack([ydata1, ydata2])
- ycontrol = np.vstack([ycontrol1, ycontrol2])
- ydata = np.tile(ydata, (20, 1))
- ycontrol = np.tile(ycontrol, (20, 1))
- result = _apply_window(ydata, mlab.window_hanning, axis=1,
- return_window=False)
- assert_allclose(ycontrol, result, atol=1e-08)
- def test_apply_window_hanning_2D_stack_windows_axis1(self):
- ydata = np.arange(32)
- ydata1 = ydata+5
- ydata2 = ydata+3.3
- ycontrol1 = _apply_window(ydata1, mlab.window_hanning)
- ycontrol2 = mlab.window_hanning(ydata2)
- ydata = np.vstack([ydata1, ydata2])
- ycontrol = np.vstack([ycontrol1, ycontrol2])
- ydata = np.tile(ydata, (20, 1))
- ycontrol = np.tile(ycontrol, (20, 1))
- result = _apply_window(ydata, mlab.window_hanning, axis=1,
- return_window=False)
- assert_allclose(ycontrol, result, atol=1e-08)
- def test_apply_window_hanning_2D_stack_windows_axis1_unflatten(self):
- n = 32
- ydata = np.arange(n)
- ydata1 = ydata+5
- ydata2 = ydata+3.3
- ycontrol1 = _apply_window(ydata1, mlab.window_hanning)
- ycontrol2 = mlab.window_hanning(ydata2)
- ydata = np.vstack([ydata1, ydata2])
- ycontrol = np.vstack([ycontrol1, ycontrol2])
- ydata = np.tile(ydata, (20, 1))
- ycontrol = np.tile(ycontrol, (20, 1))
- ydata = ydata.flatten()
- ydata1 = mlab.stride_windows(ydata, 32, noverlap=0, axis=0)
- result = _apply_window(ydata1, mlab.window_hanning, axis=0,
- return_window=False)
- assert_allclose(ycontrol.T, result, atol=1e-08)
- class TestDetrend:
- def setup(self):
- np.random.seed(0)
- n = 1000
- x = np.linspace(0., 100, n)
- self.sig_zeros = np.zeros(n)
- self.sig_off = self.sig_zeros + 100.
- self.sig_slope = np.linspace(-10., 90., n)
- self.sig_slope_mean = x - x.mean()
- sig_rand = np.random.standard_normal(n)
- sig_sin = np.sin(x*2*np.pi/(n/100))
- sig_rand -= sig_rand.mean()
- sig_sin -= sig_sin.mean()
- self.sig_base = sig_rand + sig_sin
- self.atol = 1e-08
- def test_detrend_none_0D_zeros(self):
- input = 0.
- targ = input
- mlab.detrend_none(input)
- assert input == targ
- def test_detrend_none_0D_zeros_axis1(self):
- input = 0.
- targ = input
- mlab.detrend_none(input, axis=1)
- assert input == targ
- def test_detrend_str_none_0D_zeros(self):
- input = 0.
- targ = input
- mlab.detrend(input, key='none')
- assert input == targ
- def test_detrend_detrend_none_0D_zeros(self):
- input = 0.
- targ = input
- mlab.detrend(input, key=mlab.detrend_none)
- assert input == targ
- def test_detrend_none_0D_off(self):
- input = 5.5
- targ = input
- mlab.detrend_none(input)
- assert input == targ
- def test_detrend_none_1D_off(self):
- input = self.sig_off
- targ = input
- res = mlab.detrend_none(input)
- assert_array_equal(res, targ)
- def test_detrend_none_1D_slope(self):
- input = self.sig_slope
- targ = input
- res = mlab.detrend_none(input)
- assert_array_equal(res, targ)
- def test_detrend_none_1D_base(self):
- input = self.sig_base
- targ = input
- res = mlab.detrend_none(input)
- assert_array_equal(res, targ)
- def test_detrend_none_1D_base_slope_off_list(self):
- input = self.sig_base + self.sig_slope + self.sig_off
- targ = input.tolist()
- res = mlab.detrend_none(input.tolist())
- assert res == targ
- def test_detrend_none_2D(self):
- arri = [self.sig_base,
- self.sig_base + self.sig_off,
- self.sig_base + self.sig_slope,
- self.sig_base + self.sig_off + self.sig_slope]
- input = np.vstack(arri)
- targ = input
- res = mlab.detrend_none(input)
- assert_array_equal(res, targ)
- def test_detrend_none_2D_T(self):
- arri = [self.sig_base,
- self.sig_base + self.sig_off,
- self.sig_base + self.sig_slope,
- self.sig_base + self.sig_off + self.sig_slope]
- input = np.vstack(arri)
- targ = input
- res = mlab.detrend_none(input.T)
- assert_array_equal(res.T, targ)
- def test_detrend_mean_0D_zeros(self):
- input = 0.
- targ = 0.
- res = mlab.detrend_mean(input)
- assert_almost_equal(res, targ)
- def test_detrend_str_mean_0D_zeros(self):
- input = 0.
- targ = 0.
- res = mlab.detrend(input, key='mean')
- assert_almost_equal(res, targ)
- def test_detrend_detrend_mean_0D_zeros(self):
- input = 0.
- targ = 0.
- res = mlab.detrend(input, key=mlab.detrend_mean)
- assert_almost_equal(res, targ)
- def test_detrend_mean_0D_off(self):
- input = 5.5
- targ = 0.
- res = mlab.detrend_mean(input)
- assert_almost_equal(res, targ)
- def test_detrend_str_mean_0D_off(self):
- input = 5.5
- targ = 0.
- res = mlab.detrend(input, key='mean')
- assert_almost_equal(res, targ)
- def test_detrend_detrend_mean_0D_off(self):
- input = 5.5
- targ = 0.
- res = mlab.detrend(input, key=mlab.detrend_mean)
- assert_almost_equal(res, targ)
- def test_detrend_mean_1D_zeros(self):
- input = self.sig_zeros
- targ = self.sig_zeros
- res = mlab.detrend_mean(input)
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_mean_1D_base(self):
- input = self.sig_base
- targ = self.sig_base
- res = mlab.detrend_mean(input)
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_mean_1D_base_off(self):
- input = self.sig_base + self.sig_off
- targ = self.sig_base
- res = mlab.detrend_mean(input)
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_mean_1D_base_slope(self):
- input = self.sig_base + self.sig_slope
- targ = self.sig_base + self.sig_slope_mean
- res = mlab.detrend_mean(input)
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_mean_1D_base_slope_off(self):
- input = self.sig_base + self.sig_slope + self.sig_off
- targ = self.sig_base + self.sig_slope_mean
- res = mlab.detrend_mean(input)
- assert_allclose(res, targ, atol=1e-08)
- def test_detrend_mean_1D_base_slope_off_axis0(self):
- input = self.sig_base + self.sig_slope + self.sig_off
- targ = self.sig_base + self.sig_slope_mean
- res = mlab.detrend_mean(input, axis=0)
- assert_allclose(res, targ, atol=1e-08)
- def test_detrend_mean_1D_base_slope_off_list(self):
- input = self.sig_base + self.sig_slope + self.sig_off
- targ = self.sig_base + self.sig_slope_mean
- res = mlab.detrend_mean(input.tolist())
- assert_allclose(res, targ, atol=1e-08)
- def test_detrend_mean_1D_base_slope_off_list_axis0(self):
- input = self.sig_base + self.sig_slope + self.sig_off
- targ = self.sig_base + self.sig_slope_mean
- res = mlab.detrend_mean(input.tolist(), axis=0)
- assert_allclose(res, targ, atol=1e-08)
- def test_demean_0D_off(self):
- input = 5.5
- targ = 0.
- with pytest.warns(MatplotlibDeprecationWarning):
- res = mlab.demean(input, axis=None)
- assert_almost_equal(res, targ)
- def test_demean_1D_base_slope_off(self):
- input = self.sig_base + self.sig_slope + self.sig_off
- targ = self.sig_base + self.sig_slope_mean
- with pytest.warns(MatplotlibDeprecationWarning):
- res = mlab.demean(input)
- assert_allclose(res, targ, atol=1e-08)
- def test_demean_1D_base_slope_off_axis0(self):
- input = self.sig_base + self.sig_slope + self.sig_off
- targ = self.sig_base + self.sig_slope_mean
- with pytest.warns(MatplotlibDeprecationWarning):
- res = mlab.demean(input, axis=0)
- assert_allclose(res, targ, atol=1e-08)
- def test_demean_1D_base_slope_off_list(self):
- input = self.sig_base + self.sig_slope + self.sig_off
- targ = self.sig_base + self.sig_slope_mean
- with pytest.warns(MatplotlibDeprecationWarning):
- res = mlab.demean(input.tolist())
- assert_allclose(res, targ, atol=1e-08)
- def test_detrend_mean_2D_default(self):
- arri = [self.sig_off,
- self.sig_base + self.sig_off]
- arrt = [self.sig_zeros,
- self.sig_base]
- input = np.vstack(arri)
- targ = np.vstack(arrt)
- res = mlab.detrend_mean(input)
- assert_allclose(res, targ, atol=1e-08)
- def test_detrend_mean_2D_none(self):
- arri = [self.sig_off,
- self.sig_base + self.sig_off]
- arrt = [self.sig_zeros,
- self.sig_base]
- input = np.vstack(arri)
- targ = np.vstack(arrt)
- res = mlab.detrend_mean(input, axis=None)
- assert_allclose(res, targ,
- atol=1e-08)
- def test_detrend_mean_2D_none_T(self):
- arri = [self.sig_off,
- self.sig_base + self.sig_off]
- arrt = [self.sig_zeros,
- self.sig_base]
- input = np.vstack(arri).T
- targ = np.vstack(arrt)
- res = mlab.detrend_mean(input, axis=None)
- assert_allclose(res.T, targ,
- atol=1e-08)
- def test_detrend_mean_2D_axis0(self):
- arri = [self.sig_base,
- self.sig_base + self.sig_off,
- self.sig_base + self.sig_slope,
- self.sig_base + self.sig_off + self.sig_slope]
- arrt = [self.sig_base,
- self.sig_base,
- self.sig_base + self.sig_slope_mean,
- self.sig_base + self.sig_slope_mean]
- input = np.vstack(arri).T
- targ = np.vstack(arrt).T
- res = mlab.detrend_mean(input, axis=0)
- assert_allclose(res, targ,
- atol=1e-08)
- def test_detrend_mean_2D_axis1(self):
- arri = [self.sig_base,
- self.sig_base + self.sig_off,
- self.sig_base + self.sig_slope,
- self.sig_base + self.sig_off + self.sig_slope]
- arrt = [self.sig_base,
- self.sig_base,
- self.sig_base + self.sig_slope_mean,
- self.sig_base + self.sig_slope_mean]
- input = np.vstack(arri)
- targ = np.vstack(arrt)
- res = mlab.detrend_mean(input, axis=1)
- assert_allclose(res, targ,
- atol=1e-08)
- def test_detrend_mean_2D_axism1(self):
- arri = [self.sig_base,
- self.sig_base + self.sig_off,
- self.sig_base + self.sig_slope,
- self.sig_base + self.sig_off + self.sig_slope]
- arrt = [self.sig_base,
- self.sig_base,
- self.sig_base + self.sig_slope_mean,
- self.sig_base + self.sig_slope_mean]
- input = np.vstack(arri)
- targ = np.vstack(arrt)
- res = mlab.detrend_mean(input, axis=-1)
- assert_allclose(res, targ,
- atol=1e-08)
- def test_detrend_2D_default(self):
- arri = [self.sig_off,
- self.sig_base + self.sig_off]
- arrt = [self.sig_zeros,
- self.sig_base]
- input = np.vstack(arri)
- targ = np.vstack(arrt)
- res = mlab.detrend(input)
- assert_allclose(res, targ, atol=1e-08)
- def test_detrend_2D_none(self):
- arri = [self.sig_off,
- self.sig_base + self.sig_off]
- arrt = [self.sig_zeros,
- self.sig_base]
- input = np.vstack(arri)
- targ = np.vstack(arrt)
- res = mlab.detrend(input, axis=None)
- assert_allclose(res, targ, atol=1e-08)
- def test_detrend_str_mean_2D_axis0(self):
- arri = [self.sig_base,
- self.sig_base + self.sig_off,
- self.sig_base + self.sig_slope,
- self.sig_base + self.sig_off + self.sig_slope]
- arrt = [self.sig_base,
- self.sig_base,
- self.sig_base + self.sig_slope_mean,
- self.sig_base + self.sig_slope_mean]
- input = np.vstack(arri).T
- targ = np.vstack(arrt).T
- res = mlab.detrend(input, key='mean', axis=0)
- assert_allclose(res, targ,
- atol=1e-08)
- def test_detrend_str_constant_2D_none_T(self):
- arri = [self.sig_off,
- self.sig_base + self.sig_off]
- arrt = [self.sig_zeros,
- self.sig_base]
- input = np.vstack(arri).T
- targ = np.vstack(arrt)
- res = mlab.detrend(input, key='constant', axis=None)
- assert_allclose(res.T, targ,
- atol=1e-08)
- def test_detrend_str_default_2D_axis1(self):
- arri = [self.sig_base,
- self.sig_base + self.sig_off,
- self.sig_base + self.sig_slope,
- self.sig_base + self.sig_off + self.sig_slope]
- arrt = [self.sig_base,
- self.sig_base,
- self.sig_base + self.sig_slope_mean,
- self.sig_base + self.sig_slope_mean]
- input = np.vstack(arri)
- targ = np.vstack(arrt)
- res = mlab.detrend(input, key='default', axis=1)
- assert_allclose(res, targ,
- atol=1e-08)
- def test_detrend_detrend_mean_2D_axis0(self):
- arri = [self.sig_base,
- self.sig_base + self.sig_off,
- self.sig_base + self.sig_slope,
- self.sig_base + self.sig_off + self.sig_slope]
- arrt = [self.sig_base,
- self.sig_base,
- self.sig_base + self.sig_slope_mean,
- self.sig_base + self.sig_slope_mean]
- input = np.vstack(arri).T
- targ = np.vstack(arrt).T
- res = mlab.detrend(input, key=mlab.detrend_mean, axis=0)
- assert_allclose(res, targ,
- atol=1e-08)
- def test_demean_2D_default(self):
- arri = [self.sig_base,
- self.sig_base + self.sig_off,
- self.sig_base + self.sig_slope,
- self.sig_base + self.sig_off + self.sig_slope]
- arrt = [self.sig_base,
- self.sig_base,
- self.sig_base + self.sig_slope_mean,
- self.sig_base + self.sig_slope_mean]
- input = np.vstack(arri).T
- targ = np.vstack(arrt).T
- with pytest.warns(MatplotlibDeprecationWarning):
- res = mlab.demean(input)
- assert_allclose(res, targ,
- atol=1e-08)
- def test_demean_2D_none(self):
- arri = [self.sig_off,
- self.sig_base + self.sig_off]
- arrt = [self.sig_zeros,
- self.sig_base]
- input = np.vstack(arri)
- targ = np.vstack(arrt)
- with pytest.warns(MatplotlibDeprecationWarning):
- res = mlab.demean(input, axis=None)
- assert_allclose(res, targ,
- atol=1e-08)
- def test_demean_2D_axis0(self):
- arri = [self.sig_base,
- self.sig_base + self.sig_off,
- self.sig_base + self.sig_slope,
- self.sig_base + self.sig_off + self.sig_slope]
- arrt = [self.sig_base,
- self.sig_base,
- self.sig_base + self.sig_slope_mean,
- self.sig_base + self.sig_slope_mean]
- input = np.vstack(arri).T
- targ = np.vstack(arrt).T
- with pytest.warns(MatplotlibDeprecationWarning):
- res = mlab.demean(input, axis=0)
- assert_allclose(res, targ,
- atol=1e-08)
- def test_demean_2D_axis1(self):
- arri = [self.sig_base,
- self.sig_base + self.sig_off,
- self.sig_base + self.sig_slope,
- self.sig_base + self.sig_off + self.sig_slope]
- arrt = [self.sig_base,
- self.sig_base,
- self.sig_base + self.sig_slope_mean,
- self.sig_base + self.sig_slope_mean]
- input = np.vstack(arri)
- targ = np.vstack(arrt)
- with pytest.warns(MatplotlibDeprecationWarning):
- res = mlab.demean(input, axis=1)
- assert_allclose(res, targ,
- atol=1e-08)
- def test_demean_2D_axism1(self):
- arri = [self.sig_base,
- self.sig_base + self.sig_off,
- self.sig_base + self.sig_slope,
- self.sig_base + self.sig_off + self.sig_slope]
- arrt = [self.sig_base,
- self.sig_base,
- self.sig_base + self.sig_slope_mean,
- self.sig_base + self.sig_slope_mean]
- input = np.vstack(arri)
- targ = np.vstack(arrt)
- with pytest.warns(MatplotlibDeprecationWarning):
- res = mlab.demean(input, axis=-1)
- assert_allclose(res, targ,
- atol=1e-08)
- def test_detrend_bad_key_str_ValueError(self):
- input = self.sig_slope[np.newaxis]
- with pytest.raises(ValueError):
- mlab.detrend(input, key='spam')
- def test_detrend_bad_key_var_ValueError(self):
- input = self.sig_slope[np.newaxis]
- with pytest.raises(ValueError):
- mlab.detrend(input, key=5)
- def test_detrend_mean_0D_d0_ValueError(self):
- input = 5.5
- with pytest.raises(ValueError):
- mlab.detrend_mean(input, axis=0)
- def test_detrend_0D_d0_ValueError(self):
- input = 5.5
- with pytest.raises(ValueError):
- mlab.detrend(input, axis=0)
- def test_detrend_mean_1D_d1_ValueError(self):
- input = self.sig_slope
- with pytest.raises(ValueError):
- mlab.detrend_mean(input, axis=1)
- def test_detrend_1D_d1_ValueError(self):
- input = self.sig_slope
- with pytest.raises(ValueError):
- mlab.detrend(input, axis=1)
- def test_demean_1D_d1_ValueError(self):
- input = self.sig_slope
- with pytest.raises(ValueError), \
- pytest.warns(MatplotlibDeprecationWarning):
- mlab.demean(input, axis=1)
- def test_detrend_mean_2D_d2_ValueError(self):
- input = self.sig_slope[np.newaxis]
- with pytest.raises(ValueError):
- mlab.detrend_mean(input, axis=2)
- def test_detrend_2D_d2_ValueError(self):
- input = self.sig_slope[np.newaxis]
- with pytest.raises(ValueError):
- mlab.detrend(input, axis=2)
- def test_demean_2D_d2_ValueError(self):
- input = self.sig_slope[np.newaxis]
- with pytest.raises(ValueError), \
- pytest.warns(MatplotlibDeprecationWarning):
- mlab.demean(input, axis=2)
- def test_detrend_linear_0D_zeros(self):
- input = 0.
- targ = 0.
- res = mlab.detrend_linear(input)
- assert_almost_equal(res, targ)
- def test_detrend_linear_0D_off(self):
- input = 5.5
- targ = 0.
- res = mlab.detrend_linear(input)
- assert_almost_equal(res, targ)
- def test_detrend_str_linear_0D_off(self):
- input = 5.5
- targ = 0.
- res = mlab.detrend(input, key='linear')
- assert_almost_equal(res, targ)
- def test_detrend_detrend_linear_0D_off(self):
- input = 5.5
- targ = 0.
- res = mlab.detrend(input, key=mlab.detrend_linear)
- assert_almost_equal(res, targ)
- def test_detrend_linear_1d_off(self):
- input = self.sig_off
- targ = self.sig_zeros
- res = mlab.detrend_linear(input)
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_linear_1d_slope(self):
- input = self.sig_slope
- targ = self.sig_zeros
- res = mlab.detrend_linear(input)
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_linear_1d_slope_off(self):
- input = self.sig_slope + self.sig_off
- targ = self.sig_zeros
- res = mlab.detrend_linear(input)
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_str_linear_1d_slope_off(self):
- input = self.sig_slope + self.sig_off
- targ = self.sig_zeros
- res = mlab.detrend(input, key='linear')
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_detrend_linear_1d_slope_off(self):
- input = self.sig_slope + self.sig_off
- targ = self.sig_zeros
- res = mlab.detrend(input, key=mlab.detrend_linear)
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_linear_1d_slope_off_list(self):
- input = self.sig_slope + self.sig_off
- targ = self.sig_zeros
- res = mlab.detrend_linear(input.tolist())
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_linear_2D_ValueError(self):
- input = self.sig_slope[np.newaxis]
- with pytest.raises(ValueError):
- mlab.detrend_linear(input)
- def test_detrend_str_linear_2d_slope_off_axis0(self):
- arri = [self.sig_off,
- self.sig_slope,
- self.sig_slope + self.sig_off]
- arrt = [self.sig_zeros,
- self.sig_zeros,
- self.sig_zeros]
- input = np.vstack(arri).T
- targ = np.vstack(arrt).T
- res = mlab.detrend(input, key='linear', axis=0)
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_detrend_linear_1d_slope_off_axis1(self):
- arri = [self.sig_off,
- self.sig_slope,
- self.sig_slope + self.sig_off]
- arrt = [self.sig_zeros,
- self.sig_zeros,
- self.sig_zeros]
- input = np.vstack(arri).T
- targ = np.vstack(arrt).T
- res = mlab.detrend(input, key=mlab.detrend_linear, axis=0)
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_str_linear_2d_slope_off_axis0_notranspose(self):
- arri = [self.sig_off,
- self.sig_slope,
- self.sig_slope + self.sig_off]
- arrt = [self.sig_zeros,
- self.sig_zeros,
- self.sig_zeros]
- input = np.vstack(arri)
- targ = np.vstack(arrt)
- res = mlab.detrend(input, key='linear', axis=1)
- assert_allclose(res, targ, atol=self.atol)
- def test_detrend_detrend_linear_1d_slope_off_axis1_notranspose(self):
- arri = [self.sig_off,
- self.sig_slope,
- self.sig_slope + self.sig_off]
- arrt = [self.sig_zeros,
- self.sig_zeros,
- self.sig_zeros]
- input = np.vstack(arri)
- targ = np.vstack(arrt)
- res = mlab.detrend(input, key=mlab.detrend_linear, axis=1)
- assert_allclose(res, targ, atol=self.atol)
- @pytest.mark.parametrize('iscomplex', [False, True],
- ids=['real', 'complex'], scope='class')
- @pytest.mark.parametrize('sides', ['onesided', 'twosided', 'default'],
- scope='class')
- @pytest.mark.parametrize(
- 'fstims,len_x,NFFT_density,nover_density,pad_to_density,pad_to_spectrum',
- [
- ([], None, -1, -1, -1, -1),
- ([4], None, -1, -1, -1, -1),
- ([4, 5, 10], None, -1, -1, -1, -1),
- ([], None, None, -1, -1, None),
- ([], None, -1, -1, None, None),
- ([], None, None, -1, None, None),
- ([], 1024, 512, -1, -1, 128),
- ([], 256, -1, -1, 33, 257),
- ([], 255, 33, -1, -1, None),
- ([], 256, 128, -1, 256, 256),
- ([], None, -1, 32, -1, -1),
- ],
- ids=[
- 'nosig',
- 'Fs4',
- 'FsAll',
- 'nosig_noNFFT',
- 'nosig_nopad_to',
- 'nosig_noNFFT_no_pad_to',
- 'nosig_trim',
- 'nosig_odd',
- 'nosig_oddlen',
- 'nosig_stretch',
- 'nosig_overlap',
- ],
- scope='class')
- class TestSpectral:
- @pytest.fixture(scope='class', autouse=True)
- def stim(self, request, fstims, iscomplex, sides, len_x, NFFT_density,
- nover_density, pad_to_density, pad_to_spectrum):
- Fs = 100.
- x = np.arange(0, 10, 1 / Fs)
- if len_x is not None:
- x = x[:len_x]
- # get the stimulus frequencies, defaulting to None
- fstims = [Fs / fstim for fstim in fstims]
- # get the constants, default to calculated values
- if NFFT_density is None:
- NFFT_density_real = 256
- elif NFFT_density < 0:
- NFFT_density_real = NFFT_density = 100
- else:
- NFFT_density_real = NFFT_density
- if nover_density is None:
- nover_density_real = 0
- elif nover_density < 0:
- nover_density_real = nover_density = NFFT_density_real // 2
- else:
- nover_density_real = nover_density
- if pad_to_density is None:
- pad_to_density_real = NFFT_density_real
- elif pad_to_density < 0:
- pad_to_density = int(2**np.ceil(np.log2(NFFT_density_real)))
- pad_to_density_real = pad_to_density
- else:
- pad_to_density_real = pad_to_density
- if pad_to_spectrum is None:
- pad_to_spectrum_real = len(x)
- elif pad_to_spectrum < 0:
- pad_to_spectrum_real = pad_to_spectrum = len(x)
- else:
- pad_to_spectrum_real = pad_to_spectrum
- if pad_to_spectrum is None:
- NFFT_spectrum_real = NFFT_spectrum = pad_to_spectrum_real
- else:
- NFFT_spectrum_real = NFFT_spectrum = len(x)
- nover_spectrum = 0
- NFFT_specgram = NFFT_density
- nover_specgram = nover_density
- pad_to_specgram = pad_to_density
- NFFT_specgram_real = NFFT_density_real
- nover_specgram_real = nover_density_real
- if sides == 'onesided' or (sides == 'default' and not iscomplex):
- # frequencies for specgram, psd, and csd
- # need to handle even and odd differently
- if pad_to_density_real % 2:
- freqs_density = np.linspace(0, Fs / 2,
- num=pad_to_density_real,
- endpoint=False)[::2]
- else:
- freqs_density = np.linspace(0, Fs / 2,
- num=pad_to_density_real // 2 + 1)
- # frequencies for complex, magnitude, angle, and phase spectrums
- # need to handle even and odd differently
- if pad_to_spectrum_real % 2:
- freqs_spectrum = np.linspace(0, Fs / 2,
- num=pad_to_spectrum_real,
- endpoint=False)[::2]
- else:
- freqs_spectrum = np.linspace(0, Fs / 2,
- num=pad_to_spectrum_real // 2 + 1)
- else:
- # frequencies for specgram, psd, and csd
- # need to handle even and odd differentl
- if pad_to_density_real % 2:
- freqs_density = np.linspace(-Fs / 2, Fs / 2,
- num=2 * pad_to_density_real,
- endpoint=False)[1::2]
- else:
- freqs_density = np.linspace(-Fs / 2, Fs / 2,
- num=pad_to_density_real,
- endpoint=False)
- # frequencies for complex, magnitude, angle, and phase spectrums
- # need to handle even and odd differently
- if pad_to_spectrum_real % 2:
- freqs_spectrum = np.linspace(-Fs / 2, Fs / 2,
- num=2 * pad_to_spectrum_real,
- endpoint=False)[1::2]
- else:
- freqs_spectrum = np.linspace(-Fs / 2, Fs / 2,
- num=pad_to_spectrum_real,
- endpoint=False)
- freqs_specgram = freqs_density
- # time points for specgram
- t_start = NFFT_specgram_real // 2
- t_stop = len(x) - NFFT_specgram_real // 2 + 1
- t_step = NFFT_specgram_real - nover_specgram_real
- t_specgram = x[t_start:t_stop:t_step]
- if NFFT_specgram_real % 2:
- t_specgram += 1 / Fs / 2
- if len(t_specgram) == 0:
- t_specgram = np.array([NFFT_specgram_real / (2 * Fs)])
- t_spectrum = np.array([NFFT_spectrum_real / (2 * Fs)])
- t_density = t_specgram
- y = np.zeros_like(x)
- for i, fstim in enumerate(fstims):
- y += np.sin(fstim * x * np.pi * 2) * 10**i
- if iscomplex:
- y = y.astype('complex')
- # Interestingly, the instance on which this fixture is called is not
- # the same as the one on which a test is run. So we need to modify the
- # class itself when using a class-scoped fixture.
- cls = request.cls
- cls.Fs = Fs
- cls.sides = sides
- cls.fstims = fstims
- cls.NFFT_density = NFFT_density
- cls.nover_density = nover_density
- cls.pad_to_density = pad_to_density
- cls.NFFT_spectrum = NFFT_spectrum
- cls.nover_spectrum = nover_spectrum
- cls.pad_to_spectrum = pad_to_spectrum
- cls.NFFT_specgram = NFFT_specgram
- cls.nover_specgram = nover_specgram
- cls.pad_to_specgram = pad_to_specgram
- cls.t_specgram = t_specgram
- cls.t_density = t_density
- cls.t_spectrum = t_spectrum
- cls.y = y
- cls.freqs_density = freqs_density
- cls.freqs_spectrum = freqs_spectrum
- cls.freqs_specgram = freqs_specgram
- cls.NFFT_density_real = NFFT_density_real
- def check_freqs(self, vals, targfreqs, resfreqs, fstims):
- assert resfreqs.argmin() == 0
- assert resfreqs.argmax() == len(resfreqs)-1
- assert_allclose(resfreqs, targfreqs, atol=1e-06)
- for fstim in fstims:
- i = np.abs(resfreqs - fstim).argmin()
- assert vals[i] > vals[i+2]
- assert vals[i] > vals[i-2]
- def check_maxfreq(self, spec, fsp, fstims):
- # skip the test if there are no frequencies
- if len(fstims) == 0:
- return
- # if twosided, do the test for each side
- if fsp.min() < 0:
- fspa = np.abs(fsp)
- zeroind = fspa.argmin()
- self.check_maxfreq(spec[:zeroind], fspa[:zeroind], fstims)
- self.check_maxfreq(spec[zeroind:], fspa[zeroind:], fstims)
- return
- fstimst = fstims[:]
- spect = spec.copy()
- # go through each peak and make sure it is correctly the maximum peak
- while fstimst:
- maxind = spect.argmax()
- maxfreq = fsp[maxind]
- assert_almost_equal(maxfreq, fstimst[-1])
- del fstimst[-1]
- spect[maxind-5:maxind+5] = 0
- def test_spectral_helper_raises_complex_same_data(self):
- # test that mode 'complex' cannot be used if x is not y
- with pytest.raises(ValueError):
- mlab._spectral_helper(x=self.y, y=self.y+1, mode='complex')
- def test_spectral_helper_raises_magnitude_same_data(self):
- # test that mode 'magnitude' cannot be used if x is not y
- with pytest.raises(ValueError):
- mlab._spectral_helper(x=self.y, y=self.y+1, mode='magnitude')
- def test_spectral_helper_raises_angle_same_data(self):
- # test that mode 'angle' cannot be used if x is not y
- with pytest.raises(ValueError):
- mlab._spectral_helper(x=self.y, y=self.y+1, mode='angle')
- def test_spectral_helper_raises_phase_same_data(self):
- # test that mode 'phase' cannot be used if x is not y
- with pytest.raises(ValueError):
- mlab._spectral_helper(x=self.y, y=self.y+1, mode='phase')
- def test_spectral_helper_raises_unknown_mode(self):
- # test that unknown value for mode cannot be used
- with pytest.raises(ValueError):
- mlab._spectral_helper(x=self.y, mode='spam')
- def test_spectral_helper_raises_unknown_sides(self):
- # test that unknown value for sides cannot be used
- with pytest.raises(ValueError):
- mlab._spectral_helper(x=self.y, y=self.y, sides='eggs')
- def test_spectral_helper_raises_noverlap_gt_NFFT(self):
- # test that noverlap cannot be larger than NFFT
- with pytest.raises(ValueError):
- mlab._spectral_helper(x=self.y, y=self.y, NFFT=10, noverlap=20)
- def test_spectral_helper_raises_noverlap_eq_NFFT(self):
- # test that noverlap cannot be equal to NFFT
- with pytest.raises(ValueError):
- mlab._spectral_helper(x=self.y, NFFT=10, noverlap=10)
- def test_spectral_helper_raises_winlen_ne_NFFT(self):
- # test that the window length cannot be different from NFFT
- with pytest.raises(ValueError):
- mlab._spectral_helper(x=self.y, y=self.y, NFFT=10,
- window=np.ones(9))
- def test_single_spectrum_helper_raises_mode_default(self):
- # test that mode 'default' cannot be used with _single_spectrum_helper
- with pytest.raises(ValueError):
- mlab._single_spectrum_helper(x=self.y, mode='default')
- def test_single_spectrum_helper_raises_mode_psd(self):
- # test that mode 'psd' cannot be used with _single_spectrum_helper
- with pytest.raises(ValueError):
- mlab._single_spectrum_helper(x=self.y, mode='psd')
- def test_spectral_helper_psd(self):
- freqs = self.freqs_density
- spec, fsp, t = mlab._spectral_helper(x=self.y, y=self.y,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=self.nover_density,
- pad_to=self.pad_to_density,
- sides=self.sides,
- mode='psd')
- assert_allclose(fsp, freqs, atol=1e-06)
- assert_allclose(t, self.t_density, atol=1e-06)
- assert spec.shape[0] == freqs.shape[0]
- assert spec.shape[1] == self.t_specgram.shape[0]
- def test_spectral_helper_magnitude_specgram(self):
- freqs = self.freqs_specgram
- spec, fsp, t = mlab._spectral_helper(x=self.y, y=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='magnitude')
- assert_allclose(fsp, freqs, atol=1e-06)
- assert_allclose(t, self.t_specgram, atol=1e-06)
- assert spec.shape[0] == freqs.shape[0]
- assert spec.shape[1] == self.t_specgram.shape[0]
- def test_spectral_helper_magnitude_magnitude_spectrum(self):
- freqs = self.freqs_spectrum
- spec, fsp, t = mlab._spectral_helper(x=self.y, y=self.y,
- NFFT=self.NFFT_spectrum,
- Fs=self.Fs,
- noverlap=self.nover_spectrum,
- pad_to=self.pad_to_spectrum,
- sides=self.sides,
- mode='magnitude')
- assert_allclose(fsp, freqs, atol=1e-06)
- assert_allclose(t, self.t_spectrum, atol=1e-06)
- assert spec.shape[0] == freqs.shape[0]
- assert spec.shape[1] == 1
- def test_csd(self):
- freqs = self.freqs_density
- spec, fsp = mlab.csd(x=self.y, y=self.y+1,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=self.nover_density,
- pad_to=self.pad_to_density,
- sides=self.sides)
- assert_allclose(fsp, freqs, atol=1e-06)
- assert spec.shape == freqs.shape
- def test_csd_padding(self):
- """Test zero padding of csd()."""
- if self.NFFT_density is None: # for derived classes
- return
- sargs = dict(x=self.y, y=self.y+1, Fs=self.Fs, window=mlab.window_none,
- sides=self.sides)
- spec0, _ = mlab.csd(NFFT=self.NFFT_density, **sargs)
- spec1, _ = mlab.csd(NFFT=self.NFFT_density*2, **sargs)
- assert_almost_equal(np.sum(np.conjugate(spec0)*spec0).real,
- np.sum(np.conjugate(spec1/2)*spec1/2).real)
- def test_psd(self):
- freqs = self.freqs_density
- spec, fsp = mlab.psd(x=self.y,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=self.nover_density,
- pad_to=self.pad_to_density,
- sides=self.sides)
- assert spec.shape == freqs.shape
- self.check_freqs(spec, freqs, fsp, self.fstims)
- def test_psd_detrend_mean_func_offset(self):
- if self.NFFT_density is None:
- return
- ydata = np.zeros(self.NFFT_density)
- ydata1 = ydata+5
- ydata2 = ydata+3.3
- ydata = np.vstack([ydata1, ydata2])
- ydata = np.tile(ydata, (20, 1))
- ydatab = ydata.T.flatten()
- ydata = ydata.flatten()
- ycontrol = np.zeros_like(ydata)
- spec_g, fsp_g = mlab.psd(x=ydata,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- detrend=mlab.detrend_mean)
- spec_b, fsp_b = mlab.psd(x=ydatab,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- detrend=mlab.detrend_mean)
- spec_c, fsp_c = mlab.psd(x=ycontrol,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides)
- assert_array_equal(fsp_g, fsp_c)
- assert_array_equal(fsp_b, fsp_c)
- assert_allclose(spec_g, spec_c, atol=1e-08)
- # these should not be almost equal
- with pytest.raises(AssertionError):
- assert_allclose(spec_b, spec_c, atol=1e-08)
- def test_psd_detrend_mean_str_offset(self):
- if self.NFFT_density is None:
- return
- ydata = np.zeros(self.NFFT_density)
- ydata1 = ydata+5
- ydata2 = ydata+3.3
- ydata = np.vstack([ydata1, ydata2])
- ydata = np.tile(ydata, (20, 1))
- ydatab = ydata.T.flatten()
- ydata = ydata.flatten()
- ycontrol = np.zeros_like(ydata)
- spec_g, fsp_g = mlab.psd(x=ydata,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- detrend='mean')
- spec_b, fsp_b = mlab.psd(x=ydatab,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- detrend='mean')
- spec_c, fsp_c = mlab.psd(x=ycontrol,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides)
- assert_array_equal(fsp_g, fsp_c)
- assert_array_equal(fsp_b, fsp_c)
- assert_allclose(spec_g, spec_c, atol=1e-08)
- # these should not be almost equal
- with pytest.raises(AssertionError):
- assert_allclose(spec_b, spec_c, atol=1e-08)
- def test_psd_detrend_linear_func_trend(self):
- if self.NFFT_density is None:
- return
- ydata = np.arange(self.NFFT_density)
- ydata1 = ydata+5
- ydata2 = ydata+3.3
- ydata = np.vstack([ydata1, ydata2])
- ydata = np.tile(ydata, (20, 1))
- ydatab = ydata.T.flatten()
- ydata = ydata.flatten()
- ycontrol = np.zeros_like(ydata)
- spec_g, fsp_g = mlab.psd(x=ydata,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- detrend=mlab.detrend_linear)
- spec_b, fsp_b = mlab.psd(x=ydatab,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- detrend=mlab.detrend_linear)
- spec_c, fsp_c = mlab.psd(x=ycontrol,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides)
- assert_array_equal(fsp_g, fsp_c)
- assert_array_equal(fsp_b, fsp_c)
- assert_allclose(spec_g, spec_c, atol=1e-08)
- # these should not be almost equal
- with pytest.raises(AssertionError):
- assert_allclose(spec_b, spec_c, atol=1e-08)
- def test_psd_detrend_linear_str_trend(self):
- if self.NFFT_density is None:
- return
- ydata = np.arange(self.NFFT_density)
- ydata1 = ydata+5
- ydata2 = ydata+3.3
- ydata = np.vstack([ydata1, ydata2])
- ydata = np.tile(ydata, (20, 1))
- ydatab = ydata.T.flatten()
- ydata = ydata.flatten()
- ycontrol = np.zeros_like(ydata)
- spec_g, fsp_g = mlab.psd(x=ydata,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- detrend='linear')
- spec_b, fsp_b = mlab.psd(x=ydatab,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- detrend='linear')
- spec_c, fsp_c = mlab.psd(x=ycontrol,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides)
- assert_array_equal(fsp_g, fsp_c)
- assert_array_equal(fsp_b, fsp_c)
- assert_allclose(spec_g, spec_c, atol=1e-08)
- # these should not be almost equal
- with pytest.raises(AssertionError):
- assert_allclose(spec_b, spec_c, atol=1e-08)
- def test_psd_window_hanning(self):
- if self.NFFT_density is None:
- return
- ydata = np.arange(self.NFFT_density)
- ydata1 = ydata+5
- ydata2 = ydata+3.3
- ycontrol1, windowVals = _apply_window(ydata1,
- mlab.window_hanning,
- return_window=True)
- ycontrol2 = mlab.window_hanning(ydata2)
- ydata = np.vstack([ydata1, ydata2])
- ycontrol = np.vstack([ycontrol1, ycontrol2])
- ydata = np.tile(ydata, (20, 1))
- ycontrol = np.tile(ycontrol, (20, 1))
- ydatab = ydata.T.flatten()
- ydataf = ydata.flatten()
- ycontrol = ycontrol.flatten()
- spec_g, fsp_g = mlab.psd(x=ydataf,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- window=mlab.window_hanning)
- spec_b, fsp_b = mlab.psd(x=ydatab,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- window=mlab.window_hanning)
- spec_c, fsp_c = mlab.psd(x=ycontrol,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- window=mlab.window_none)
- spec_c *= len(ycontrol1)/(np.abs(windowVals)**2).sum()
- assert_array_equal(fsp_g, fsp_c)
- assert_array_equal(fsp_b, fsp_c)
- assert_allclose(spec_g, spec_c, atol=1e-08)
- # these should not be almost equal
- with pytest.raises(AssertionError):
- assert_allclose(spec_b, spec_c, atol=1e-08)
- def test_psd_window_hanning_detrend_linear(self):
- if self.NFFT_density is None:
- return
- ydata = np.arange(self.NFFT_density)
- ycontrol = np.zeros(self.NFFT_density)
- ydata1 = ydata+5
- ydata2 = ydata+3.3
- ycontrol1 = ycontrol
- ycontrol2 = ycontrol
- ycontrol1, windowVals = _apply_window(ycontrol1,
- mlab.window_hanning,
- return_window=True)
- ycontrol2 = mlab.window_hanning(ycontrol2)
- ydata = np.vstack([ydata1, ydata2])
- ycontrol = np.vstack([ycontrol1, ycontrol2])
- ydata = np.tile(ydata, (20, 1))
- ycontrol = np.tile(ycontrol, (20, 1))
- ydatab = ydata.T.flatten()
- ydataf = ydata.flatten()
- ycontrol = ycontrol.flatten()
- spec_g, fsp_g = mlab.psd(x=ydataf,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- detrend=mlab.detrend_linear,
- window=mlab.window_hanning)
- spec_b, fsp_b = mlab.psd(x=ydatab,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- detrend=mlab.detrend_linear,
- window=mlab.window_hanning)
- spec_c, fsp_c = mlab.psd(x=ycontrol,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=0,
- sides=self.sides,
- window=mlab.window_none)
- spec_c *= len(ycontrol1)/(np.abs(windowVals)**2).sum()
- assert_array_equal(fsp_g, fsp_c)
- assert_array_equal(fsp_b, fsp_c)
- assert_allclose(spec_g, spec_c, atol=1e-08)
- # these should not be almost equal
- with pytest.raises(AssertionError):
- assert_allclose(spec_b, spec_c, atol=1e-08)
- def test_psd_windowarray(self):
- freqs = self.freqs_density
- spec, fsp = mlab.psd(x=self.y,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=self.nover_density,
- pad_to=self.pad_to_density,
- sides=self.sides,
- window=np.ones(self.NFFT_density_real))
- assert_allclose(fsp, freqs, atol=1e-06)
- assert spec.shape == freqs.shape
- def test_psd_windowarray_scale_by_freq(self):
- win = mlab.window_hanning(np.ones(self.NFFT_density_real))
- spec, fsp = mlab.psd(x=self.y,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=self.nover_density,
- pad_to=self.pad_to_density,
- sides=self.sides,
- window=mlab.window_hanning)
- spec_s, fsp_s = mlab.psd(x=self.y,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=self.nover_density,
- pad_to=self.pad_to_density,
- sides=self.sides,
- window=mlab.window_hanning,
- scale_by_freq=True)
- spec_n, fsp_n = mlab.psd(x=self.y,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=self.nover_density,
- pad_to=self.pad_to_density,
- sides=self.sides,
- window=mlab.window_hanning,
- scale_by_freq=False)
- assert_array_equal(fsp, fsp_s)
- assert_array_equal(fsp, fsp_n)
- assert_array_equal(spec, spec_s)
- assert_allclose(spec_s*(win**2).sum(),
- spec_n/self.Fs*win.sum()**2,
- atol=1e-08)
- def test_complex_spectrum(self):
- freqs = self.freqs_spectrum
- spec, fsp = mlab.complex_spectrum(x=self.y,
- Fs=self.Fs,
- sides=self.sides,
- pad_to=self.pad_to_spectrum)
- assert_allclose(fsp, freqs, atol=1e-06)
- assert spec.shape == freqs.shape
- def test_magnitude_spectrum(self):
- freqs = self.freqs_spectrum
- spec, fsp = mlab.magnitude_spectrum(x=self.y,
- Fs=self.Fs,
- sides=self.sides,
- pad_to=self.pad_to_spectrum)
- assert spec.shape == freqs.shape
- self.check_maxfreq(spec, fsp, self.fstims)
- self.check_freqs(spec, freqs, fsp, self.fstims)
- def test_angle_spectrum(self):
- freqs = self.freqs_spectrum
- spec, fsp = mlab.angle_spectrum(x=self.y,
- Fs=self.Fs,
- sides=self.sides,
- pad_to=self.pad_to_spectrum)
- assert_allclose(fsp, freqs, atol=1e-06)
- assert spec.shape == freqs.shape
- def test_phase_spectrum(self):
- freqs = self.freqs_spectrum
- spec, fsp = mlab.phase_spectrum(x=self.y,
- Fs=self.Fs,
- sides=self.sides,
- pad_to=self.pad_to_spectrum)
- assert_allclose(fsp, freqs, atol=1e-06)
- assert spec.shape == freqs.shape
- def test_specgram_auto(self):
- freqs = self.freqs_specgram
- spec, fsp, t = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides)
- specm = np.mean(spec, axis=1)
- assert_allclose(fsp, freqs, atol=1e-06)
- assert_allclose(t, self.t_specgram, atol=1e-06)
- assert spec.shape[0] == freqs.shape[0]
- assert spec.shape[1] == self.t_specgram.shape[0]
- # since we are using a single freq, all time slices
- # should be about the same
- if np.abs(spec.max()) != 0:
- assert_allclose(np.diff(spec, axis=1).max()/np.abs(spec.max()), 0,
- atol=1e-02)
- self.check_freqs(specm, freqs, fsp, self.fstims)
- def test_specgram_default(self):
- freqs = self.freqs_specgram
- spec, fsp, t = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='default')
- specm = np.mean(spec, axis=1)
- assert_allclose(fsp, freqs, atol=1e-06)
- assert_allclose(t, self.t_specgram, atol=1e-06)
- assert spec.shape[0] == freqs.shape[0]
- assert spec.shape[1] == self.t_specgram.shape[0]
- # since we are using a single freq, all time slices
- # should be about the same
- if np.abs(spec.max()) != 0:
- assert_allclose(np.diff(spec, axis=1).max()/np.abs(spec.max()), 0,
- atol=1e-02)
- self.check_freqs(specm, freqs, fsp, self.fstims)
- def test_specgram_psd(self):
- freqs = self.freqs_specgram
- spec, fsp, t = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='psd')
- specm = np.mean(spec, axis=1)
- assert_allclose(fsp, freqs, atol=1e-06)
- assert_allclose(t, self.t_specgram, atol=1e-06)
- assert spec.shape[0] == freqs.shape[0]
- assert spec.shape[1] == self.t_specgram.shape[0]
- # since we are using a single freq, all time slices
- # should be about the same
- if np.abs(spec.max()) != 0:
- assert_allclose(np.diff(spec, axis=1).max()/np.abs(spec.max()), 0,
- atol=1e-02)
- self.check_freqs(specm, freqs, fsp, self.fstims)
- def test_specgram_complex(self):
- freqs = self.freqs_specgram
- spec, fsp, t = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='complex')
- specm = np.mean(np.abs(spec), axis=1)
- assert_allclose(fsp, freqs, atol=1e-06)
- assert_allclose(t, self.t_specgram, atol=1e-06)
- assert spec.shape[0] == freqs.shape[0]
- assert spec.shape[1] == self.t_specgram.shape[0]
- self.check_freqs(specm, freqs, fsp, self.fstims)
- def test_specgram_magnitude(self):
- freqs = self.freqs_specgram
- spec, fsp, t = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='magnitude')
- specm = np.mean(spec, axis=1)
- assert_allclose(fsp, freqs, atol=1e-06)
- assert_allclose(t, self.t_specgram, atol=1e-06)
- assert spec.shape[0] == freqs.shape[0]
- assert spec.shape[1] == self.t_specgram.shape[0]
- # since we are using a single freq, all time slices
- # should be about the same
- if np.abs(spec.max()) != 0:
- assert_allclose(np.diff(spec, axis=1).max()/np.abs(spec.max()), 0,
- atol=1e-02)
- self.check_freqs(specm, freqs, fsp, self.fstims)
- def test_specgram_angle(self):
- freqs = self.freqs_specgram
- spec, fsp, t = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='angle')
- assert_allclose(fsp, freqs, atol=1e-06)
- assert_allclose(t, self.t_specgram, atol=1e-06)
- assert spec.shape[0] == freqs.shape[0]
- assert spec.shape[1] == self.t_specgram.shape[0]
- def test_specgram_phase(self):
- freqs = self.freqs_specgram
- spec, fsp, t = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='phase')
- assert_allclose(fsp, freqs, atol=1e-06)
- assert_allclose(t, self.t_specgram, atol=1e-06)
- assert spec.shape[0] == freqs.shape[0]
- assert spec.shape[1] == self.t_specgram.shape[0]
- def test_specgram_warn_only1seg(self):
- """Warning should be raised if len(x) <= NFFT."""
- with pytest.warns(UserWarning, match="Only one segment is calculated"):
- mlab.specgram(x=self.y, NFFT=len(self.y), Fs=self.Fs)
- def test_psd_csd_equal(self):
- Pxx, freqsxx = mlab.psd(x=self.y,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=self.nover_density,
- pad_to=self.pad_to_density,
- sides=self.sides)
- Pxy, freqsxy = mlab.csd(x=self.y, y=self.y,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=self.nover_density,
- pad_to=self.pad_to_density,
- sides=self.sides)
- assert_array_almost_equal_nulp(Pxx, Pxy)
- assert_array_equal(freqsxx, freqsxy)
- def test_specgram_auto_default_equal(self):
- '''test that mlab.specgram without mode and with mode 'default' and
- 'psd' are all the same'''
- speca, freqspeca, ta = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides)
- specb, freqspecb, tb = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='default')
- assert_array_equal(speca, specb)
- assert_array_equal(freqspeca, freqspecb)
- assert_array_equal(ta, tb)
- def test_specgram_auto_psd_equal(self):
- '''test that mlab.specgram without mode and with mode 'default' and
- 'psd' are all the same'''
- speca, freqspeca, ta = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides)
- specc, freqspecc, tc = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='psd')
- assert_array_equal(speca, specc)
- assert_array_equal(freqspeca, freqspecc)
- assert_array_equal(ta, tc)
- def test_specgram_complex_mag_equivalent(self):
- specc, freqspecc, tc = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='complex')
- specm, freqspecm, tm = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='magnitude')
- assert_array_equal(freqspecc, freqspecm)
- assert_array_equal(tc, tm)
- assert_allclose(np.abs(specc), specm, atol=1e-06)
- def test_specgram_complex_angle_equivalent(self):
- specc, freqspecc, tc = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='complex')
- speca, freqspeca, ta = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='angle')
- assert_array_equal(freqspecc, freqspeca)
- assert_array_equal(tc, ta)
- assert_allclose(np.angle(specc), speca, atol=1e-06)
- def test_specgram_complex_phase_equivalent(self):
- specc, freqspecc, tc = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='complex')
- specp, freqspecp, tp = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='phase')
- assert_array_equal(freqspecc, freqspecp)
- assert_array_equal(tc, tp)
- assert_allclose(np.unwrap(np.angle(specc), axis=0), specp,
- atol=1e-06)
- def test_specgram_angle_phase_equivalent(self):
- speca, freqspeca, ta = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='angle')
- specp, freqspecp, tp = mlab.specgram(x=self.y,
- NFFT=self.NFFT_specgram,
- Fs=self.Fs,
- noverlap=self.nover_specgram,
- pad_to=self.pad_to_specgram,
- sides=self.sides,
- mode='phase')
- assert_array_equal(freqspeca, freqspecp)
- assert_array_equal(ta, tp)
- assert_allclose(np.unwrap(speca, axis=0), specp,
- atol=1e-06)
- def test_psd_windowarray_equal(self):
- win = mlab.window_hanning(np.ones(self.NFFT_density_real))
- speca, fspa = mlab.psd(x=self.y,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=self.nover_density,
- pad_to=self.pad_to_density,
- sides=self.sides,
- window=win)
- specb, fspb = mlab.psd(x=self.y,
- NFFT=self.NFFT_density,
- Fs=self.Fs,
- noverlap=self.nover_density,
- pad_to=self.pad_to_density,
- sides=self.sides)
- assert_array_equal(fspa, fspb)
- assert_allclose(speca, specb, atol=1e-08)
- # extra test for cohere...
- def test_cohere():
- N = 1024
- np.random.seed(19680801)
- x = np.random.randn(N)
- # phase offset
- y = np.roll(x, 20)
- # high-freq roll-off
- y = np.convolve(y, np.ones(20) / 20., mode='same')
- cohsq, f = mlab.cohere(x, y, NFFT=256, Fs=2, noverlap=128)
- assert_allclose(np.mean(cohsq), 0.837, atol=1.e-3)
- assert np.isreal(np.mean(cohsq))
- #*****************************************************************
- # These Tests where taken from SCIPY with some minor modifications
- # this can be retrieved from:
- # https://github.com/scipy/scipy/blob/master/scipy/stats/tests/test_kdeoth.py
- #*****************************************************************
- class TestGaussianKDE:
- def test_kde_integer_input(self):
- """Regression test for #1181."""
- x1 = np.arange(5)
- kde = mlab.GaussianKDE(x1)
- y_expected = [0.13480721, 0.18222869, 0.19514935, 0.18222869,
- 0.13480721]
- np.testing.assert_array_almost_equal(kde(x1), y_expected, decimal=6)
- def test_gaussian_kde_covariance_caching(self):
- x1 = np.array([-7, -5, 1, 4, 5], dtype=float)
- xs = np.linspace(-10, 10, num=5)
- # These expected values are from scipy 0.10, before some changes to
- # gaussian_kde. They were not compared with any external reference.
- y_expected = [0.02463386, 0.04689208, 0.05395444, 0.05337754,
- 0.01664475]
- # set it to the default bandwidth.
- kde2 = mlab.GaussianKDE(x1, 'scott')
- y2 = kde2(xs)
- np.testing.assert_array_almost_equal(y_expected, y2, decimal=7)
- def test_kde_bandwidth_method(self):
- np.random.seed(8765678)
- n_basesample = 50
- xn = np.random.randn(n_basesample)
- # Default
- gkde = mlab.GaussianKDE(xn)
- # Supply a callable
- gkde2 = mlab.GaussianKDE(xn, 'scott')
- # Supply a scalar
- gkde3 = mlab.GaussianKDE(xn, bw_method=gkde.factor)
- xs = np.linspace(-7, 7, 51)
- kdepdf = gkde.evaluate(xs)
- kdepdf2 = gkde2.evaluate(xs)
- assert kdepdf.all() == kdepdf2.all()
- kdepdf3 = gkde3.evaluate(xs)
- assert kdepdf.all() == kdepdf3.all()
- class TestGaussianKDECustom:
- def test_no_data(self):
- """Pass no data into the GaussianKDE class."""
- with pytest.raises(ValueError):
- mlab.GaussianKDE([])
- def test_single_dataset_element(self):
- """Pass a single dataset element into the GaussianKDE class."""
- with pytest.raises(ValueError):
- mlab.GaussianKDE([42])
- def test_silverman_multidim_dataset(self):
- """Use a multi-dimensional array as the dataset and test silverman's
- output"""
- x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
- with pytest.raises(np.linalg.LinAlgError):
- mlab.GaussianKDE(x1, "silverman")
- def test_silverman_singledim_dataset(self):
- """Use a single dimension list as the dataset and test silverman's
- output."""
- x1 = np.array([-7, -5, 1, 4, 5])
- mygauss = mlab.GaussianKDE(x1, "silverman")
- y_expected = 0.76770389927475502
- assert_almost_equal(mygauss.covariance_factor(), y_expected, 7)
- def test_scott_multidim_dataset(self):
- """Use a multi-dimensional array as the dataset and test scott's output
- """
- x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
- with pytest.raises(np.linalg.LinAlgError):
- mlab.GaussianKDE(x1, "scott")
- def test_scott_singledim_dataset(self):
- """Use a single-dimensional array as the dataset and test scott's
- output"""
- x1 = np.array([-7, -5, 1, 4, 5])
- mygauss = mlab.GaussianKDE(x1, "scott")
- y_expected = 0.72477966367769553
- assert_almost_equal(mygauss.covariance_factor(), y_expected, 7)
- def test_scalar_empty_dataset(self):
- """Use an empty array as the dataset and test the scalar's cov factor
- """
- with pytest.raises(ValueError):
- mlab.GaussianKDE([], bw_method=5)
- def test_scalar_covariance_dataset(self):
- """Use a dataset and test a scalar's cov factor
- """
- np.random.seed(8765678)
- n_basesample = 50
- multidim_data = [np.random.randn(n_basesample) for i in range(5)]
- kde = mlab.GaussianKDE(multidim_data, bw_method=0.5)
- assert kde.covariance_factor() == 0.5
- def test_callable_covariance_dataset(self):
- """Use a multi-dimensional array as the dataset and test the callable's
- cov factor"""
- np.random.seed(8765678)
- n_basesample = 50
- multidim_data = [np.random.randn(n_basesample) for i in range(5)]
- def callable_fun(x):
- return 0.55
- kde = mlab.GaussianKDE(multidim_data, bw_method=callable_fun)
- assert kde.covariance_factor() == 0.55
- def test_callable_singledim_dataset(self):
- """Use a single-dimensional array as the dataset and test the
- callable's cov factor"""
- np.random.seed(8765678)
- n_basesample = 50
- multidim_data = np.random.randn(n_basesample)
- kde = mlab.GaussianKDE(multidim_data, bw_method='silverman')
- y_expected = 0.48438841363348911
- assert_almost_equal(kde.covariance_factor(), y_expected, 7)
- def test_wrong_bw_method(self):
- """Test the error message that should be called when bw is invalid."""
- np.random.seed(8765678)
- n_basesample = 50
- data = np.random.randn(n_basesample)
- with pytest.raises(ValueError):
- mlab.GaussianKDE(data, bw_method="invalid")
- class TestGaussianKDEEvaluate:
- def test_evaluate_diff_dim(self):
- """
- Test the evaluate method when the dim's of dataset and points have
- different dimensions.
- """
- x1 = np.arange(3, 10, 2)
- kde = mlab.GaussianKDE(x1)
- x2 = np.arange(3, 12, 2)
- y_expected = [
- 0.08797252, 0.11774109, 0.11774109, 0.08797252, 0.0370153
- ]
- y = kde.evaluate(x2)
- np.testing.assert_array_almost_equal(y, y_expected, 7)
- def test_evaluate_inv_dim(self):
- """
- Invert the dimensions; i.e., for a dataset of dimension 1 [3, 2, 4],
- the points should have a dimension of 3 [[3], [2], [4]].
- """
- np.random.seed(8765678)
- n_basesample = 50
- multidim_data = np.random.randn(n_basesample)
- kde = mlab.GaussianKDE(multidim_data)
- x2 = [[1], [2], [3]]
- with pytest.raises(ValueError):
- kde.evaluate(x2)
- def test_evaluate_dim_and_num(self):
- """Tests if evaluated against a one by one array"""
- x1 = np.arange(3, 10, 2)
- x2 = np.array([3])
- kde = mlab.GaussianKDE(x1)
- y_expected = [0.08797252]
- y = kde.evaluate(x2)
- np.testing.assert_array_almost_equal(y, y_expected, 7)
- def test_evaluate_point_dim_not_one(self):
- x1 = np.arange(3, 10, 2)
- x2 = [np.arange(3, 10, 2), np.arange(3, 10, 2)]
- kde = mlab.GaussianKDE(x1)
- with pytest.raises(ValueError):
- kde.evaluate(x2)
- def test_evaluate_equal_dim_and_num_lt(self):
- x1 = np.arange(3, 10, 2)
- x2 = np.arange(3, 8, 2)
- kde = mlab.GaussianKDE(x1)
- y_expected = [0.08797252, 0.11774109, 0.11774109]
- y = kde.evaluate(x2)
- np.testing.assert_array_almost_equal(y, y_expected, 7)
- def test_psd_onesided_norm():
- u = np.array([0, 1, 2, 3, 1, 2, 1])
- dt = 1.0
- Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size)
- P, f = mlab.psd(u, NFFT=u.size, Fs=1/dt, window=mlab.window_none,
- detrend=mlab.detrend_none, noverlap=0, pad_to=None,
- scale_by_freq=None,
- sides='onesided')
- Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1])
- assert_allclose(P, Su_1side, atol=1e-06)
- def test_psd_oversampling():
- """Test the case len(x) < NFFT for psd()."""
- u = np.array([0, 1, 2, 3, 1, 2, 1])
- dt = 1.0
- Su = np.abs(np.fft.fft(u) * dt)**2 / (dt * u.size)
- P, f = mlab.psd(u, NFFT=u.size*2, Fs=1/dt, window=mlab.window_none,
- detrend=mlab.detrend_none, noverlap=0, pad_to=None,
- scale_by_freq=None,
- sides='onesided')
- Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1])
- assert_almost_equal(np.sum(P), np.sum(Su_1side)) # same energy
|