def test_fisher_matrix(self):
"""
"""
new = self.bayes.update(simulations={'simple1': [self.sim1, self.exp1],
'simple2': [self.sim1, self.exp1]},
models={'simp':
self.model.update_dof([1, 0.5])})
initial_data = new.get_data()
sens_matrix = new._get_sens(initial_data=initial_data)
sigma = inv(new.simulations['simple1']['exp'].get_sigma())
fisher_1 = np.dot(np.dot(sens_matrix['simple1'].T,
sigma),
sens_matrix['simple1'])
fisher_2 = np.dot(np.dot(sens_matrix['simple2'].T,
sigma),
sens_matrix['simple2'])
npt.assert_array_almost_equal(self.exp1.get_fisher_matrix(
sens_matrix=sens_matrix['simple1']),
fisher_1)
npt.assert_array_almost_equal(self.exp1.get_fisher_matrix(
sens_matrix=sens_matrix['simple2']),
fisher_2)
python类assert_array_almost_equal()的实例源码
def test_sigma(self):
"""Tests that the correct covariance matrix is generated
"""
exp = SimpleExperiment(exp_var=0.01)
true_sigma = np.diag((exp.data[1] * 0.01)**2)
npt.assert_array_almost_equal(true_sigma, exp.get_sigma())
def test_compare(self):
"""Tests that the experiment can be compared to aligned simulation data
"""
exp = SimpleExperiment()
# Generate some simulation data
sim_data = self.simSimp(self.models)
stored_data = copy.deepcopy(sim_data)
sim_data = exp.align(sim_data)
epsilon = exp.compare(sim_data)
npt.assert_array_almost_equal((4**2 - 2**2) * (exp.data[0]-1)**2
+ (2-1) * (exp.data[0]-1), epsilon)
def test_get_sens(self):
"""
"""
sens = self.simSimp.get_sens(self.models, ['simp1', 'simp2'])
indep = np.arange(10)
resp_mat = np.array([(1.02 * 2 * indep)**2 + 1 * indep -
(2 * indep)**2 - indep,
(2 * indep)**2 + 1.02 * indep -
(2 * indep)**2 - 1 * indep])
inp_mat = np.array([[0.02 * 2, 0], [0, 0.02]])
true_sens1 = np.linalg.lstsq(inp_mat, resp_mat)[0].T
indep = np.arange(10)
resp_mat = np.array([(1.02 * 3 * indep)**2 + 3 * indep -
(3 * indep)**2 - 3 * indep,
(3 * indep)**2 + 1.02 * 3 * indep -
(3 * indep)**2 - 3 * indep])
inp_mat = np.array([[0.02 * 3, 0], [0, 0.02 * 3]])
true_sens2 = np.linalg.lstsq(inp_mat, resp_mat)[0].T
# print(sens)
# print(true_sens1 - sens[:,:2])
# print(true_sens2 - sens[:,2:])
npt.assert_array_almost_equal(sens[:,:2], true_sens1)
npt.assert_array_almost_equal(sens[:,2:], true_sens2)
def test_sens_pll(models, sim):
results = sim.get_sens_mpi(models, ['simp',])
#print(results)
resp_mat = np.zeros((10,10), dtype=np.float64)
inp_mat = np.zeros((10,10), dtype=np.float64)
for i in range(models['simp'].shape()):
dof_new = np.arange(10, dtype=np.float64) + 1
delta = np.zeros((10,))
delta[i] = 0.02 * dof_new[i]
dof_new += delta
#print(dof_new)
resp_mat[:, i] = np.arange(10) * dof_new\
- np.arange(10) * (np.arange(10) + 1)
inp_mat[:, i] = delta
sens_matrix = np.linalg.lstsq(inp_mat, resp_mat.T)[0].T
# print(resp_mat)
# print(inp_mat)
# print(sens_matrix)
for i in range(models['simp'].shape()):
npt.assert_array_almost_equal(
results[i , :],
sens_matrix[i, :],
err_msg='Error in {:d} dof sens'.format(i)
)
def test_sens(models, sim):
results = sim.get_sens(models, ['simp',])
#print(results)
resp_mat = np.zeros((10,10), dtype=np.float64)
inp_mat = np.zeros((10,10), dtype=np.float64)
for i in range(models['simp'].shape()):
dof_new = np.arange(10, dtype=np.float64) + 1
delta = np.zeros((10,))
delta[i] = 0.02 * dof_new[i]
dof_new += delta
#print(dof_new)
resp_mat[:, i] = np.arange(10) * dof_new\
- np.arange(10) * (np.arange(10) + 1)
inp_mat[:, i] = delta
sens_matrix = np.linalg.lstsq(inp_mat, resp_mat.T)[0].T
# print(resp_mat)
# print(inp_mat)
# print(sens_matrix)
for i in range(models['simp'].shape()):
npt.assert_array_almost_equal(
results[i , :],
sens_matrix[i, :],
err_msg='Error in {:d} dof sens'.format(i)
)
def test_get_measurements_std():
dt_means, dt_stds, dlna_means, dlna_stds = \
fw.get_measurements_std({})
assert len(dt_means) == 0
assert len(dt_stds) == 0
assert len(dlna_means) == 0
assert len(dlna_stds) == 0
dt_means, dt_stds, dlna_means, dlna_stds = \
fw.get_measurements_std(measures)
# from tests/data/window/measurements.fake.json
_true_dt_mean = \
{"R": np.mean([1, -1, 1, 1, -2]),
"T": np.mean([1, 1.5, -2.5]),
"Z": np.mean([1, 2, -1.5, 2, -5, -0.2, 0.8, -1.6, 1.6, 0.9])}
_true_dt_stds = \
{"R": np.std([1, -1, 1, 1, -2]),
"T": np.std([1, 1.5, -2.5]),
"Z": np.std([1, 2, -1.5, 2, -5, -0.2, 0.8, -1.6, 1.6, 0.9])}
_true_dlna_mean = \
{"R": np.mean([0.7, -0.7, 0.6, 1.0, -0.8]),
"T": np.mean([0.9, 0.3, -0.7]),
"Z": np.mean([0.6, 0.4, -0.5, 1.2, -1.5, -0.2, 0.8, -0.6, 1.1, 0.9])}
_true_dlna_stds = \
{"R": np.std([0.7, -0.7, 0.6, 1.0, -0.8]),
"T": np.std([0.9, 0.3, -0.7]),
"Z": np.std([0.6, 0.4, -0.5, 1.2, -1.5, -0.2, 0.8, -0.6, 1.1, 0.9])}
for comp in dt_means:
npt.assert_array_almost_equal(dt_means[comp], _true_dt_mean[comp])
npt.assert_array_almost_equal(dt_stds[comp], _true_dt_stds[comp])
npt.assert_array_almost_equal(dlna_means[comp], _true_dlna_mean[comp])
npt.assert_array_almost_equal(dlna_stds[comp], _true_dlna_stds[comp])
def test_get_user_bound():
info = {"tshift_acceptance_level": 3, "tshift_reference": 0,
"dlna_acceptance_level": 0.8, "dlna_reference": 0.0}
v = fw.get_user_bound(info)
npt.assert_array_almost_equal(v, [-3, 3, -0.8, 0.8])
info = {"tshift_acceptance_level": 10, "tshift_reference": -1,
"dlna_acceptance_level": 0.6, "dlna_reference": 0.2}
v = fw.get_user_bound(info)
npt.assert_array_almost_equal(v, [-11, 9, -0.4, 0.8])
def adjoint_equal(adj1, adj2):
assert adj1.adj_src_type == adj2.adj_src_type
npt.assert_almost_equal(adj1.misfit, adj2.misfit)
npt.assert_almost_equal(adj1.dt, adj2.dt)
npt.assert_almost_equal(adj1.min_period, adj2.min_period)
npt.assert_almost_equal(adj1.max_period, adj2.max_period)
assert adj1.id == adj2.id
assert adj1.measurement == adj2.measurement
npt.assert_array_almost_equal(
adj1.adjoint_source, adj2.adjoint_source)
assert adj1.starttime == adj2.starttime
def test_constructors(self):
atom1 = mastmol.Atom(coords=self.coords, atom_type=self.MockAtomType)
atom2 = self.MockAtomType.to_atom(self.coords)
npt.assert_array_almost_equal(atom1.coords, atom2.coords)
self.assertEqual(atom1.atom_type, atom2.atom_type)
def test_constructors(self):
bonds = []
bonds.append(mastmol.Bond(atom_container=self.atoms, bond_type=self.MockBondType))
bonds.append(mastmol.Bond(atom_container=self.atoms, atom_ids=(0,1),
bond_type=self.MockBondType))
bonds.append(self.MockBondType.to_bond(*self.coords))
for bond_a, bond_b in itertools.combinations(bonds, 2):
npt.assert_array_almost_equal(bond_a.coords, bond_b.coords)
self.assertEqual(bond_a.bond_type, bond_b.bond_type)
def test_constructors(self):
molecules = []
molecules.append(mastmol.Molecule(atoms=self.atoms, bonds=self.bonds,
mol_type=self.MockMoleculeType))
molecules.append(self.MockMoleculeType.to_molecule(self.coords))
for mol_a, mol_b in itertools.combinations(molecules, 2):
npt.assert_array_almost_equal(mol_a.atom_coords, mol_b.atom_coords)
for bond_a, bond_b in zip(mol_a.bonds, mol_b.bonds):
self.assertIs(bond_a.bond_type, bond_b.bond_type)
for atom_a, atom_b in zip(mol_a.atoms, mol_b.atoms):
self.assertIs(atom_a.atom_type, atom_b.atom_type)
def test_cal_price_cosine(self):
cosine_pricer = FourierPricer(self.vanilla_option)
strike_arr = np.array([5, 10, 30, 36, 50, 60, 100])
put_call_arr = np.array(['call', 'call', 'put', 'call', 'call', 'put', 'call'])
exp = np.array([3.09958567e+01, 2.60163625e+01, 8.25753140e-05, 8.12953226e-01,
8.97449491e-11, 2.37785797e+01, 2.19293560e-85, ]
)
volatility = 0.20
N = 150
cosine_pricer.set_log_st_process(BlackScholes(volatility))
cosine_pricer.set_pricing_engine(CosineEngine(N, L=30))
res = cosine_pricer.calc_price(strike_arr, put_call_arr, put_label='put')
npt.assert_array_almost_equal(res, exp, 6)
def test_JSON(self):
testMage = np.random.uniform( high=10, size=[3,128,64] ).astype( 'int8' )
meta = {'foo': 5, 'bar': 42}
mrcName = os.path.join( tmpDir, "testMage.mrcz" )
pixelsize = [1.2, 5.6, 3.4]
mrcz.writeMRC( testMage, mrcName, meta=meta,
pixelsize=pixelsize, pixelunits=u"\AA",
voltage=300.0, C3=2.7, gain=1.05,
compressor='zstd', clevel=1, n_threads=4 )
rereadMage, rereadHeader = mrcz.readMRC( mrcName, pixelunits=u"\AA" )
try: os.remove( mrcName )
except IOError: log.info( "Warning: file {} left on disk".format(mrcName) )
assert( np.all(testMage.shape == rereadMage.shape) )
assert( testMage.dtype == rereadMage.dtype )
for key in meta:
assert( meta[key] == rereadHeader[key] )
npt.assert_array_almost_equal( testMage, rereadMage )
npt.assert_array_equal( rereadHeader['voltage'], 300.0 )
npt.assert_array_almost_equal( rereadHeader['pixelsize'], pixelsize )
npt.assert_array_equal( rereadHeader['pixelunits'], u"\AA" )
npt.assert_array_equal( rereadHeader['C3'], 2.7 )
npt.assert_array_equal( rereadHeader['gain'], 1.05 )
pass
def test_Async(self):
testMage = np.random.uniform( high=10, size=[3,128,64] ).astype( 'int8' )
meta = {'foo': 5, 'bar': 42}
mrcName = os.path.join( tmpDir, "testMage.mrcz" )
pixelsize = [1.2, 5.6, 3.4]
worker = mrcz.asyncWriteMRC( testMage, mrcName, meta=meta,
pixelsize=pixelsize, pixelunits=u"\AA",
voltage=300.0, C3=2.7, gain=1.05,
compressor='zstd', clevel=1, n_threads=4 )
worker.result() # Wait for write to finish
worker = mrcz.asyncReadMRC( mrcName, pixelunits=u"\AA" )
rereadMage, rereadHeader = worker.result()
try: os.remove( mrcName )
except IOError: log.info( "Warning: file {} left on disk".format(mrcName) )
assert( np.all(testMage.shape == rereadMage.shape) )
assert( testMage.dtype == rereadMage.dtype )
for key in meta:
assert( meta[key] == rereadHeader[key] )
npt.assert_array_almost_equal( testMage, rereadMage )
npt.assert_array_equal( rereadHeader['voltage'], 300.0 )
npt.assert_array_almost_equal( rereadHeader['pixelsize'], pixelsize )
npt.assert_array_equal( rereadHeader['pixelunits'], u"\AA" )
npt.assert_array_equal( rereadHeader['C3'], 2.7 )
npt.assert_array_equal( rereadHeader['gain'], 1.05 )
pass
def test_AsList(self):
testFrame = np.random.uniform( high=10, size=[128,64] ).astype( 'int8' )
testMage = [testFrame, testFrame]
meta = {'foo': 5, 'bar': 42}
mrcName = os.path.join( tmpDir, "testMage.mrcz" )
pixelsize = [5.6, 3.4]
mrcz.writeMRC( testMage, mrcName, meta=meta,
pixelsize=pixelsize, pixelunits=u"\AA",
voltage=300.0, C3=2.7, gain=1.05,
compressor='zstd', clevel=1, n_threads=4 )
rereadMage, rereadHeader = mrcz.readMRC( mrcName, pixelunits=u"\AA", asList=True )
# Test that we can load as an array
mageAsArray, _ = mrcz.readMRC( mrcName, pixelunits=u"\AA", asList=False )
try: os.remove( mrcName )
except IOError: log.info( "Warning: file {} left on disk".format(mrcName) )
assert( isinstance(rereadMage, list) )
assert( len(rereadMage) == len(testMage) )
for testFrame, rereadFrame in zip(testMage, rereadMage):
assert( testFrame.dtype == rereadFrame.dtype )
npt.assert_array_almost_equal(testFrame, rereadFrame)
for key in meta:
assert( meta[key] == rereadHeader[key] )
npt.assert_array_equal( rereadHeader['voltage'], 300.0 )
npt.assert_array_almost_equal( rereadHeader['pixelsize'][1:], pixelsize )
npt.assert_array_equal( rereadHeader['pixelunits'], u"\AA" )
npt.assert_array_equal( rereadHeader['C3'], 2.7 )
npt.assert_array_equal( rereadHeader['gain'], 1.05 )
pass
def crossReadWrite(self, testMage, casttype=None, compressor=None, clevel = 1 ):
mrcInput = os.path.join( tmpDir, "testIn.mrcz" )
mrcOutput = os.path.join( tmpDir, "testOut.mrcz" )
compressor = None
blocksize = 64
clevel = 1
pixelsize = [1.2, 2.6, 3.4]
mrcz.writeMRC( testMage, mrcInput,
pixelsize=pixelsize, pixelunits=u"\AA",
voltage=300.0, C3=2.7, gain=1.05,
compressor=compressor )
sub.call( cmrczProg + " -i %s -o %s -c %s -B %d -l %d"
%(mrcInput, mrcOutput, compressor, blocksize, clevel ), shell=True )
rereadMage, rereadHeader = mrcz.readMRC( mrcOutput, pixelunits=u"\AA" )
os.remove( mrcOutput )
os.remove( mrcInput )
assert( np.all(testMage.shape == rereadMage.shape) )
assert( testMage.dtype == rereadMage.dtype )
npt.assert_array_almost_equal( testMage, rereadMage )
npt.assert_array_equal( rereadHeader['voltage'], 300.0 )
npt.assert_array_almost_equal( rereadHeader['pixelsize'], pixelsize )
npt.assert_array_equal( rereadHeader['pixelunits'], u"\AA" )
npt.assert_array_equal( rereadHeader['C3'], 2.7 )
npt.assert_array_equal( rereadHeader['gain'], 1.05 )
def test():
s2 = np.sqrt(2)
check = npt.assert_array_almost_equal
# test forward kinematics
check(forward_kinematics((0,0,0)),[l2+d,0,l1])
check(forward_kinematics((0,90,0)),[l1+l2+d,0,0])
check(forward_kinematics((0,45,-45)), np.array([l1+l2,0,l1+l2])/np.sqrt(2) + [d,0,0])
check(forward_kinematics((0,0,90)),[d,0,l1-l2])
check(forward_kinematics((0,0,45)), [d+l2/np.sqrt(2),0,l1-l2/np.sqrt(2)])
check(forward_kinematics((90,90,0)),[0,l1+l2+d,0])
check(forward_kinematics((45,90,0)), np.array([l1+l2+d,l1+l2+d,0])/np.sqrt(2))
# test inverse kinematics
check(inverse_kinematics(forward_kinematics((0,0.01,0.01))),(0,0.01,0.01))
check(inverse_kinematics(forward_kinematics((0,22.5,0.01))),(0,22.5,0.01))
check(inverse_kinematics(forward_kinematics((0,45,45))),(0,45,45))
check(inverse_kinematics(forward_kinematics((0,0.01,45))),(0,0.01,45))
check(inverse_kinematics(forward_kinematics((0,0.01,22.5))),(0,0.01,22.5))
check(inverse_kinematics(forward_kinematics((90,45,22.5))),(90,45,22.5))
check(inverse_kinematics(forward_kinematics((45,45,22.5))),(45,45,22.5))
# test jacobian
check(jacobian((0,0,0)), np.matrix([[0,l1,0],[l2+d,0,0],[0,0,-l2]]))
check(jacobian((90,90,0)), np.matrix([[-l1-l2-d,0,0],[0,0,0],[0,-l1,-l2]]))
check(jacobian((0,45,45)), np.matrix([[0,l1/s2,-l2/s2],[(l1+l2)/s2+d,0,0],[0,-l1/s2,-l2/s2]]))
def _compare(self, results, expected):
ctr = expected.shape[1] // 2
npt.assert_array_almost_equal(results[0], expected[:, :ctr], 4,
'States mismatch!')
npt.assert_array_almost_equal(results[1], expected[:, ctr:], 4,
'Distances mismatch!')
def test_constructors(self):
atom1 = mastmol.Atom(coords=self.coords, atom_type=self.MockAtomType)
atom2 = self.MockAtomType.to_atom(self.coords)
npt.assert_array_almost_equal(atom1.coords, atom2.coords)
self.assertEqual(atom1.atom_type, atom2.atom_type)