本文整理汇总了Python中numpy.empty_like方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.empty_like方法的具体用法?Python numpy.empty_like怎么用?Python numpy.empty_like使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.empty_like方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: level_thickness
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def level_thickness(p, p_top=0., p_bot=1.01325e5):
"""
Calculates the thickness, in Pa, of each pressure level.
Assumes that the pressure values given are at the center of that model
level, except for the lowest value (typically 1000 hPa), which is the
bottom boundary. The uppermost level extends to 0 hPa.
Unlike `dp_from_p`, this does not incorporate the surface pressure.
"""
p_vals = to_pascal(p.values.copy())
dp_vals = np.empty_like(p_vals)
# Bottom level extends from p[0] to halfway betwen p[0] and p[1].
dp_vals[0] = p_bot - 0.5*(p_vals[0] + p_vals[1])
# Middle levels extend from halfway between [k-1], [k] and [k], [k+1].
dp_vals[1:-1] = 0.5*(p_vals[0:-2] - p_vals[2:])
# Top level extends from halfway between top two levels to 0 hPa.
dp_vals[-1] = 0.5*(p_vals[-2] + p_vals[-1]) - p_top
dp = p.copy()
dp.values = dp_vals
return dp
示例2: _bounds_from_array
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def _bounds_from_array(arr, dim_name, bounds_name):
"""Get the bounds of an array given its center values.
E.g. if lat-lon grid center lat/lon values are known, but not the
bounds of each grid box. The algorithm assumes that the bounds
are simply halfway between each pair of center values.
"""
# TODO: don't assume needed dimension is in axis=0
# TODO: refactor to get rid of repetitive code
spacing = arr.diff(dim_name).values
lower = xr.DataArray(np.empty_like(arr), dims=arr.dims,
coords=arr.coords)
lower.values[:-1] = arr.values[:-1] - 0.5*spacing
lower.values[-1] = arr.values[-1] - 0.5*spacing[-1]
upper = xr.DataArray(np.empty_like(arr), dims=arr.dims,
coords=arr.coords)
upper.values[:-1] = arr.values[:-1] + 0.5*spacing
upper.values[-1] = arr.values[-1] + 0.5*spacing[-1]
bounds = xr.concat([lower, upper], dim='bounds')
return bounds.T
示例3: finish
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def finish(self):
""" Compute the aggregated value in each scenario based on the parent `EventRecorder` events """
events = self.event_recorder.events
# Return NaN if no events found
if len(events) == 0:
return
scen_id = np.empty(len(events), dtype=np.int)
values = np.empty_like(scen_id, dtype=np.float64)
for i, evt in enumerate(events):
scen_id[i] = evt.scenario_index.global_id
values[i] = pandas.Series(evt.values).aggregate(self.event_agg_func)
df = pandas.DataFrame({'scenario_id': scen_id, 'value': values})
# Group by scenario ...
grouped = df.groupby('scenario_id').agg(self.recorder_agg_func)
# ... and update the internal values
for index, row in grouped.iterrows():
self._values[index] = row['value']
示例4: canonicalize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def canonicalize(mf, mo_coeff_kpts, mo_occ_kpts, fock=None):
if fock is None:
dm = mf.make_rdm1(mo_coeff_kpts, mo_occ_kpts)
fock = mf.get_fock(dm=dm)
mo_coeff = []
mo_energy = []
for k, mo in enumerate(mo_coeff_kpts):
mo1 = np.empty_like(mo)
mo_e = np.empty_like(mo_occ_kpts[k])
occidx = mo_occ_kpts[k] == 2
viridx = ~occidx
for idx in (occidx, viridx):
if np.count_nonzero(idx) > 0:
orb = mo[:,idx]
f1 = reduce(np.dot, (orb.T.conj(), fock[k], orb))
e, c = scipy.linalg.eigh(f1)
mo1[:,idx] = np.dot(orb, c)
mo_e[idx] = e
mo_coeff.append(mo1)
mo_energy.append(mo_e)
return mo_energy, mo_coeff
示例5: canonicalize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def canonicalize(mf, mo_coeff, mo_occ, fock=None):
'''Canonicalization diagonalizes the Fock matrix within occupied, open,
virtual subspaces separatedly (without change occupancy).
'''
if fock is None:
dm = mf.make_rdm1(mo_coeff, mo_occ)
fock = mf.get_fock(dm=dm)
coreidx = mo_occ == 2
viridx = mo_occ == 0
openidx = ~(coreidx | viridx)
mo = numpy.empty_like(mo_coeff)
mo_e = numpy.empty(mo_occ.size)
for idx in (coreidx, openidx, viridx):
if numpy.count_nonzero(idx) > 0:
orb = mo_coeff[:,idx]
f1 = reduce(numpy.dot, (orb.conj().T, fock, orb))
e, c = scipy.linalg.eigh(f1)
mo[:,idx] = numpy.dot(orb, c)
mo_e[idx] = e
return mo_e, mo
示例6: time_reversal_matrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def time_reversal_matrix(mol, mat):
''' T(A_ij) = A[T(i),T(j)]^*
'''
n2c = mol.nao_2c()
tao = numpy.asarray(mol.time_reversal_map())
# tao(i) = -j means T(f_i) = -f_j
# tao(i) = j means T(f_i) = f_j
idx = abs(tao)-1 # -1 for C indexing convention
#:signL = [(1 if x>0 else -1) for x in tao]
#:sign = numpy.hstack((signL, signL))
#:tmat = numpy.empty_like(mat)
#:for j in range(mat.__len__()):
#: for i in range(mat.__len__()):
#: tmat[idx[i],idx[j]] = mat[i,j] * sign[i]*sign[j]
#:return tmat.conjugate()
sign_mask = tao<0
if mat.shape[0] == n2c*2:
idx = numpy.hstack((idx, idx+n2c))
sign_mask = numpy.hstack((sign_mask, sign_mask))
tmat = mat.take(idx,axis=0).take(idx,axis=1)
tmat[sign_mask,:] *= -1
tmat[:,sign_mask] *= -1
return tmat.T
示例7: contract_1e
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def contract_1e(f1e, fcivec, norb, nelec, link_index=None):
fcivec = numpy.asarray(fcivec, order='C')
link_index = _unpack(norb, nelec, link_index)
na, nlink = link_index.shape[:2]
assert(fcivec.size == na**2)
ci1 = numpy.empty_like(fcivec)
f1e_tril = lib.pack_tril(f1e)
libfci.FCIcontract_1e_spin0(f1e_tril.ctypes.data_as(ctypes.c_void_p),
fcivec.ctypes.data_as(ctypes.c_void_p),
ci1.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb), ctypes.c_int(na),
ctypes.c_int(nlink),
link_index.ctypes.data_as(ctypes.c_void_p))
# no *.5 because FCIcontract_2e_spin0 only compute half of the contraction
return lib.transpose_sum(ci1, inplace=True).reshape(fcivec.shape)
# Note eri is NOT the 2e hamiltonian matrix, the 2e hamiltonian is
# h2e = eri_{pq,rs} p^+ q r^+ s
# = (pq|rs) p^+ r^+ s q - (pq|rs) \delta_{qr} p^+ s
# so eri is defined as
# eri_{pq,rs} = (pq|rs) - (1/Nelec) \sum_q (pq|qs)
# to restore the symmetry between pq and rs,
# eri_{pq,rs} = (pq|rs) - (.5/Nelec) [\sum_q (pq|qs) + \sum_p (pq|rp)]
# Please refer to the treatment in direct_spin1.absorb_h1e
# the input fcivec should be symmetrized
示例8: reorder_eri
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def reorder_eri(eri, norb, orbsym):
if orbsym is None:
return [eri], numpy.arange(norb), numpy.zeros(norb,dtype=numpy.int32)
# map irrep IDs of Dooh or Coov to D2h, C2v
# see symm.basis.linearmole_symm_descent
orbsym = numpy.asarray(orbsym) % 10
# irrep of (ij| pair
trilirrep = (orbsym[:,None]^orbsym)[numpy.tril_indices(norb)]
# and the number of occurence for each irrep
dimirrep = numpy.asarray(numpy.bincount(trilirrep), dtype=numpy.int32)
# we sort the irreps of (ij| pair, to group the pairs which have same irreps
# "order" is irrep-id-sorted index. The (ij| paired is ordered that the
# pair-id given by order[0] comes first in the sorted pair
# "rank" is a sorted "order". Given nth (ij| pair, it returns the place(rank)
# of the sorted pair
old_eri_irrep = numpy.asarray(trilirrep, dtype=numpy.int32)
rank_in_irrep = numpy.empty_like(old_eri_irrep)
p0 = 0
eri_irs = [numpy.zeros((0,0))] * TOTIRREPS
for ir, nnorb in enumerate(dimirrep):
idx = numpy.asarray(numpy.where(trilirrep == ir)[0], dtype=numpy.int32)
rank_in_irrep[idx] = numpy.arange(nnorb, dtype=numpy.int32)
eri_irs[ir] = lib.take_2d(eri, idx, idx)
p0 += nnorb
return eri_irs, rank_in_irrep, old_eri_irrep
示例9: test_type2_rad_part
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def test_type2_rad_part(self):
rc = .8712
rs, ws = radi.gauss_chebyshev(99)
def type2_facs_rad(ish, lc):
facs0 = facs_rad(mol, ish, lc, rc, rs).transpose(0,2,1).copy()
facs1 = numpy.empty_like(facs0)
libecp.type2_facs_rad(facs1.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(ish), ctypes.c_int(lc),
ctypes.c_double(rc),
rs.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(len(rs)), ctypes.c_int(1),
mol._atm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(mol.natm),
mol._bas.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(mol.nbas),
mol._env.ctypes.data_as(ctypes.c_void_p))
self.assertTrue(numpy.allclose(facs0, facs1))
for ish in range(mol.nbas):
for lc in range(5):
type2_facs_rad(ish, lc)
示例10: gen_vind
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def gen_vind(mf, mo_coeff, mo_occ):
nao, nmo = mo_coeff.shape
mocc = mo_coeff[:,mo_occ>0]
nocc = mocc.shape[1]
vresp = mf.gen_response(mo_coeff, mo_occ, hermi=1)
def fx(mo1):
mo1 = mo1.reshape(-1,nmo,nocc)
nset = len(mo1)
dm1 = numpy.empty((nset,nao,nao))
for i, x in enumerate(mo1):
dm = reduce(numpy.dot, (mo_coeff, x*2, mocc.T)) # *2 for double occupancy
dm1[i] = dm + dm.T
v1 = vresp(dm1)
v1vo = numpy.empty_like(mo1)
for i, x in enumerate(v1):
v1vo[i] = reduce(numpy.dot, (mo_coeff.T, x, mocc))
return v1vo
return fx
示例11: test_cholesky_eri
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def test_cholesky_eri(self):
j2c = df.incore.fill_2c2e(mol, auxmol)
eri0 = numpy.empty_like(j2c)
pi = 0
for i in range(mol.nbas, len(bas)):
pj = 0
for j in range(mol.nbas, len(bas)):
shls = (i, j)
buf = gto.moleintor.getints_by_shell('int2c2e_sph',
shls, atm, bas, env)
di, dj = buf.shape
eri0[pi:pi+di,pj:pj+dj] = buf
pj += dj
pi += di
self.assertTrue(numpy.allclose(eri0, j2c))
j3c = df.incore.aux_e2(mol, auxmol, intor='int3c2e_sph', aosym='s2ij')
cderi = df.incore.cholesky_eri(mol)
eri0 = numpy.einsum('pi,pk->ik', cderi, cderi)
eri1 = numpy.einsum('ik,kl->il', j3c, numpy.linalg.inv(j2c))
eri1 = numpy.einsum('ip,kp->ik', eri1, j3c)
self.assertTrue(numpy.allclose(eri1, eri0))
cderi1 = df.incore.cholesky_eri_debug(mol)
self.assertAlmostEqual(abs(cderi-cderi1).max(), 0, 9)
示例12: _solve_mo1_uncoupled
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def _solve_mo1_uncoupled(mo_energy, mo_occ, h1, s1):
'''uncoupled first order equation'''
e_a = mo_energy[mo_occ==0]
e_i = mo_energy[mo_occ>0]
e_ai = 1 / (e_a.reshape(-1,1) - e_i)
hs = h1 - s1 * e_i
mo10 = numpy.empty_like(hs)
mo10[:,mo_occ==0,:] = -hs[:,mo_occ==0,:] * e_ai
mo10[:,mo_occ>0,:] = -s1[:,mo_occ>0,:] * .5
e_ji = e_i.reshape(-1,1) - e_i
mo_e10 = hs[:,mo_occ>0,:] + mo10[:,mo_occ>0,:] * e_ji
return mo10, mo_e10
#TODO: merge to hessian.rhf.solve_mo1 function
示例13: _add_giao_phase
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def _add_giao_phase(mol, vmat):
'''Add the factor i/2*(Ri-Rj) of the GIAO phase e^{i/2 (Ri-Rj) times r}'''
ao_coords = rhf_mag._get_ao_coords(mol)
Rx = .5 * (ao_coords[:,0:1] - ao_coords[:,0])
Ry = .5 * (ao_coords[:,1:2] - ao_coords[:,1])
Rz = .5 * (ao_coords[:,2:3] - ao_coords[:,2])
vxc20 = numpy.empty_like(vmat)
vxc20[0] = Ry * vmat[2] - Rz * vmat[1]
vxc20[1] = Rz * vmat[0] - Rx * vmat[2]
vxc20[2] = Rx * vmat[1] - Ry * vmat[0]
vxc20, vmat = vmat, vxc20
vxc20[:,0] = Ry * vmat[:,2] - Rz * vmat[:,1]
vxc20[:,1] = Rz * vmat[:,0] - Rx * vmat[:,2]
vxc20[:,2] = Rx * vmat[:,1] - Ry * vmat[:,0]
vxc20 *= -1
return vxc20
示例14: mask_randomly
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def mask_randomly(self, imgs):
y1 = np.random.randint(0, self.img_rows - self.mask_height, imgs.shape[0])
y2 = y1 + self.mask_height
x1 = np.random.randint(0, self.img_rows - self.mask_width, imgs.shape[0])
x2 = x1 + self.mask_width
masked_imgs = np.empty_like(imgs)
missing_parts = np.empty((imgs.shape[0], self.mask_height, self.mask_width, self.channels))
for i, img in enumerate(imgs):
masked_img = img.copy()
_y1, _y2, _x1, _x2 = y1[i], y2[i], x1[i], x2[i]
missing_parts[i] = masked_img[_y1:_y2, _x1:_x2, :].copy()
masked_img[_y1:_y2, _x1:_x2, :] = 0
masked_imgs[i] = masked_img
return masked_imgs, missing_parts, (y1, y2, x1, x2)
示例15: log_loss_value
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import empty_like [as 别名]
def log_loss_value(Z, weights, total_weights, rho):
"""
computes the value and slope of the logistic loss in a numerically stable way
supports sample non-negative weights for each example in the training data
see http://stackoverflow.com/questions/20085768/
Parameters
----------
Z numpy.array containing training data with shape = (n_rows, n_cols)
rho numpy.array of coefficients with shape = (n_cols,)
total_weights numpy.sum(total_weights) (only included to reduce computation)
weights numpy.array of sample weights with shape (n_rows,)
Returns
-------
loss_value scalar = 1/n_rows * sum(log( 1 .+ exp(-Z*rho))
"""
scores = Z.dot(rho)
pos_idx = scores > 0
loss_value = np.empty_like(scores)
loss_value[pos_idx] = np.log1p(np.exp(-scores[pos_idx]))
loss_value[~pos_idx] = -scores[~pos_idx] + np.log1p(np.exp(scores[~pos_idx]))
loss_value = loss_value.dot(weights) / total_weights
return loss_value