Here are the examples of the python api numpy.number taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
66 Examples
3
Example 1
Project: pyscf Source File: rdm.py
def make_rdm12_ms0(fname, cibra, ciket, norb, nelec, link_index=None, symm=0):
if link_index is None:
if isinstance(nelec, (int, numpy.number)):
neleca = nelec//2
else:
neleca, nelecb = nelec
assert(neleca == nelecb)
link_index = cistring.gen_linkstr_index(range(norb), neleca)
link_index = (link_index, link_index)
return make_rdm12_spin1(fname, cibra, ciket, norb, nelec, link_index, symm)
3
Example 2
def isnumber(x):
# These are scalar quantities that we can compare (=,>,>=, etc.)
if isinstance(x, Number):
return True
if numpy is not None and isinstance(x, numpy.number):
return True
return False
3
Example 3
def contract_2e_hubbard(u, fcivec, nsite, nelec, nphonon):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
strsa = numpy.asarray(cistring.gen_strings4orblist(range(nsite), neleca))
strsb = numpy.asarray(cistring.gen_strings4orblist(range(nsite), nelecb))
cishape = make_shape(nsite, nelec, nphonon)
ci0 = fcivec.reshape(cishape)
fcinew = numpy.zeros(cishape)
for i in range(nsite):
maska = (strsa & (1<<i)) > 0
maskb = (strsb & (1<<i)) > 0
fcinew[maska[:,None]&maskb] += u * ci0[maska[:,None]&maskb]
return fcinew.reshape(fcivec.shape)
3
Example 4
def _unpack(norb, nelec, link_index):
if link_index is None:
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
link_indexa = cistring.gen_linkstr_index(range(norb), neleca)
link_indexb = cistring.gen_linkstr_index(range(norb), nelecb)
return link_indexa, link_indexb
else:
return link_index
3
Example 5
Project: pyscf Source File: direct_spin0_symm.py
def dump_flags(self, verbose=None):
if verbose is None: verbose = self.verbose
direct_spin0.FCISolver.dump_flags(self, verbose)
log = logger.Logger(self.stdout, verbose)
if isinstance(self.wfnsym, str):
log.info('specified CI wfn symmetry = %s', self.wfnsym)
elif isinstance(self.wfnsym, (int, numpy.number)):
log.info('specified CI wfn symmetry = %s',
symm.irrep_id2name(self.mol.groupname, self.wfnsym))
3
Example 6
def absorb_h1e(h1e, eri, norb, nelec, fac=1):
'''Modify 2e Hamiltonian to include 1e Hamiltonian contribution.
'''
if not isinstance(nelec, (int, numpy.number)):
nelec = sum(nelec)
eri = eri.copy()
h2e = pyscf.ao2mo.restore(1, eri, norb)
f1e = h1e - numpy.einsum('jiik->jk', h2e) * .5
f1e = f1e * (1./(nelec+1e-100))
for k in range(norb):
h2e[k,k,:,:] += f1e
h2e[:,:,k,k] += f1e
return h2e * fac
3
Example 7
Project: polar2grid Source File: containers.py
def default(self, obj):
if isinstance(obj, BaseP2GObject):
mod_str = str(obj.__class__.__module__)
mod_str = mod_str + "." if mod_str != __name__ else ""
cls_str = str(obj.__class__.__name__)
obj = obj.copy(as_dict=True)
# object should now be a builtin dict
obj["__class__"] = mod_str + cls_str
return obj
# return super(P2GJSONEncoder, self).encode(obj)
elif isinstance(obj, datetime):
return obj.isoformat()
elif numpy.issubclass_(obj, numpy.number):
return dtype_to_str(obj)
else:
return super(P2GJSONEncoder, self).default(obj)
3
Example 8
def kernel(self, h1e, eri, norb, nelec, ci0=None,
tol=None, lindep=None, max_cycle=None, max_space=None,
nroots=None, davidson_only=None, pspace_size=None,
orbsym=None, wfnsym=None, **kwargs):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
link_indexa = cistring.gen_linkstr_index(range(norb), neleca)
link_indexb = cistring.gen_linkstr_index(range(norb), nelecb)
e, c = direct_spin1.kernel_ms1(self, h1e, eri, norb, nelec, ci0,
(link_indexa,link_indexb),
tol, lindep, max_cycle, max_space, nroots,
davidson_only, pspace_size, **kwargs)
return e, c
3
Example 9
Project: statsmodels Source File: pandas.py
def is_numeric_dtype(arr_or_dtype):
# Crude implementation only suitable for array-like types
try:
tipo = arr_or_dtype.dtype.type
except AttributeError:
tipo = type(None)
return (issubclass(tipo, (np.number, np.bool_)) and
not issubclass(tipo, (np.datetime64, np.timedelta64)))
3
Example 10
def edit_clicked(self):
idx = self.table.selectedIndexes()
if idx:
idx = self.table_model_filter.mapToSource(idx[0])
key = self.table_model.index_to_key(idx)
if key is not None:
persist, value = self.table_model.backing_store[key]
t = type(value)
if np.issubdtype(t, np.number):
dialog_cls = NumberEditor
elif np.issubdtype(t, np.bool_):
dialog_cls = BoolEditor
elif np.issubdtype(t, np.unicode_):
dialog_cls = StringEditor
else:
logger.error("Cannot edit dataset %s: "
"type %s is not supported", key, t)
return
dialog_cls(self, self.dataset_ctl, key, value).open()
3
Example 11
def dump_flags(self, verbose=None):
if verbose is None: verbose = self.verbose
direct_spin1.FCISolver.dump_flags(self, verbose)
log = pyscf.lib.logger.Logger(self.stdout, verbose)
if isinstance(self.wfnsym, str):
log.info('specified CI wfn symmetry = %s', self.wfnsym)
elif isinstance(self.wfnsym, (int, numpy.number)):
log.info('specified CI wfn symmetry = %s',
symm.irrep_id2name(self.mol.groupname, self.wfnsym))
return self
3
Example 12
def _unpack(nelec):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
return neleca, nelecb
else:
return nelec
3
Example 13
def make_shape(nsite, nelec, nphonon):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
na = cistring.num_strings(nsite, neleca)
nb = cistring.num_strings(nsite, nelecb)
return (na,nb)+(nphonon+1,)*nsite
3
Example 14
@pyscf.lib.with_doc(direct_spin1.trans_rdm1s.__doc__)
def trans_rdm1s(cibra, ciket, norb, nelec, link_index=None):
if link_index is None:
if isinstance(nelec, (int, numpy.number)):
neleca = nelec//2
else:
neleca, nelecb = nelec
assert(neleca == nelecb)
link_index = cistring.gen_linkstr_index(range(norb), neleca)
rdm1a = rdm.make_rdm1('FCItrans_rdm1a', cibra, ciket,
norb, nelec, link_index)
rdm1b = rdm.make_rdm1('FCItrans_rdm1b', cibra, ciket,
norb, nelec, link_index)
return rdm1a, rdm1b
3
Example 15
def contract_1e(h1e, fcivec, nsite, nelec, nphonon):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
link_indexa = cistring.gen_linkstr_index(range(nsite), neleca)
link_indexb = cistring.gen_linkstr_index(range(nsite), nelecb)
cishape = make_shape(nsite, nelec, nphonon)
ci0 = fcivec.reshape(cishape)
fcinew = numpy.zeros(cishape)
for str0, tab in enumerate(link_indexa):
for a, i, str1, sign in tab:
fcinew[str1] += sign * ci0[str0] * h1e[a,i]
for str0, tab in enumerate(link_indexb):
for a, i, str1, sign in tab:
fcinew[:,str1] += sign * ci0[:,str0] * h1e[a,i]
return fcinew.reshape(fcivec.shape)
3
Example 16
def write_head(fout, nmo, nelec, ms=0, orbsym=[]):
if not isinstance(nelec, (int, numpy.number)):
ms = abs(nelec[0] - nelec[1])
nelec = nelec[0] + nelec[1]
fout.write(' &FCI NORB=%4d,NELEC=%2d,MS2=%d,\n' % (nmo, nelec, ms))
if orbsym:
fout.write(' ORBSYM=%s\n' % ','.join([str(x) for x in orbsym]))
else:
fout.write(' ORBSYM=%s\n' % ('1,' * nmo))
fout.write(' ISYM=1,\n')
fout.write(' &END\n')
3
Example 17
Project: polar2grid Source File: dtype.py
def str_to_dtype(dtype_str):
if numpy.issubclass_(dtype_str, numpy.number):
# if they gave us a numpy dtype
return dtype_str
try:
return str2dtype[dtype_str]
except KeyError:
raise ValueError("Not a valid data type string: %s" % (dtype_str,))
3
Example 18
def is_zero(x):
# DO NOT try to replace this with an attempted '== 0' comparison.
# This will become an elementwise numpy operation and not do what
# you want.
if isinstance(x, (int, complex, float, numpy.number)):
return x == 0
else:
return False
3
Example 19
Project: caravel Source File: dataframe.py
def agg_func(dtype, column_name):
# consider checking for key substring too.
if is_id(column_name):
return 'count_distinct'
if np.issubdtype(dtype, np.number):
return 'sum'
return None
3
Example 20
Project: artiq Source File: tools.py
def short_format(v):
if v is None:
return "None"
t = type(v)
if np.issubdtype(t, np.number) or np.issubdtype(t, np.bool_):
return str(v)
elif np.issubdtype(t, np.unicode_):
return "\"" + elide(v, 50) + "\""
else:
r = t.__name__
if t is list or t is dict or t is set:
r += " ({})".format(len(v))
if t is np.ndarray:
r += " " + str(np.shape(v))
return r
3
Example 21
def _convert_array(self, array):
try:
global np
import numpy as np
except ImportError as ex:
raise ImportError('DataFrameClient requires Numpy, '
'"{ex}" problem importing'.format(ex=str(ex)))
if self.ignore_nan:
number_types = (int, float, np.number)
condition = (all(isinstance(el, number_types) for el in array) and
np.isnan(array))
return list(np.where(condition, None, array))
else:
return list(array)
3
Example 22
def absorb_h1e(h1e, eri, norb, nelec, fac=1):
'''Modify 2e Hamiltonian to include 1e Hamiltonian contribution.
'''
if not isinstance(nelec, (int, numpy.number)):
nelec = sum(nelec)
eri = eri.copy()
h2e = pyscf.ao2mo.restore(1, eri, norb)
f1e = h1e - numpy.einsum('jiik->jk', h2e) * .5
f1e = f1e * (1./(nelec+1e-100))
for k in range(norb):
h2e[k,k,:,:] += f1e
h2e[:,:,k,k] += f1e
return pyscf.ao2mo.restore(4, h2e, norb) * fac
3
Example 23
def _unpack(norb, nelec, link_index):
if link_index is None:
if isinstance(nelec, (int, numpy.number)):
neleca = nelec//2
else:
neleca, nelecb = nelec
assert(neleca == nelecb)
return cistring.gen_linkstr_index_trilidx(range(norb), neleca)
else:
return link_index
3
Example 24
def make_rdm1s(fcivec, norb, nelec, link_index=None):
'''Spin searated 1-particle density matrices, (alpha,beta)
'''
if link_index is None:
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
link_indexa = cistring.gen_linkstr_index(range(norb), neleca)
link_indexb = cistring.gen_linkstr_index(range(norb), nelecb)
link_index = (link_indexa, link_indexb)
rdm1a = rdm.make_rdm1_spin1('FCImake_rdm1a', fcivec, fcivec,
norb, nelec, link_index)
rdm1b = rdm.make_rdm1_spin1('FCImake_rdm1b', fcivec, fcivec,
norb, nelec, link_index)
return rdm1a, rdm1b
3
Example 25
def _convert_array(array, dtype):
"""
Converts an array to a new dtype--if the itemsize of the new dtype is
the same as the old dtype and both types are not numeric, a view is
returned. Otherwise a new array must be created.
"""
if array.dtype == dtype:
return array
elif (array.dtype.itemsize == dtype.itemsize and not
(np.issubdtype(array.dtype, np.number) and
np.issubdtype(dtype, np.number))):
# Includes a special case when both dtypes are at least numeric to
# account for ticket #218: https://aeon.stsci.edu/ssb/trac/pyfits/ticket/218
return array.view(dtype)
else:
return array.astype(dtype)
3
Example 26
def _unpack(norb, nelec, link_index):
if link_index is None:
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
link_indexa = cistring.gen_linkstr_index_trilidx(range(norb), neleca)
link_indexb = cistring.gen_linkstr_index_trilidx(range(norb), nelecb)
return link_indexa, link_indexb
else:
return link_index
3
Example 27
@network
def test_dtypes(self):
#GH3995, #GH8980
data = web.get_data_google('F', start='JAN-01-10', end='JAN-27-13')
self.assertTrue(np.issubdtype(data.Open.dtype, np.number))
self.assertTrue(np.issubdtype(data.Close.dtype, np.number))
self.assertTrue(np.issubdtype(data.Low.dtype, np.number))
self.assertTrue(np.issubdtype(data.High.dtype, np.number))
self.assertTrue(np.issubdtype(data.Volume.dtype, np.number))
3
Example 28
def absorb_h1e(h1e, eri, norb, nelec, fac=1):
'''Modify 2e Hamiltonian to include 1e Hamiltonian contribution.
'''
if not isinstance(nelec, (int, numpy.number)):
nelec = sum(nelec)
h2e = eri.copy()
f1e = h1e - numpy.einsum('jiik->jk', h2e) * .5
f1e = f1e * (1./(nelec+1e-100))
for k in range(norb):
h2e[k,k,:,:] += f1e
h2e[:,:,k,k] += f1e
return h2e * fac
3
Example 29
Project: pyscf Source File: direct_spin1_symm.py
def _id_wfnsym(cis, norb, nelec, wfnsym):
if wfnsym is None:
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
wfnsym = 0 # Ag, A1 or A
for i in cis.orbsym[nelecb:neleca]:
wfnsym ^= i
elif isinstance(wfnsym, str):
wfnsym = symm.irrep_name2id(cis.mol.groupname, wfnsym) % 10
return wfnsym
2
Example 30
Project: pyscf Source File: casci.py
def kernel(self, mo_coeff=None, ci0=None):
if mo_coeff is None:
mo_coeff = self.mo_coeff
else:
self.mo_coeff = mo_coeff
if ci0 is None:
ci0 = self.ci
if self.verbose >= logger.WARN:
self.check_sanity()
self.dump_flags()
self.e_tot, self.e_cas, self.ci = \
kernel(self, mo_coeff, ci0=ci0, verbose=self.verbose)
log = logger.Logger(self.stdout, self.verbose)
if self.canonicalization:
if isinstance(self.e_cas, (float, numpy.number)):
self.canonicalize_(mo_coeff, self.ci,
cas_natorb=self.natorb, verbose=log)
else:
self.canonicalize_(mo_coeff, self.ci[0],
cas_natorb=self.natorb, verbose=log)
if log.verbose >= logger.NOTE and hasattr(self.fcisolver, 'spin_square'):
ss = self.fcisolver.spin_square(self.ci, self.ncas, self.nelecas)
if isinstance(self.e_cas, (float, numpy.number)):
log.note('CASCI E = %.15g E(CI) = %.15g S^2 = %.7f',
self.e_tot, self.e_cas, ss[0])
else:
for i, e in enumerate(self.e_cas):
log.note('CASCI root %d E = %.15g E(CI) = %.15g S^2 = %.7f',
i, self.e_tot[i], e, ss[0][i])
else:
if isinstance(self.e_cas, (float, numpy.number)):
log.note('CASCI E = %.15g E(CI) = %.15g', self.e_tot, self.e_cas)
else:
for i, e in enumerate(self.e_cas):
log.note('CASCI root %d E = %.15g E(CI) = %.15g',
i, self.e_tot[i], e)
self._finalize()
return self.e_tot, self.e_cas, self.ci, self.mo_coeff, self.mo_energy
0
Example 31
def get_init_guess(norb, nelec, nroots, hdiag, orbsym, wfnsym=0):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
strsa = numpy.asarray(cistring.gen_strings4orblist(range(norb), neleca))
strsb = numpy.asarray(cistring.gen_strings4orblist(range(norb), nelecb))
airreps = numpy.zeros(strsa.size, dtype=numpy.int32)
birreps = numpy.zeros(strsb.size, dtype=numpy.int32)
for i in range(norb):
airreps[numpy.bitwise_and(strsa, 1<<i) > 0] ^= orbsym[i]
birreps[numpy.bitwise_and(strsb, 1<<i) > 0] ^= orbsym[i]
na = len(strsa)
nb = len(strsb)
ci0 = []
iroot = 0
for addr in numpy.argsort(hdiag):
x = numpy.zeros((na*nb))
addra = addr // nb
addrb = addr % nb
if airreps[addra] ^ birreps[addrb] == wfnsym:
x[addr] = 1
ci0.append(x)
iroot += 1
if iroot >= nroots:
break
# Add noise
ci0[0][0 ] += 1e-5
ci0[0][-1] -= 1e-5
return ci0
0
Example 32
def contract_2e_hubbard(u, fcivec, norb, nelec, opt=None):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
u_aa, u_ab, u_bb = u
strsa = numpy.asarray(cistring.gen_strings4orblist(range(norb), neleca))
strsb = numpy.asarray(cistring.gen_strings4orblist(range(norb), nelecb))
na = cistring.num_strings(norb, neleca)
nb = cistring.num_strings(norb, nelecb)
fcivec = fcivec.reshape(na,nb)
fcinew = numpy.zeros_like(fcivec)
if u_aa != 0: # u * n_alpha^+ n_alpha
for i in range(norb):
maska = (strsa & (1<<i)) > 0
fcinew[maska] += u_aa * fcivec[maska]
if u_ab != 0: # u * (n_alpha^+ n_beta + n_beta^+ n_alpha)
for i in range(norb):
maska = (strsa & (1<<i)) > 0
maskb = (strsb & (1<<i)) > 0
fcinew[maska[:,None]&maskb] += 2*u_ab * fcivec[maska[:,None]&maskb]
if u_bb != 0: # u * n_beta^+ n_beta
for i in range(norb):
maskb = (strsb & (1<<i)) > 0
fcinew[:,maskb] += u_bb * fcivec[:,maskb]
return fcinew
0
Example 33
def make_hdiag(h1e, eri, norb, nelec):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
h1e_a = numpy.ascontiguousarray(h1e[0])
h1e_b = numpy.ascontiguousarray(h1e[1])
g2e_aa = pyscf.ao2mo.restore(1, eri[0], norb)
g2e_ab = pyscf.ao2mo.restore(1, eri[1], norb)
g2e_bb = pyscf.ao2mo.restore(1, eri[2], norb)
link_indexa = cistring.gen_linkstr_index(range(norb), neleca)
link_indexb = cistring.gen_linkstr_index(range(norb), nelecb)
na = link_indexa.shape[0]
nb = link_indexb.shape[0]
occslista = numpy.asarray(link_indexa[:,:neleca,0], order='C')
occslistb = numpy.asarray(link_indexb[:,:nelecb,0], order='C')
hdiag = numpy.empty(na*nb)
jdiag_aa = numpy.asarray(numpy.einsum('iijj->ij',g2e_aa), order='C')
jdiag_ab = numpy.asarray(numpy.einsum('iijj->ij',g2e_ab), order='C')
jdiag_bb = numpy.asarray(numpy.einsum('iijj->ij',g2e_bb), order='C')
kdiag_aa = numpy.asarray(numpy.einsum('ijji->ij',g2e_aa), order='C')
kdiag_bb = numpy.asarray(numpy.einsum('ijji->ij',g2e_bb), order='C')
libfci.FCImake_hdiag_uhf(hdiag.ctypes.data_as(ctypes.c_void_p),
h1e_a.ctypes.data_as(ctypes.c_void_p),
h1e_b.ctypes.data_as(ctypes.c_void_p),
jdiag_aa.ctypes.data_as(ctypes.c_void_p),
jdiag_ab.ctypes.data_as(ctypes.c_void_p),
jdiag_bb.ctypes.data_as(ctypes.c_void_p),
kdiag_aa.ctypes.data_as(ctypes.c_void_p),
kdiag_bb.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb),
ctypes.c_int(na), ctypes.c_int(nb),
ctypes.c_int(neleca), ctypes.c_int(nelecb),
occslista.ctypes.data_as(ctypes.c_void_p),
occslistb.ctypes.data_as(ctypes.c_void_p))
return numpy.asarray(hdiag)
0
Example 34
def absorb_h1e(h1e, eri, norb, nelec, fac=1):
if not isinstance(nelec, (int, numpy.number)):
nelec = sum(nelec)
h1e_a, h1e_b = h1e
h2e_aa = pyscf.ao2mo.restore(1, eri[0], norb).copy()
h2e_ab = pyscf.ao2mo.restore(1, eri[1], norb).copy()
h2e_bb = pyscf.ao2mo.restore(1, eri[2], norb).copy()
f1e_a = h1e_a - numpy.einsum('jiik->jk', h2e_aa) * .5
f1e_b = h1e_b - numpy.einsum('jiik->jk', h2e_bb) * .5
f1e_a *= 1./(nelec+1e-100)
f1e_b *= 1./(nelec+1e-100)
for k in range(norb):
h2e_aa[:,:,k,k] += f1e_a
h2e_aa[k,k,:,:] += f1e_a
h2e_ab[:,:,k,k] += f1e_a
h2e_ab[k,k,:,:] += f1e_b
h2e_bb[:,:,k,k] += f1e_b
h2e_bb[k,k,:,:] += f1e_b
return (pyscf.ao2mo.restore(4, h2e_aa, norb) * fac,
pyscf.ao2mo.restore(4, h2e_ab, norb) * fac,
pyscf.ao2mo.restore(4, h2e_bb, norb) * fac)
0
Example 35
Project: pystan Source File: misc.py
def _dict_to_rdump(data):
parts = []
for name, value in data.items():
if isinstance(value, (Sequence, Number, np.number, np.ndarray, int, bool, float)) \
and not isinstance(value, string_types):
value = np.asarray(value)
else:
raise ValueError("Variable {} is not a number and cannot be dumped.".format(name))
if value.dtype == np.bool:
value = value.astype(int)
if value.ndim == 0:
s = '{} <- {}\n'.format(name, str(value))
elif value.ndim == 1:
s = '{} <-\nc({})\n'.format(name, ', '.join(str(v) for v in value))
elif value.ndim > 1:
tmpl = '{} <-\nstructure(c({}), .Dim = c({}))\n'
# transpose value as R uses column-major
# 'F' = Fortran, column-major
s = tmpl.format(name,
', '.join(str(v) for v in value.flatten(order='F')),
', '.join(str(v) for v in value.shape))
parts.append(s)
return ''.join(parts)
0
Example 36
@pyscf.lib.with_doc(direct_spin1.make_hdiag.__doc__)
def make_hdiag(h1e, eri, norb, nelec):
if isinstance(nelec, (int, numpy.number)):
neleca = nelec//2
else:
neleca, nelecb = nelec
assert(neleca == nelecb)
h1e = numpy.ascontiguousarray(h1e)
eri = pyscf.ao2mo.restore(1, eri, norb)
link_index = cistring.gen_linkstr_index(range(norb), neleca)
na = link_index.shape[0]
occslist = numpy.asarray(link_index[:,:neleca,0], order='C')
hdiag = numpy.empty((na,na))
jdiag = numpy.asarray(numpy.einsum('iijj->ij',eri), order='C')
kdiag = numpy.asarray(numpy.einsum('ijji->ij',eri), order='C')
libfci.FCImake_hdiag(hdiag.ctypes.data_as(ctypes.c_void_p),
h1e.ctypes.data_as(ctypes.c_void_p),
jdiag.ctypes.data_as(ctypes.c_void_p),
kdiag.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb), ctypes.c_int(na),
ctypes.c_int(neleca),
occslist.ctypes.data_as(ctypes.c_void_p))
# symmetrize hdiag to reduce numerical error
hdiag = pyscf.lib.transpose_sum(hdiag, inplace=True) * .5
return hdiag.ravel()
0
Example 37
def pspace(h1e, eri, norb, nelec, hdiag, np=400):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
h1e_a = numpy.ascontiguousarray(h1e[0])
h1e_b = numpy.ascontiguousarray(h1e[1])
g2e_aa = pyscf.ao2mo.restore(1, eri[0], norb)
g2e_ab = pyscf.ao2mo.restore(1, eri[1], norb)
g2e_bb = pyscf.ao2mo.restore(1, eri[2], norb)
link_indexa = cistring.gen_linkstr_index_trilidx(range(norb), neleca)
link_indexb = cistring.gen_linkstr_index_trilidx(range(norb), nelecb)
nb = link_indexb.shape[0]
addr = numpy.argsort(hdiag)[:np]
addra = addr // nb
addrb = addr % nb
stra = numpy.array([cistring.addr2str(norb,neleca,ia) for ia in addra],
dtype=numpy.long)
strb = numpy.array([cistring.addr2str(norb,nelecb,ib) for ib in addrb],
dtype=numpy.long)
np = len(addr)
h0 = numpy.zeros((np,np))
libfci.FCIpspace_h0tril_uhf(h0.ctypes.data_as(ctypes.c_void_p),
h1e_a.ctypes.data_as(ctypes.c_void_p),
h1e_b.ctypes.data_as(ctypes.c_void_p),
g2e_aa.ctypes.data_as(ctypes.c_void_p),
g2e_ab.ctypes.data_as(ctypes.c_void_p),
g2e_bb.ctypes.data_as(ctypes.c_void_p),
stra.ctypes.data_as(ctypes.c_void_p),
strb.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb), ctypes.c_int(np))
for i in range(np):
h0[i,i] = hdiag[addr[i]]
h0 = pyscf.lib.hermi_triu(h0)
return addr, h0
0
Example 38
@pyscf.lib.with_doc(direct_spin1.pspace.__doc__)
def pspace(h1e, eri, norb, nelec, hdiag, np=400):
if isinstance(nelec, (int, numpy.number)):
neleca = nelec//2
else:
neleca, nelecb = nelec
assert(neleca == nelecb)
h1e = numpy.ascontiguousarray(h1e)
eri = pyscf.ao2mo.restore(1, eri, norb)
na = cistring.num_strings(norb, neleca)
addr = numpy.argsort(hdiag)[:np]
# symmetrize addra/addrb
addra = addr // na
addrb = addr % na
stra = numpy.array([cistring.addr2str(norb,neleca,ia) for ia in addra],
dtype=numpy.long)
strb = numpy.array([cistring.addr2str(norb,neleca,ib) for ib in addrb],
dtype=numpy.long)
np = len(addr)
h0 = numpy.zeros((np,np))
libfci.FCIpspace_h0tril(h0.ctypes.data_as(ctypes.c_void_p),
h1e.ctypes.data_as(ctypes.c_void_p),
eri.ctypes.data_as(ctypes.c_void_p),
stra.ctypes.data_as(ctypes.c_void_p),
strb.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb), ctypes.c_int(np))
for i in range(np):
h0[i,i] = hdiag[addr[i]]
h0 = pyscf.lib.hermi_triu(h0)
return addr, h0
0
Example 39
Project: attention-lvcsr Source File: sharedvar.py
@shared_constructor
def scalar_constructor(value, name=None, strict=False, allow_downcast=None,
borrow=False, target='cpu'):
"""
SharedVariable constructor for scalar values. Default: int64 or float64.
Notes
-----
We implement this using 0-d tensors for now.
We ignore the borrow parameter as we convert ``value`` to an
ndarray (this is a new object). This respects the semantic of
borrow, as it is a hint to Theano that we can reuse it.
"""
if target != 'cpu':
raise TypeError('not for cpu')
if not isinstance(value, (numpy.number, float, int, complex)):
raise TypeError()
try:
dtype = value.dtype
except Exception:
dtype = numpy.asarray(value).dtype
dtype = str(dtype)
value = theano._asarray(value, dtype=dtype)
tensor_type = TensorType(dtype=str(value.dtype), broadcastable=[])
try:
# Do not pass the dtype to asarray because we want this to fail if
# strict is True and the types do not match.
rval = ScalarSharedVariable(type=tensor_type,
value=numpy.array(value, copy=True),
name=name,
strict=strict,
allow_downcast=allow_downcast)
return rval
except Exception:
traceback.print_exc()
raise
0
Example 40
def contract_2e(eri, fcivec, nsite, nelec, nphonon):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
link_indexa = cistring.gen_linkstr_index(range(nsite), neleca)
link_indexb = cistring.gen_linkstr_index(range(nsite), nelecb)
cishape = make_shape(nsite, nelec, nphonon)
ci0 = fcivec.reshape(cishape)
t1a = numpy.zeros((nsite,nsite)+cishape)
t1b = numpy.zeros((nsite,nsite)+cishape)
for str0, tab in enumerate(link_indexa):
for a, i, str1, sign in tab:
t1a[a,i,str1] += sign * ci0[str0]
for str0, tab in enumerate(link_indexb):
for a, i, str1, sign in tab:
t1b[a,i,:,str1] += sign * ci0[:,str0]
g2e_aa = pyscf.ao2mo.restore(1, eri[0], nsite)
g2e_ab = pyscf.ao2mo.restore(1, eri[1], nsite)
g2e_bb = pyscf.ao2mo.restore(1, eri[2], nsite)
t2a = numpy.dot(g2e_aa.reshape(nsite**2,-1), t1a.reshape(nsite**2,-1))
t2a+= numpy.dot(g2e_ab.reshape(nsite**2,-1), t1b.reshape(nsite**2,-1))
t2b = numpy.dot(g2e_ab.reshape(nsite**2,-1).T, t1a.reshape(nsite**2,-1))
t2b+= numpy.dot(g2e_bb.reshape(nsite**2,-1), t1b.reshape(nsite**2,-1))
t2a = t2a.reshape((nsite,nsite)+cishape)
t2b = t2b.reshape((nsite,nsite)+cishape)
fcinew = numpy.zeros(cishape)
for str0, tab in enumerate(link_indexa):
for a, i, str1, sign in tab:
fcinew[str1] += sign * t2a[a,i,str0]
for str0, tab in enumerate(link_indexb):
for a, i, str1, sign in tab:
fcinew[:,str1] += sign * t2b[a,i,:,str0]
return fcinew.reshape(fcivec.shape)
0
Example 41
def get_init_guess(norb, nelec, nroots, hdiag):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
na = cistring.num_strings(norb, neleca)
nb = cistring.num_strings(norb, nelecb)
init_strs = []
iroot = 0
for addr in numpy.argsort(hdiag):
addra = addr // nb
addrb = addr % nb
if (addrb,addra) not in init_strs: # avoid initial guess linear dependency
init_strs.append((addra,addrb))
iroot += 1
if iroot >= nroots:
break
ci0 = []
for addra,addrb in init_strs:
x = numpy.zeros((na,nb))
if addra == addrb == 0:
x[addra,addrb] = 1
else:
x[addra,addrb] = x[addrb,addra] = numpy.sqrt(.5)
ci0.append(x.ravel())
# Add noise
ci0[0][0 ] += 1e-5
ci0[0][-1] -= 1e-5
return ci0
0
Example 42
def get_init_guess(norb, nelec, nroots, hdiag, orbsym, wfnsym=0):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
strsa = numpy.asarray(cistring.gen_strings4orblist(range(norb), neleca))
strsb = numpy.asarray(cistring.gen_strings4orblist(range(norb), nelecb))
airreps = numpy.zeros(strsa.size, dtype=numpy.int32)
birreps = numpy.zeros(strsb.size, dtype=numpy.int32)
for i in range(norb):
airreps[numpy.bitwise_and(strsa, 1<<i) > 0] ^= orbsym[i]
birreps[numpy.bitwise_and(strsb, 1<<i) > 0] ^= orbsym[i]
na = len(strsa)
nb = len(strsb)
init_strs = []
iroot = 0
for addr in numpy.argsort(hdiag):
addra = addr // nb
addrb = addr % nb
if airreps[addra] ^ birreps[addrb] == wfnsym:
if (addrb,addra) not in init_strs:
init_strs.append((addra,addrb))
iroot += 1
if iroot >= nroots:
break
ci0 = []
for addra,addrb in init_strs:
x = numpy.zeros((na,nb))
if addra == addrb == 0:
x[addra,addrb] = 1
else:
x[addra,addrb] = x[addrb,addra] = numpy.sqrt(.5)
ci0.append(x.ravel())
if len(ci0) == 0:
raise RuntimeError('No determinant matches the target symmetry %s' %
wfnsym)
return ci0
0
Example 43
Project: pyscf Source File: direct_ep.py
def contract_ep(g, fcivec, nsite, nelec, nphonon):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
strsa = numpy.asarray(cistring.gen_strings4orblist(range(nsite), neleca))
strsb = numpy.asarray(cistring.gen_strings4orblist(range(nsite), nelecb))
cishape = make_shape(nsite, nelec, nphonon)
na, nb = cishape[:2]
ci0 = fcivec.reshape(cishape)
fcinew = numpy.zeros(cishape)
nbar = float(neleca+nelecb) / nsite
phonon_cre = numpy.sqrt(numpy.arange(1,nphonon+1))
for i in range(nsite):
maska = (strsa & (1<<i)) > 0
maskb = (strsb & (1<<i)) > 0
e_part = numpy.zeros((na,nb))
e_part[maska,:] += 1
e_part[:,maskb] += 1
e_part[:] -= float(neleca+nelecb) / nsite
for ip in range(nphonon):
slices1 = slices_for_cre(i, nsite, ip)
slices0 = slices_for (i, nsite, ip)
fcinew[slices1] += numpy.einsum('ij...,ij...->ij...', g*phonon_cre[ip]*e_part, ci0[slices0])
fcinew[slices0] += numpy.einsum('ij...,ij...->ij...', g*phonon_cre[ip]*e_part, ci0[slices1])
return fcinew.reshape(fcivec.shape)
0
Example 44
def make_hdiag(h1e, eri, norb, nelec):
'''Diagonal Hamiltonian for Davidson preconditioner
'''
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
h1e = numpy.ascontiguousarray(h1e)
eri = pyscf.ao2mo.restore(1, eri, norb)
link_indexa = cistring.gen_linkstr_index(range(norb), neleca)
link_indexb = cistring.gen_linkstr_index(range(norb), nelecb)
na = link_indexa.shape[0]
nb = link_indexb.shape[0]
occslista = numpy.asarray(link_indexa[:,:neleca,0], order='C')
occslistb = numpy.asarray(link_indexb[:,:nelecb,0], order='C')
hdiag = numpy.empty(na*nb)
jdiag = numpy.asarray(numpy.einsum('iijj->ij',eri), order='C')
kdiag = numpy.asarray(numpy.einsum('ijji->ij',eri), order='C')
libfci.FCImake_hdiag_uhf(hdiag.ctypes.data_as(ctypes.c_void_p),
h1e.ctypes.data_as(ctypes.c_void_p),
h1e.ctypes.data_as(ctypes.c_void_p),
jdiag.ctypes.data_as(ctypes.c_void_p),
jdiag.ctypes.data_as(ctypes.c_void_p),
jdiag.ctypes.data_as(ctypes.c_void_p),
kdiag.ctypes.data_as(ctypes.c_void_p),
kdiag.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb),
ctypes.c_int(na), ctypes.c_int(nb),
ctypes.c_int(neleca), ctypes.c_int(nelecb),
occslista.ctypes.data_as(ctypes.c_void_p),
occslistb.ctypes.data_as(ctypes.c_void_p))
return numpy.asarray(hdiag)
0
Example 45
Project: pyscf Source File: addons.py
def fix_spin_(fciobj, shift=.2, ss_value=None):
r'''If FCI solver cannot stick on spin eigenfunction, modify the solver by
adding a shift on spin square operator
.. math::
(H + shift*S^2) |\Psi\rangle = E |\Psi\rangle
Args:
fciobj : An instance of :class:`FCISolver`
Kwargs:
shift : float
Level shift for states which have different spin
ss_value : number
S^2 expection value == s*(s+1)
Returns
A modified FCI object based on fciobj.
'''
from pyscf.fci import spin_op
from pyscf.fci import direct_spin0
fciobj.davidson_only = True
def contract_2e(eri, fcivec, norb, nelec, link_index=None, **kwargs):
if isinstance(nelec, (int, numpy.number)):
sz = (nelec % 2) * .5
else:
sz = abs(nelec[0]-nelec[1]) * .5
if ss_value is None:
ss = sz*(sz+1)
else:
ss = ss_value
ci0 = old_contract_2e(eri, fcivec, norb, nelec, link_index, **kwargs)
if ss == 0:
na = int(numpy.sqrt(fcivec.size))
ci0 = pyscf.lib.transpose_sum(ci0.reshape(na,na), inplace=True)
ci0 *= .5
if ss < sz*(sz+1)+.1:
# (S^2-ss_value)|Psi> to shift state other than the lowest state
ci1 = spin_op.contract_ss(fcivec, norb, nelec).reshape(fcivec.shape)
ci1 -= ss * fcivec
else:
# (S^2-ss_value)^2|Psi> to shift states except the given spin.
# It still relies on the quality of initial guess
tmp = spin_op.contract_ss(fcivec, norb, nelec).reshape(fcivec.shape)
tmp -= ss * fcivec
ci1 = -ss * tmp
ci1 += spin_op.contract_ss(tmp, norb, nelec).reshape(fcivec.shape)
tmp = None
ci1 *= shift
ci1 += ci0.reshape(fcivec.shape)
return ci1
fciobj.contract_2e, old_contract_2e = contract_2e, fciobj.contract_2e
return fciobj
0
Example 46
def make_rdm1e(fcivec, nsite, nelec):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
link_indexa = cistring.gen_linkstr_index(range(nsite), neleca)
link_indexb = cistring.gen_linkstr_index(range(nsite), nelecb)
na = cistring.num_strings(nsite, neleca)
nb = cistring.num_strings(nsite, nelecb)
rdm1 = numpy.zeros((nsite,nsite))
ci0 = fcivec.reshape(na,-1)
for str0, tab in enumerate(link_indexa):
for a, i, str1, sign in tab:
rdm1[a,i] += sign * numpy.dot(ci0[str1],ci0[str0])
ci0 = fcivec.reshape(na,nb,-1)
for str0, tab in enumerate(link_indexb):
for a, i, str1, sign in tab:
rdm1[a,i] += sign * numpy.einsum('ax,ax->', ci0[:,str1],ci0[:,str0])
return rdm1
0
Example 47
def pspace(h1e, eri, norb, nelec, hdiag, np=400):
'''pspace Hamiltonian to improve Davidson preconditioner. See, CPL, 169, 463
'''
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
h1e = numpy.ascontiguousarray(h1e)
eri = pyscf.ao2mo.restore(1, eri, norb)
nb = cistring.num_strings(norb, nelecb)
if hdiag.size < np:
addr = numpy.arange(hdiag.size)
else:
try:
addr = numpy.argpartition(hdiag, np-1)[:np]
except AttributeError:
addr = numpy.argsort(hdiag)[:np]
addra, addrb = divmod(addr, nb)
stra = numpy.array([cistring.addr2str(norb,neleca,ia) for ia in addra],
dtype=numpy.uint64)
strb = numpy.array([cistring.addr2str(norb,nelecb,ib) for ib in addrb],
dtype=numpy.uint64)
np = len(addr)
h0 = numpy.zeros((np,np))
libfci.FCIpspace_h0tril(h0.ctypes.data_as(ctypes.c_void_p),
h1e.ctypes.data_as(ctypes.c_void_p),
eri.ctypes.data_as(ctypes.c_void_p),
stra.ctypes.data_as(ctypes.c_void_p),
strb.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(norb), ctypes.c_int(np))
for i in range(np):
h0[i,i] = hdiag[addr[i]]
h0 = pyscf.lib.hermi_triu(h0)
return addr, h0
0
Example 48
def shared(value, name=None, strict=False, allow_downcast=None):
"""
SharedVariable constructor for scalar values. Default: int64 or float64.
Notes
-----
We implement this using 0-d tensors for now.
"""
if not isinstance(value, (numpy.number, float, int, complex)):
raise TypeError()
try:
dtype = value.dtype
except AttributeError:
dtype = numpy.asarray(value).dtype
dtype = str(dtype)
value = getattr(numpy, dtype)(value)
scalar_type = Scalar(dtype=dtype)
rval = ScalarSharedVariable(
type=scalar_type,
value=value,
name=name,
strict=strict,
allow_downcast=allow_downcast)
return rval
0
Example 49
Project: pyscf Source File: direct_ep.py
def make_rdm12e(fcivec, nsite, nelec):
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
link_indexa = cistring.gen_linkstr_index(range(nsite), neleca)
link_indexb = cistring.gen_linkstr_index(range(nsite), nelecb)
na = cistring.num_strings(nsite, neleca)
nb = cistring.num_strings(nsite, nelecb)
ci0 = fcivec.reshape(na,nb,-1)
rdm1 = numpy.zeros((nsite,nsite))
rdm2 = numpy.zeros((nsite,nsite,nsite,nsite))
for str0 in range(na):
t1 = numpy.zeros((nsite,nsite,nb)+ci0.shape[2:])
for a, i, str1, sign in link_indexa[str0]:
t1[i,a,:] += sign * ci0[str1,:]
for k, tab in enumerate(link_indexb):
for a, i, str1, sign in tab:
t1[i,a,k] += sign * ci0[str0,str1]
rdm1 += numpy.einsum('mp,ijmp->ij', ci0[str0], t1)
# i^+ j|0> => <0|j^+ i, so swap i and j
#:rdm2 += numpy.einsum('ijmp,klmp->jikl', t1, t1)
tmp = lib.dot(t1.reshape(nsite**2,-1), t1.reshape(nsite**2,-1).T)
rdm2 += tmp.reshape((nsite,)*4).transpose(1,0,2,3)
rdm1, rdm2 = pyscf.fci.rdm.reorder_rdm(rdm1, rdm2, True)
return rdm1, rdm2
0
Example 50
def get_init_guess(norb, nelec, nroots, hdiag):
'''Initial guess is the single Slater determinant
'''
if isinstance(nelec, (int, numpy.number)):
nelecb = nelec//2
neleca = nelec - nelecb
else:
neleca, nelecb = nelec
na = cistring.num_strings(norb, neleca)
nb = cistring.num_strings(norb, nelecb)
# The "nroots" lowest determinats based on energy expectation value.
ci0 = []
try:
addrs = numpy.argpartition(hdiag, nroots-1)[:nroots]
except AttributeError:
addrs = numpy.argsort(hdiag)[:nroots]
for addr in addrs:
x = numpy.zeros((na*nb))
x[addr] = 1
ci0.append(x.ravel())
# Add noise
ci0[0][0 ] += 1e-5
ci0[0][-1] -= 1e-5
return ci0