本文整理汇总了Python中numpy.identity函数的典型用法代码示例。如果您正苦于以下问题:Python identity函数的具体用法?Python identity怎么用?Python identity使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了identity函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Energy_condensate_full
def Energy_condensate_full(Q, F1, x, y, H, mu, kappa, Ns) :
if Q==0 and F1 ==0 :
return 1e14
m = find_minimum(Q, F1, mu, kappa, Ns)
if m[0] < H/2 :
return 1e14
result = 0
for n1 in range(Ns) :
for n2 in range(Ns) :
M, dim = HamiltonianMatrix(n1, n2, Q, F1, 0, H, mu, kappa, Ns, 'T1')
B = np.identity(dim)
B[dim/2:dim, dim/2:dim] = -np.identity(dim/2)
eig = np.absolute(np.real(lin.eigvals(np.dot(B,M))))
result += sum(eig)/2
vec = [x[Ns * n1 + n2], np.conjugate(y[Ns * ((Ns - n1) % Ns) + (Ns - n2) % Ns])]
result += np.dot(vec, np.dot(np.conj(vec).T, M))
return result - 3 * Ns ** 2 * (np.abs(F1)**2 - np.abs(Q)**2)/2 - Ns**2 * mu*(1. + kappa) + Ns * H
示例2: test_linear_2p2s_with_dof_at_1_correlation_matrix
def test_linear_2p2s_with_dof_at_1_correlation_matrix(self):
dof_index = 0
output_index = 0
model_instance = dict(models.model_data.model_structure)
model_instance["parameters"] = numpy.array([2.0, 4.0])
model_instance["inputs"] = numpy.array([[1.0, 10], [2.0, 20], [3.0, 30]])
problem_instance = dict(models.model_data.problem_structure)
problem_instance["output_indices"] = [output_index]
problem_instance["inputs"] = model_instance["inputs"]
problem_instance["parameters"] = [model_instance["parameters"][dof_index]]
problem_instance["parameter_indices"] = [dof_index]
dof = [1.0]
# one standard deviation
offset = -1
measured = numpy.array([[1.0], [2.0], [3.0]]) + offset
problem_instance["outputs"] = measured
sens = [J_linear_2p2s([dof[0], model_instance["parameters"][1]], x) for x in model_instance["inputs"]]
# identity covariance matrix of observation errors
cov_obs_errs = numpy.identity(3)
actual = metrics.confidence_measures.compute_covariance_matrix(sens, cov_obs_errs)
expected = numpy.array([[1**2+2**2+3**2, 0], [0, 0]])
[[self.assertEqual(act, exp) for act, exp in zip(acts, exps)] for acts, exps in zip(actual, expected)]
# diagonal covariance matrix of observation errors
multiplier = 2
cov_obs_errs = numpy.identity(3) * multiplier
actual = metrics.confidence_measures.compute_covariance_matrix(sens, cov_obs_errs)
expected = numpy.array([[(1**2+2**2+3**2)/multiplier, 0], [0, 0]])
[[self.assertEqual(act, exp) for act, exp in zip(acts, exps)] for acts, exps in zip(actual, expected)]
示例3: updateParameters
def updateParameters(self, articlePicked, click, userID):
self.counter +=1
self.Wlong = vectorize(self.W)
featureDimension = len(articlePicked.featureVector)
T_X = vectorize(np.outer(articlePicked.featureVector, self.W.T[userID]))
self.A += np.outer(T_X, T_X)
self.b += click*T_X
self.AInv = np.linalg.inv(self.A)
self.UserTheta = matrixize(np.dot(self.AInv, self.b), len(articlePicked.featureVector))
Xi_Matirx = np.zeros(shape = (featureDimension, self.userNum))
Xi_Matirx.T[userID] = articlePicked.featureVector
W_X = vectorize( np.dot(np.transpose(self.UserTheta), Xi_Matirx))
self.batchGradient +=evaluateGradient(W_X, click, self.Wlong, self.lambda_, self.regu )
if self.counter%self.windowSize ==0:
self.Wlong -= 1/(float(self.counter/self.windowSize)+1)*self.batchGradient
self.W = matrixize(self.Wlong, self.userNum)
self.W = normalize(self.W, axis=0, norm='l1')
#print 'SVD', self.W
self.batchGradient = np.zeros(self.userNum*self.userNum)
# Use Ridge regression to fit W
'''
plt.pcolor(self.W_b)
plt.colorbar
plt.show()
'''
if self.W.T[userID].any() <0 or self.W.T[userID].any()>1:
print self.W.T[userID]
self.CoTheta = np.dot(self.UserTheta, self.W)
self.BigW = np.kron(np.transpose(self.W), np.identity(n=len(articlePicked.featureVector)))
self.CCA = np.dot(np.dot(self.BigW , self.AInv), np.transpose(self.BigW))
self.BigTheta = np.kron(np.identity(n=self.userNum) , self.UserTheta)
示例4: compose_matrix
def compose_matrix(scale=None, shear=None, angles=None, translate=None,perspective=None):
"""Return 4x4 transformation matrix from sequence of
transformations.
Code modified from the work of Christoph Gohlke link provided here
http://www.lfd.uci.edu/~gohlke/code/transformations.py.html
This is the inverse of the decompose_matrix function.
Parameters
-------------
scale : vector of 3 scaling factors
shear : list of shear factors for x-y, x-z, y-z axes
angles : list of Euler angles about static x, y, z axes
translate : translation vector along x, y, z axes
perspective : perspective partition of matrix
Returns
---------
matrix : 4x4 array
Examples
----------
>>> import math
>>> import numpy as np
>>> import dipy.core.geometry as gm
>>> scale = np.random.random(3) - 0.5
>>> shear = np.random.random(3) - 0.5
>>> angles = (np.random.random(3) - 0.5) * (2*math.pi)
>>> trans = np.random.random(3) - 0.5
>>> persp = np.random.random(4) - 0.5
>>> M0 = gm.compose_matrix(scale, shear, angles, trans, persp)
"""
M = np.identity(4)
if perspective is not None:
P = np.identity(4)
P[3, :] = perspective[:4]
M = np.dot(M, P)
if translate is not None:
T = np.identity(4)
T[:3, 3] = translate[:3]
M = np.dot(M, T)
if angles is not None:
R = euler_matrix(angles[0], angles[1], angles[2], 'sxyz')
M = np.dot(M, R)
if shear is not None:
Z = np.identity(4)
Z[1, 2] = shear[2]
Z[0, 2] = shear[1]
Z[0, 1] = shear[0]
M = np.dot(M, Z)
if scale is not None:
S = np.identity(4)
S[0, 0] = scale[0]
S[1, 1] = scale[1]
S[2, 2] = scale[2]
M = np.dot(M, S)
M /= M[3, 3]
return M
示例5: maximum_muscle_force
def maximum_muscle_force(OptimalLengths, Angle, AngularVelocity, R, OptimalForces):
"""
OptimalLengths must be a 1X4 Matrix with optimal muscle lengths for 4 muscles.
Angle should be the current angle. AngularVelocity should be the current
angular velocity. R is the 1X4 moment arm matrix. And OptimalForces should be
a 4X1 matrix of forces produced by each muscle when at optimal lengths and
velocities.
"""
# Force-Length Considerations
CurrentMuscleLengths = OptimalLengths.T - R.T*Angle
NormalizedMuscleLengths = np.matrix([(CurrentMuscleLengths[i,0]/OptimalLengths.T[i,0])-1 for i in range(4)])
# We subtract one from every Normalized Muscle Length to find the percentage
# above and below the optimal length.
MaximumMuscleForce_FL = np.identity(4)*[force_length_curve(NormalizedMuscleLengths[0,i]) \
+ passive_force_length_curve(NormalizedMuscleLengths[0,i],) \
for i in range(4)]
# Force-Velocity Considerations
CurrentMuscleVelocity = -R.T*AngularVelocity
NormalizedMuscleVelocity = [CurrentMuscleVelocity[i,0]/OptimalLengths.T[i,0] for i in range(4)]
MaximumMuscleForce_FV = np.identity(4)* \
[force_velocity_curve(NormalizedMuscleLengths[0,i],NormalizedMuscleVelocity[i]) \
for i in range(4)]
MaximumMuscleForce = (MaximumMuscleForce_FL+MaximumMuscleForce_FV)*[OptimalForces[0,i] for i in range(4)]
return(MaximumMuscleForce)
示例6: Hhfs
def Hhfs(L,S,I):
"""Provides the I dot J matrix (magnetic dipole interaction)"""
gS=int(2*S+1)
Sx=jx(S)
Sy=jy(S)
Sz=jz(S)
Si=identity(gS)
gL=int(2*L+1)
Lx=jx(L)
Ly=jy(L)
Lz=jz(L)
Li=identity(gL)
gJ=gL*gS
Jx=kron(Lx,Si)+kron(Li,Sx)
Jy=kron(Ly,Si)+kron(Li,Sy)
Jz=kron(Lz,Si)+kron(Li,Sz)
Ji=identity(gJ)
J2=dot(Jx,Jx)+dot(Jy,Jy)+dot(Jz,Jz)
gI=int(2*I+1)
gF=gJ*gI
Ix=jx(I)
Iy=jy(I)
Iz=jz(I)
Ii=identity(gI)
Fx=kron(Jx,Ii)+kron(Ji,Ix)
Fy=kron(Jy,Ii)+kron(Ji,Iy)
Fz=kron(Jz,Ii)+kron(Ji,Iz)
Fi=identity(gF)
F2=dot(Fx,Fx)+dot(Fy,Fy)+dot(Fz,Fz)
Hhfs=0.5*(F2-I*(I+1)*Fi-kron(J2,Ii))
return Hhfs
示例7: rotation
def rotation(ntheta):
'''Find rotation matrix from axis-angle vector.'''
theta = la.norm(ntheta)
if theta == 0:
return np.identity(3)
Q = dual(ntheta / theta)
return np.identity(3) - Q * math.sin(theta) + dot(Q, Q) * (1 - math.cos(theta))
示例8: on_key_down
def on_key_down(self, keysym):
# Control simulation
if keysym.sym == sdl.SDLK_q:
self.exit_()
if keysym.sym == sdl.SDLK_r:
self.reset()
if keysym.sym == sdl.SDLK_p:
self.runSimulation = not self.runSimulation
print '-'*40
print "Run Simulation: ", self.runSimulation
if keysym.sym == sdl.SDLK_h:
self.showHelp()
if keysym.sym == sdl.SDLK_g:
if self.worldView == 0:
self.worldView = 1
self.renderer.setProjection(self.sim.width, self.sim.height)
self.renderer.matModelView = np.identity(4,'f')
self.renderer.matView = np.identity(4,'f')
elif self.worldView == 1:
self.worldView = 0
width, height = self.userController.agent.fov
self.renderer.setProjection(width, height)
self.renderer.worldView = self.worldView
if keysym.sym == sdl.SDLK_f:
self.frameStats.show()
if keysym.sym == sdl.SDLK_i:
# use for tests
pass
# Control agent
self.userController.keyDown(keysym.sym)
示例9: transform
def transform(args, workspace_lh, workspace_rh, nsubjs):
transform_lh = np.zeros((args.nvoxel, args.nfeature, nsubjs))
transform_rh = np.zeros((args.nvoxel, args.nfeature, nsubjs))
if args.align_algo in ["ha", "srm_noneprob"]:
transform_lh = workspace_lh["R"]
transform_rh = workspace_rh["R"]
elif args.align_algo in ["srm", "pca", "ica"]:
bW_lh = workspace_lh["bW"]
bW_rh = workspace_rh["bW"]
for m in range(nsubjs):
transform_lh[:, :, m] = bW_lh[m * args.nvoxel : (m + 1) * args.nvoxel, :]
transform_rh[:, :, m] = bW_rh[m * args.nvoxel : (m + 1) * args.nvoxel, :]
elif args.align_algo in ["ha_sm_retraction"]:
bW_lh = workspace_lh["W"]
bW_rh = workspace_rh["W"]
for m in range(nsubjs):
transform_lh[:, :, m] = bW_lh[:, :, m]
transform_rh[:, :, m] = bW_rh[:, :, m]
elif args.align_algo == "noalign":
for m in range(nsubjs):
transform_lh[:, :, m] = np.identity(args.nvoxel)
transform_rh[:, :, m] = np.identity(args.nvoxel)
else:
exit("alignment algo not recognized")
return (transform_lh, transform_rh)
示例10: test_cell_triclinic
def test_cell_triclinic():
while True:
rvecs = np.random.uniform(-1, 1, (3, 3))
if abs(np.linalg.det(rvecs)) > 0.1:
break
cell = Cell(rvecs)
# Test attributes
assert cell.nvec == 3
assert (cell.rvecs == rvecs).all()
assert abs(cell.volume - abs(np.linalg.det(rvecs))) < 1e-10
assert abs(np.dot(cell.gvecs, cell.rvecs.transpose()) - np.identity(3)).max() < 1e-5
assert abs(np.dot(cell.gvecs.transpose(), cell.rvecs) - np.identity(3)).max() < 1e-5
cell2 = Cell(-cell.rvecs)
assert abs(cell2.volume - abs(np.linalg.det(rvecs))) < 1e-10
for i in xrange(3):
assert cell.get_rlength(i) == cell.rlengths[i]
assert cell.get_glength(i) == cell.glengths[i]
assert cell.get_rspacing(i) == cell.rspacings[i]
assert cell.get_gspacing(i) == cell.gspacings[i]
assert abs(cell.get_rlength(i) - 1.0/cell.get_gspacing(i)) < 1e-10
assert abs(cell.get_glength(i) - 1.0/cell.get_rspacing(i)) < 1e-10
# Test methods (1)
vec1 = np.array([10.0, 0.0, 5.0])*angstrom
cell.mic(vec1)
cell.add_rvec(vec1, np.array([1,2,3]))
# Test methods (2)
check_frac_cart(cell)
check_g_lincomb_dot_rvecs(cell)
示例11: get_bands
def get_bands(h,output_file="BANDS2D_",nindex=[-1,1],
nk=50,nsuper=1,reciprocal=False,
operator=None,k0=[0.,0.]):
""" Calculate band structure"""
if h.dimensionality!=2: raise # continue if two dimensional
hk_gen = h.get_hk_gen() # gets the function to generate h(k)
kxs = np.linspace(-nsuper,nsuper,nk)+k0[0] # generate kx
kys = np.linspace(-nsuper,nsuper,nk)+k0[1] # generate ky
kdos = [] # empty list
kxout = []
kyout = []
if reciprocal: R = h.geometry.get_k2K() # get matrix
else: R = np.matrix(np.identity(3)) # get identity
# setup a reasonable value for delta
# setup the operator
if operator is None:
operator = np.matrix(np.identity(h.intra.shape[0]))
os.system("rm -f "+output_file+"*") # delete previous files
fo = [open(output_file+"_"+str(i)+".OUT","w") for i in nindex] # files
for x in kxs:
for y in kxs:
r = np.matrix([x,y,0.]).T # real space vectors
k = np.array((R*r).T)[0] # change of basis
hk = hk_gen(k) # get hamiltonian
evals = lg.eigvalsh(hk) # eigenvalues
epos = sorted(evals[evals>0]) # positive energies
eneg = -np.array(sorted(np.abs(evals[evals<0]))) # negative energies
for (i,j) in zip(nindex,range(len(nindex))): # loop over bands
fo[j].write(str(x)+" "+str(y)+" ")
if i>0: fo[j].write(str(epos[i-1])+"\n")
if i<0: fo[j].write(str(eneg[abs(i)-1])+"\n")
[f.close() for f in fo] # close file
示例12: test_cell_cubic
def test_cell_cubic():
rvecs = np.array([[9.865, 0.0, 0.0], [0.0, 9.865, 0.0], [0.0, 0.0, 9.865]])*angstrom
cell = Cell(rvecs)
# Test attributes
assert cell.nvec == 3
assert (cell.rvecs == rvecs).all()
assert (cell.rspacings == 9.865*angstrom).all()
assert (cell.gspacings == 1/(9.865*angstrom)).all()
assert abs(cell.volume - (9.865*angstrom)**3) < 1e-10
assert abs(np.dot(cell.gvecs, cell.rvecs.transpose()) - np.identity(3)).max() < 1e-5
assert abs(np.dot(cell.gvecs.transpose(), cell.rvecs) - np.identity(3)).max() < 1e-5
cell2 = Cell(-cell.rvecs)
assert abs(cell2.volume - (9.865*angstrom)**3) < 1e-10
for i in xrange(3):
assert cell.get_rlength(i) == cell.rlengths[i]
assert cell.get_glength(i) == cell.glengths[i]
assert cell.get_rspacing(i) == cell.rspacings[i]
assert cell.get_gspacing(i) == cell.gspacings[i]
assert abs(cell.get_rlength(i) - 1.0/cell.get_gspacing(i)) < 1e-10
assert abs(cell.get_glength(i) - 1.0/cell.get_rspacing(i)) < 1e-10
# Test methods (1)
vec1 = np.array([10.0, 0.0, 5.0])*angstrom
cell.mic(vec1)
assert abs(vec1 - np.array([0.135, 0.0, -4.865])*angstrom).max() < 1e-10
cell.add_rvec(vec1, np.array([1,2,3]))
assert abs(vec1 - np.array([10.0, 19.73, 24.73])*angstrom).max() < 1e-10
# Test methods (2)
check_frac_cart(cell)
check_g_lincomb_dot_rvecs(cell)
示例13: identity_like_generalized
def identity_like_generalized(a):
a = asarray(a)
if a.ndim == 3:
return np.array([identity(a.shape[-2]) for ax in a])
elif a.ndim > 3:
raise ValueError("Not implemented...")
return identity(a.shape[0])
示例14: ale3dStrainOutToV
def ale3dStrainOutToV(vecds):
#takes 5 components of evecd and the 6th component is lndetv
"""convert from vecds representation to symmetry matrix"""
eps = num.zeros([3,3],dtype='float64')
#Akk_by_3 = sqr3i * vecds[5] # -p
a = num.exp(vecds[5])**(1./3.)# -p
t1 = sqr2i*vecds[0]
t2 = sqr6i*vecds[1]
eps[0, 0] = t1 - t2
eps[1, 1] = -t1 - t2
eps[2, 2] = sqr2b3*vecds[1]
eps[1, 0] = vecds[2] * sqr2i
eps[2, 0] = vecds[3] * sqr2i
eps[2, 1] = vecds[4] * sqr2i
eps[0, 1] = eps[1, 0]
eps[0, 2] = eps[2, 0]
eps[1, 2] = eps[2, 1]
epstar=eps/a
V=(num.identity(3)+epstar)*a
Vinv=(num.identity(3)-epstar)/a
return V,Vinv
示例15: _get_H
def _get_H(self, debug=False):
"""
returns H_t as defined in algorithm 2
Reference:
https://en.wikipedia.org/wiki/Limited-memory_BFGS
http://www.ccms.or.kr/data/pdfpaper/jcms21_1/21_1_117.pdf
https://homes.cs.washington.edu/~galen/files/quasi-newton-notes.pdf
"""
I = np.identity(len(self.w))
if min(len(self.s), len(self.y)) == 0:
print "Warning: No second order information used!"
return I
assert len(self.s) > 0, "s cannot be empty."
assert len(self.s) == len(self.y), "s and y must have same length"
assert self.s[0].shape == self.y[0].shape, \
"s and y must have same shape"
assert abs(self.y[-1]).sum() != 0, "latest y entry cannot be 0!"
assert 1/np.inner(self.y[-1], self.s[-1]) != 0, "!"
I = np.identity(len(self.s[0]))
H = np.dot((np.inner(self.s[-1], self.y[-1]) / np.inner(self.y[-1],
self.y[-1])), I)
for (s_j, y_j) in itertools.izip(self.s, self.y):
rho = 1.0/np.inner(y_j, s_j)
V = I - np.multiply(rho, np.outer(s_j, y_j))
H = (V).dot(H).dot(V.T)
H += np.multiply(rho, np.outer(s_j, s_j))
return H