示例#1
0
def add_zeeman(h,zeeman=[0.0,0.0,0.0]):
  """ Add Zeeman to the hamiltonian """
  from scipy.sparse import coo_matrix as coo
  from scipy.sparse import bmat
  if h.has_spin: # only if the system has spin
    sx = coo([[0.0,1.0],[1.0,0.0]])   # sigma x
    sy = coo([[0.0,-1j],[1j,0.0]])   # sigma y
    sz = coo([[1.0,0.0],[0.0,-1.0]])   # sigma z
    no = h.num_orbitals # number of orbitals (without spin)
    # create matrix to add to the hamiltonian
    bzee = [[None for i in range(no)] for j in range(no)]
    # assign diagonal terms
    if not callable(zeeman): # if it is a number
      for i in range(no):
        bzee[i][i] = zeeman[0]*sx+zeeman[1]*sy+zeeman[2]*sz
    elif callable(zeeman): # if it is a function
      x = h.geometry.x  # x position
      y = h.geometry.y  # y position
      for i in range(no):
        z = zeeman(x[i],y[i])  # get the value of the zeeman
        bzee[i][i] = z[0]*sx+z[1]*sy+z[2]*sz
    else:
      raise
    bzee = bmat(bzee) # create matrix
    if h.has_eh: # if electron hole, double the dimension
      bzee = bmat([[bzee,None],[None,-bzee]])
    bzee = bzee.todense() # create dense matrix
    h.intra = h.intra + bzee
  if not h.has_spin:  # still have to implement this...
    raise
示例#2
0
	def kron(self, B):
		fp = self.fparity	# def fp just for convenience
		ss = self.sym_sum	# def ss just for convenience

		if self.sym!=B.sym:
			raise Exception('A, B symmetries do not match.')
		sym = B.sym
		dim = sym * self.dim * B.dim
		if not np.array_equal(self.fparity, B.fparity):
			raise Exception('A, B fermion types do not match.')
		datatype = self.datatype
		if np.dtype(datatype) < np.dtype(B.datatype): datatype = B.datatype

		ret = quantum_operator(sym, dim, datatype, fp, ss)
		for row in range(sym):
			for col in range(sym):
				for row1 in range(sym):
					for col1 in range(sym):
						row2 = ss(row, -row1)
						col2 = ss(col, -col1)
						if not self._empty_(row1, col1) and not B._empty_(row2, col2):
							sign = 1 - 2*( fp[col1] * fp[ss(col2, -row2)] )
							block = self.dim * B.dim
							temp = coo( skron(self.val[row1][col1], B.val[row2][col2]) * sign )
							add = coo((temp.data, (temp.row + row1*block, temp.col + col1*block)), (dim, dim), dtype=datatype)
							ret.val[row][col] += add
		return ret
示例#3
0
def print_hamiltonian(h):
  """ Print the hamilotnian on screen """
  from scipy.sparse import coo_matrix as coo # import sparse matrix
  intra = coo(h.intra) # intracell
  inter = coo(h.inter) # intracell
  print "Intracell matrix"
  print intra
  print "Intercell matrix"
  print inter
  return
示例#4
0
def print_hamiltonian(h):
    """ Print the hamilotnian on screen """
    from scipy.sparse import coo_matrix as coo  # import sparse matrix
    intra = coo(h.intra)  # intracell
    inter = coo(h.inter)  # intracell
    print("Intracell matrix")
    print(intra)
    print("Intercell matrix")
    print(inter)
    return
示例#5
0
def add_swave(intra,delta=0.0,mu=0.0,phi=0.0):
  """ Adds swave pairing """
  intra_sc = 0.0*intra  # intracell pairing potential
  from scipy.sparse import coo_matrix as coo
  from scipy.sparse import bmat
  # intracell contribution
  deltac = delta*np.exp(1j*phi*np.pi) # complex SC order parameter
  for i in range(len(intra)/2): # loop over intracell pairs
    intra_sc[2*i,2*i+1] = deltac    # up down electron hole
    intra_sc[2*i+1,2*i] = -deltac    # down up
  intra_eh = nambu(coo(intra),coupling=coo(intra_sc))
  return intra_eh
def test_isotope_images_are_stored(search_results, spark_context):
    mask = np.array([[1, 1], [1, 0]])
    IMG_ID = "iso_image_id"
    img_store_mock = MagicMock(spec=ImageStoreServiceWrapper)
    img_store_mock.post_image.return_value = IMG_ID

    img_store_mock.reset_mock()
    ion_iso_images = spark_context.parallelize([
        (0, [ coo([[0, 0], [0, 1]]), None, coo([[2, 3], [1, 0]]), None ]),
        (1, [ coo([[1, 1], [0, 1]]), None, None, None])
    ])
    ids = search_results.post_images_to_image_store(ion_iso_images, mask, img_store_mock, 'fs')
    assert ids == { 0: {'iso_image_ids': [IMG_ID, None, IMG_ID, None]}, 1: {'iso_image_ids': [IMG_ID, None, None, None]} }
    assert img_store_mock.post_image.call_count == 3
示例#7
0
文件: ising.py 项目: baoqt2/pyGMs
 def __init__(self, factorList=None, copy=True, isLog=False):
   """Take in a list of factors and convert & store them in the internal format
     Can also accept a matrix of Ising parameters
   """
   if factorList is None:
     self.h = np.zeros(0); self.L=csr((0,0)); return;
   if not isinstance(factorList[0], Factor): # not a factor list => matrix?
     L = coo(factorList)
     LL = csr(factorList)
     n = L.shape[0]
     self.h = np.array([LL[i,i] for i in range(n)]);    # extract diagonal
     self.dims = np.array([2 for i in range(n)], dtype=int);   # all variables binary
     keep = (L.row != L.col)
     data,row,col = L.data[keep],L.row[keep],L.col[keep]
     #for j in np.where(L.row > L.col): row[j],col[j] = col[j],row[j]
     self.L = csr((data,(row,col)),shape=(n,n))   # keep in csr format
     self.L = .5*(self.L+self.L.T)  # force symmetric if not (TODO: detect zeros & overwrite?)
   else:
     n = np.max([np.max(f.vars.labels) for f in factorList if len(f.vars)])+1
     assert np.max([np.max(f.vars.dims()) for f in factorList]) <= 2, "Variables must be binary"
     assert np.max([f.nvar for f in factorList]) <= 2, "Factors must be pairwise"
     self.dims = np.zeros((n,), dtype=int)
     for f in factorList:
       for v in f.vars: self.dims[v] = v.states
     self.h = np.zeros(n);
     self.L = csr(([],([],[])),shape=(n,n));
     self.addFactors(factorList, isLog=isLog)
示例#8
0
 def spm(m):
     """Non vanishing elements"""
     from scipy.sparse import coo_matrix as coo
     mc = coo(m)  # to coo_matrixi
     data = mc.data  # get data
     col = mc.col  # get column index
     row = mc.row  # get row index
     return (row, col, data.real, data.imag)  # return things to print
示例#9
0
文件: 4e.py 项目: clover199/pyLIB
	def kron_s(A, B, sec):
		fp = A.fparity
		ss = A.sym_sum
		sym = A.sym
		dim = sym * A.dim * B.dim
		ret = csr((dim, dim), dtype=np.complex)
		for row1 in range(sym):
			for col1 in range(sym):
				row2 = ss(sec, -row1)
				col2 = ss(sec, -col1)
				if not A._empty_(row1, col1) and not B._empty_(row2, col2):
					sign = 1 - 2*( fp[col1] * fp[ss(col2, -row2)] )
					temp = coo( sparse.kron(A.val[row1][col1], B.val[row2][col2]) * sign )
					block = A.dim * B.dim
					add = coo((temp.data, (temp.row + row1*block, temp.col + col1*block)),(dim, dim), dtype=np.complex)
					ret += add
		return ret
示例#10
0
文件: ising.py 项目: baoqt2/pyGMs
 def factors(self):
   """Return a list of factors (converted to full tables)"""
   X = [Var(i,2) for i in range(self.nvar)]
   factors = [Factor([],np.exp(self.c))] 
   # TODO: exclude if zero? or exclude if inf/-inf, or if in "assigned", or?
   factors = factors + [Factor([X[i]],[-th,th]).exp() for i,th in enumerate(self.h) if self.dims[i]>1]
   L = coo(self.L)
   factors = factors + [Factor([X[i],X[j]],[[th,-th],[-th,th]]).exp() for i,j,th in zip(L.row,L.col,L.data) if i<j]
   return factors
def single_chrom_ABC(pregs, prna, eregs, ek27ac, llinks, contact_path, binsize,
                     normalisation, gamma, distance_thresh, chrom):

    print("loading contact data, chromosome {}".format(chrom))
    contacts = straw_extract_chr_matrix(contact_path,
                                        chrom,
                                        binsize=binsize,
                                        normalisation=normalisation)

    prom_bins = np.mean(pregs[chrom], axis=1).astype('int')
    enh_bins = np.mean(eregs[chrom], axis=1).astype('int')

    ep_dists = abs(prom_bins[:, None] - enh_bins[None, :])
    distance_mask = ep_dists < distance_thresh
    prom_bins = (prom_bins / binsize).astype('int')
    enh_bins = (enh_bins / binsize).astype('int')

    enh_act = ek27ac[chrom]

    if contact_path is not None:
        clipped_contacts, logs = clip_contacts(prom_bins, enh_bins, contacts,
                                               gamma, chrom)
        print("Clipped contact data for chromosome {}".format(chrom))
    else:
        clipped_contacts, logs = theoretical_contact_strengths(
            prom_bins, enh_bins, gamma, chrom)
        print("Using theoretical contact strengths for chromosome {}".format(
            chrom))

    ABC_scores = np.multiply(
        llinks[chrom].todense(),
        np.repeat(enh_act[None, :], prom_bins.shape[0], axis=0))
    ABC_scores = np.multiply(ABC_scores, clipped_contacts)
    ABC_scores[~prna[chrom], :] = 0
    ABC_scores[distance_mask] = 0

    ABC_score_sums = np.array(np.sum(ABC_scores, axis=1))[:, 0]
    if np.sum(ABC_score_sums) > 0:
        ABC_score_sums[ABC_score_sums == 0] = np.percentile(
            ABC_score_sums[ABC_score_sums > 0], 1)

        ABC_scores[ABC_score_sums > 0, :] = np.divide(
            ABC_scores[ABC_score_sums > 0, :],
            np.repeat(ABC_score_sums[ABC_score_sums > 0, None],
                      ABC_scores.shape[1],
                      axis=1))

        ABC_scores = coo(ABC_scores)

        print("Got scores for chromosome {}".format(chrom))
        return ABC_scores.data, np.append(ABC_scores.row[:, None],
                                          ABC_scores.col[:, None],
                                          axis=1), chrom, logs
    else:
        return np.zeros(1), np.append(np.zeros(1)[:, None],
                                      np.zeros(1)[:, None],
                                      axis=1), chrom, logs
示例#12
0
def write_mean_field(m,output_file="mean_field.in"):
  """Reads the file input_file and returns a traceless matrix"""
  f = open(output_file,"w") # open file
  mf = coo(m) # sparse matrix
  f.write("# number of non vanishing elements\n"+str(len(mf.col))+"\n")
  f.write("# i   j     real      imaginary\n")
  for (i,j,d) in zip(mf.row,mf.col,mf.data):
    f.write(str(i+1)+"    "+str(j+1)+"   "+str(d.real)+"   "+str(d.imag)+"\n")
  f.close() # close file
示例#13
0
    def spm(m):
        """Non vanishing elements"""
        from scipy.sparse import coo_matrix as coo

        mc = coo(m)  # to coo_matrixi
        data = mc.data  # get data
        col = mc.col  # get column index
        row = mc.row  # get row index
        return (row, col, data.real, data.imag)  # return things to print
示例#14
0
def write_mean_field(m, output_file="mean_field.in"):
    """Reads the file input_file and returns a traceless matrix"""
    f = open(output_file, "w")  # open file
    mf = coo(m)  # sparse matrix
    f.write("# number of non vanishing elements\n" + str(len(mf.col)) + "\n")
    f.write("# i   j     real      imaginary\n")
    for (i, j, d) in zip(mf.row, mf.col, mf.data):
        f.write(
            str(i + 1) + "    " + str(j + 1) + "   " + str(d.real) + "   " +
            str(d.imag) + "\n")
    f.close()  # close file
示例#15
0
def add_zeeman(h,zeeman=[0.0,0.0,0.0]):
  """ Add Zeeman to the hamiltonian """
  # convert the input into a list
  def convert(z):
    try: # try to get the first element
      a = z[0]
    except: # convert to list
      z = [0.,0.,z]
    return z
  from scipy.sparse import coo_matrix as coo
  from scipy.sparse import bmat
  if h.has_spin: # only if the system has spin
    sx = coo([[0.0,1.0],[1.0,0.0]])   # sigma x
    sy = coo([[0.0,-1j],[1j,0.0]])   # sigma y
    sz = coo([[1.0,0.0],[0.0,-1.0]])   # sigma z
   # no = h.num_orbitals # number of orbitals (without spin)
    no = h.intra.shape[0]//2 # number of orbitals (without spin)
    # create matrix to add to the hamiltonian
    bzee = [[None for i in range(no)] for j in range(no)]
    # assign diagonal terms
    if not callable(zeeman): # if it is a number
      for i in range(no):
        zeeman = convert(zeeman) # convert to list
        bzee[i][i] = zeeman[0]*sx+zeeman[1]*sy+zeeman[2]*sz
    elif callable(zeeman): # if it is a function
      x = h.geometry.x  # x position
      y = h.geometry.y  # y position
      z = h.geometry.z  # z position
      for i in range(no):
        mm = zeeman(x[i],y[i],z[i])  # get the value of the zeeman
        mm = convert(mm) # convert to list
        bzee[i][i] = mm[0]*sx+mm[1]*sy+mm[2]*sz
    else:
      raise
    bzee = bmat(bzee) # create matrix
    if h.has_eh: # if electron hole, double the dimension
      bzee = bmat([[bzee,None],[None,-bzee]])
    if not h.is_sparse: bzee = bzee.todense() # create dense matrix
    h.intra = h.intra + bzee
  if not h.has_spin:  # still have to implement this...
    raise
示例#16
0
def nv_el(m):
  """ get the non vanishing elments of a matrix"""
  from scipy.sparse import coo_matrix as coo
  mc = coo(m) # to coo_matrixi
  data = mc.data # get data
  col = mc.col # get column index
  row = mc.row # get row index
  nv = []
  nt=len(data)
  for i in range(nt):
   # save the nonvanishing values
   nv.append([row[i]+1,col[i]+1,data[i].real,data[i].imag])
  return nv
示例#17
0
def nv_el(m):
  """ get the non vanishing elments of a matrix"""
  from scipy.sparse import coo_matrix as coo
  mc = coo(m) # to coo_matrixi
  data = mc.data # get data
  col = mc.col # get column index
  row = mc.row # get row index
  nv = []
  nt=len(data)
  for i in range(nt):
   # save the nonvanishing values
   nv.append([row[i]+1,col[i]+1,data[i].real,data[i].imag])
  return nv
def test_isotope_images_are_stored(search_results, spark_context):
    mask = np.array([[1, 1], [1, 0]])
    IMG_ID = "iso_image_id"
    img_store_mock = MagicMock(spec=ImageStoreServiceWrapper)
    img_store_mock.post_image.return_value = IMG_ID

    img_store_mock.reset_mock()
    ion_iso_images = spark_context.parallelize([
        (0, [coo([[0, 0], [0, 1]]), None,
             coo([[2, 3], [1, 0]]), None]),
        (1, [coo([[1, 1], [0, 1]]), None, None, None])
    ])
    ids = search_results.post_images_to_image_store(ion_iso_images, mask,
                                                    img_store_mock, 'fs')
    assert ids == {
        0: {
            'iso_image_ids': [IMG_ID, None, IMG_ID, None]
        },
        1: {
            'iso_image_ids': [IMG_ID, None, None, None]
        }
    }
    assert img_store_mock.post_image.call_count == 3
示例#19
0
 def kron_s(A, B, sec):
     fp = A.fparity
     ss = A.sym_sum
     sym = A.sym
     dim = sym * A.dim * B.dim
     ret = csr((dim, dim), dtype=np.complex)
     for row1 in range(sym):
         for col1 in range(sym):
             row2 = ss(sec, -row1)
             col2 = ss(sec, -col1)
             if not A._empty_(row1, col1) and not B._empty_(row2, col2):
                 sign = 1 - 2 * (fp[col1] * fp[ss(col2, -row2)])
                 temp = coo(
                     sparse.kron(A.val[row1][col1], B.val[row2][col2]) *
                     sign)
                 block = A.dim * B.dim
                 add = coo(
                     (temp.data,
                      (temp.row + row1 * block, temp.col + col1 * block)),
                     (dim, dim),
                     dtype=np.complex)
                 ret += add
     return ret
示例#20
0
def add_pwave_electron_hole_pairing(h,delta=0.0,mu=0.0,phi=0.0):
  """ Adds an pwave (spin conserving) electron-hole pairing
   potential to first neighbors,
   delta is pairing potential
   mu is chemical potential
   phi is superconducting phase"""
  h.has_eh = True # has electron hole pairs
  intra = h.intra  # intra cell potential
  intra_sc = 0.0*intra  # intracell pairing potential
  x = h.geometry.x # x position
  y = h.geometry.y # y position
  from scipy.sparse import coo_matrix as coo
  from scipy.sparse import bmat
  deltac = delta*np.exp(1j*phi*np.pi) # complex SC order parameter
  # intracell contribution
  pairs = find_first_neighbor(x,y,x,y) # get intra pairs of first neighbors
  for p in pairs: # loop over intracell pairs
 # geometric phase, dependent on bonding orientation
    gp = np.arctan2(x[p[0]]-x[p[1]],y[p[0]]-y[p[1]]) 
    gp = np.exp(1j*gp)  # get complex phase
    intra_sc[2*p[0],2*p[1]] = deltac*gp    # up up, times phase
    intra_sc[2*p[0]+1,2*p[1]+1] = deltac*gp  # down down, times phase
  # intracell eh matrix
  intra_eh = [[coo(intra),coo(intra_sc-intra_sc.H)],
                   [coo(intra_sc.H-intra_sc),-coo(intra)]]
  intra_eh = bmat(intra_eh).todense()
  if h.dimensionality == 0:   # if 0 dimensional return
    return (intra_eh,None)
  # intercell contribution
  if h.dimensionality == 1: # if one dimensional calculate neighbor contribution
    celldis = h.geometry.celldis # distance to neighboring cell
    inter = h.inter  # inter cell potential
    inter_sc = 0.0*inter  # intercell pairing potential
    pairs = find_first_neighbor(x,y,x+celldis,y) # get inter pairs of first neighbors
    for p in pairs: # loop over intercell pairs
      gp = np.arctan2(x[p[0]]-x[p[1]-celldis],y[p[0]]-y[p[1]]) 
      gp = np.exp(1j*gp)  # get complex phase
      inter_sc[2*p[0],2*p[1]] = deltac*gp   # up up, times phase
      inter_sc[2*p[0]+1,2*p[1]+1] = deltac*gp  # down down, times phase
    # intercell eh matrix
    inter_eh = [[coo(inter),coo(inter_sc)],[-coo(inter_sc.H),-coo(inter)]]
    inter_eh = bmat(inter_eh).todense()
    return (intra_eh,inter_eh)
def straw_extract_chr_matrix(hic_file,
                             chrom,
                             binsize = 5000,
                             normalisation = 'KR',
                             trim = False
                            ):
    result = straw.straw(normalisation,hic_file,str(chrom), str(chrom),'BP',binsize)
    
    data = np.array(result[2] + result[2])
    goodidxs = ~np.isnan(data)

    if np.sum(goodidxs) == 0:
        print("Unable to get good data (no valid contact pairs) for requested normalisation on chromosome {}, using SQRT_VC instead".format(chrom))
        result = straw.straw('VC_SQRT',hic_file,str(chrom), str(chrom),'BP',binsize)
        data = np.array(result[2] + result[2])
        goodidxs = ~np.isnan(data)
        print("\t{} pairs covered with SQRT_VC normalisation".format(np.sum(goodidxs)))
        
    row  = np.array(result[0] + result[1])
    row = row[goodidxs]
    rowmin = np.min(row)
    rowmax = np.max(row)

    if trim:
        row = (row - rowmin)/binsize
    else:
        row = row/binsize
    row = row.astype('int32')

    col  = np.array(result[1] + result[0])
    col = col[goodidxs]
    if trim:
        col = (col - rowmin)/binsize
    else:
        col = col/binsize 
        
    col = col.astype('int32')

    mycoo = coo((data[goodidxs], (row, col)), shape=(np.max(row)+1, np.max(row)+1))
    
    return mycoo
示例#22
0
文件: 4e.py 项目: clover199/pyLIB
def FK(L=8, sec=0, t1=1., t2=1.0, f0=1., f1=1., pbc=False):
	''' see the paper for Hamiltonian
		hopping t: i c^d c
		f0: -(2n-1)(2n-1)
		f1: -4(n+n-1)(n+n-1) + 8(cccc+h.c.) '''
	if L not in [1,2,4,8]:
		raise Exception("Illegal L value")
	print "\n--> Construct the Hamiltonian for the FK model of size L=%d ..." % (L)

	n_up = op.fermion_up4().hermitian().mult( op.fermion_up4() )
	n_down = op.fermion_down4().hermitian().mult( op.fermion_down4() )
	pp = op.fermion_up4().mult( op.fermion_down4() )	# cc
	ide = n_up.identity()
	n2_up = n_up.copy().times(-2).plus( ide )		# 1-2n
	n2_down = n_down.copy().times(-2).plus( ide )	# 1-2n
	nn = n2_up.copy().plus(n2_down)		# 2(1-n-n)
	mH = n2_up.mult( n2_down ).times(-f0/2.)
	if L==1:
		H = mH.hermitian().plus(mH)
	 	H.L = 1
	 	H.basis = op.basis(4)
		return H

	# the 2-stie ham with the hopping t1 and onsite-interaction f0
	H2 = op.fermion_up4().hermitian().kron( op.fermion_up4() )
	H2.plus( op.fermion_down4().hermitian().kron( op.fermion_down4() ) )
	H2.times( 2.j*float(t1) )
	H2.plus( mH.kron(ide).plus( ide.kron(mH) ) )
	if L==2:
		H = H2.hermitian().plus(H2)
	 	H.L = 1
	 	H.basis = op.basis(4)
		return H

	# the 4 site ham with interaction f1 and hopping t2
	H4 = ham.operator(4, [op.fermion_up4().hermitian(), op.fermion_up4()], [1,3])
	H4.plus( ham.operator(4, [op.fermion_down4().hermitian(), op.fermion_down4()], [1,3]) )
	H4.times( 2.j*float(t2) )
	ide = H2.identity()
	H4.plus( H2.kron(ide).plus( ide.kron(H2) ) )
	H4.plus( ham.operator(4, [nn, nn], [1,2]).times(-f1/2.) )
	H4.plus( ham.operator(4, [pp, pp], [1,2]).times(f1*8.) )

	if L==4:
		H = H4.hermitian().plus(H4)
	 	H.L = 1
	 	H.basis = op.basis(4)
		return H

	def kron_s(A, B, sec):
		fp = A.fparity
		ss = A.sym_sum
		sym = A.sym
		dim = sym * A.dim * B.dim
		ret = csr((dim, dim), dtype=np.complex)
		for row1 in range(sym):
			for col1 in range(sym):
				row2 = ss(sec, -row1)
				col2 = ss(sec, -col1)
				if not A._empty_(row1, col1) and not B._empty_(row2, col2):
					sign = 1 - 2*( fp[col1] * fp[ss(col2, -row2)] )
					temp = coo( sparse.kron(A.val[row1][col1], B.val[row2][col2]) * sign )
					block = A.dim * B.dim
					add = coo((temp.data, (temp.row + row1*block, temp.col + col1*block)),(dim, dim), dtype=np.complex)
					ret += add
		return ret

	# the 8 site ham
	lup = ham.operator(4, [op.fermion_up4().hermitian()], [2])
	rup = ham.operator(4, [op.fermion_up4()], [0])
	ldown = ham.operator(4, [op.fermion_down4().hermitian()], [2])
	rdown = ham.operator(4, [op.fermion_down4()], [0])
	ide = H4.identity()
	ln = ham.operator(4, [nn], [3])
	rn = ham.operator(4, [nn], [0])
	lp = ham.operator(4, [pp], [3])
	rp = ham.operator(4, [pp], [0])

	Hs = coo((16384, 16384), dtype=np.complex)
	Hs += kron_s(lup, rup, sec)
	Hs += kron_s(ldown, rdown, sec)
	Hs *= 2.j*float(t2)
	Hs += kron_s(H4, ide, sec)
	Hs += kron_s(ide, H4, sec)
	Hs += kron_s(ln, rn, sec)*(-f1/2.)
	Hs += kron_s(lp, rp, sec)*(f1*8.)

	if pbc:
		edge = kron_s(rup,lup, sec)
		edge += kron_s(rdown, ldown, sec)
		edge *= -2.j*float(t2)
		Hs += edge
		Hs += kron_s(rn, ln, sec)*(-f1/2.)
		Hs += kron_s(rp, lp, sec)*(f1*8.)

	Hs += Hs.conjugate().transpose()
	print "--> Hamiltonian constructed."
	return Hs
示例#23
0
def FK(L=8, sec=0, t1=1., t2=1.0, f0=1., f1=1., pbc=False):
    ''' see the paper for Hamiltonian
		hopping t: i c^d c
		f0: -(2n-1)(2n-1)
		f1: -4(n+n-1)(n+n-1) + 8(cccc+h.c.) '''
    if L not in [1, 2, 4, 8]:
        raise Exception("Illegal L value")
    print "\n--> Construct the Hamiltonian for the FK model of size L=%d ..." % (
        L)

    n_up = op.fermion_up4().hermitian().mult(op.fermion_up4())
    n_down = op.fermion_down4().hermitian().mult(op.fermion_down4())
    pp = op.fermion_up4().mult(op.fermion_down4())  # cc
    ide = n_up.identity()
    n2_up = n_up.copy().times(-2).plus(ide)  # 1-2n
    n2_down = n_down.copy().times(-2).plus(ide)  # 1-2n
    nn = n2_up.copy().plus(n2_down)  # 2(1-n-n)
    mH = n2_up.mult(n2_down).times(-f0 / 2.)
    if L == 1:
        H = mH.hermitian().plus(mH)
        H.L = 1
        H.basis = op.basis(4)
        return H

    # the 2-stie ham with the hopping t1 and onsite-interaction f0
    H2 = op.fermion_up4().hermitian().kron(op.fermion_up4())
    H2.plus(op.fermion_down4().hermitian().kron(op.fermion_down4()))
    H2.times(2.j * float(t1))
    H2.plus(mH.kron(ide).plus(ide.kron(mH)))
    if L == 2:
        H = H2.hermitian().plus(H2)
        H.L = 1
        H.basis = op.basis(4)
        return H

    # the 4 site ham with interaction f1 and hopping t2
    H4 = ham.operator(4, [op.fermion_up4().hermitian(),
                          op.fermion_up4()], [1, 3])
    H4.plus(
        ham.operator(4, [op.fermion_down4().hermitian(),
                         op.fermion_down4()], [1, 3]))
    H4.times(2.j * float(t2))
    ide = H2.identity()
    H4.plus(H2.kron(ide).plus(ide.kron(H2)))
    H4.plus(ham.operator(4, [nn, nn], [1, 2]).times(-f1 / 2.))
    H4.plus(ham.operator(4, [pp, pp], [1, 2]).times(f1 * 8.))

    if L == 4:
        H = H4.hermitian().plus(H4)
        H.L = 1
        H.basis = op.basis(4)
        return H

    def kron_s(A, B, sec):
        fp = A.fparity
        ss = A.sym_sum
        sym = A.sym
        dim = sym * A.dim * B.dim
        ret = csr((dim, dim), dtype=np.complex)
        for row1 in range(sym):
            for col1 in range(sym):
                row2 = ss(sec, -row1)
                col2 = ss(sec, -col1)
                if not A._empty_(row1, col1) and not B._empty_(row2, col2):
                    sign = 1 - 2 * (fp[col1] * fp[ss(col2, -row2)])
                    temp = coo(
                        sparse.kron(A.val[row1][col1], B.val[row2][col2]) *
                        sign)
                    block = A.dim * B.dim
                    add = coo(
                        (temp.data,
                         (temp.row + row1 * block, temp.col + col1 * block)),
                        (dim, dim),
                        dtype=np.complex)
                    ret += add
        return ret

    # the 8 site ham
    lup = ham.operator(4, [op.fermion_up4().hermitian()], [2])
    rup = ham.operator(4, [op.fermion_up4()], [0])
    ldown = ham.operator(4, [op.fermion_down4().hermitian()], [2])
    rdown = ham.operator(4, [op.fermion_down4()], [0])
    ide = H4.identity()
    ln = ham.operator(4, [nn], [3])
    rn = ham.operator(4, [nn], [0])
    lp = ham.operator(4, [pp], [3])
    rp = ham.operator(4, [pp], [0])

    Hs = coo((16384, 16384), dtype=np.complex)
    Hs += kron_s(lup, rup, sec)
    Hs += kron_s(ldown, rdown, sec)
    Hs *= 2.j * float(t2)
    Hs += kron_s(H4, ide, sec)
    Hs += kron_s(ide, H4, sec)
    Hs += kron_s(ln, rn, sec) * (-f1 / 2.)
    Hs += kron_s(lp, rp, sec) * (f1 * 8.)

    if pbc:
        edge = kron_s(rup, lup, sec)
        edge += kron_s(rdown, ldown, sec)
        edge *= -2.j * float(t2)
        Hs += edge
        Hs += kron_s(rn, ln, sec) * (-f1 / 2.)
        Hs += kron_s(rp, lp, sec) * (f1 * 8.)

    Hs += Hs.conjugate().transpose()
    print "--> Hamiltonian constructed."
    return Hs
示例#24
0
def add_swave_electron_hole_pairing(h,delta=0.0,mu=0.0,phi=0.0):
  """ Adds an swave electron-hole pairing
   potential to first neighbors,
   delta is pairing potential
   mu is chemical potential
   phi is superconducting phase,
   delta and phi can be functions!!!!!"""
  h.has_eh = True # has electron hole pairs
  intra = h.intra  # intra cell potential
  intra_sc = 0.0*intra  # intracell pairing potential
  x = h.geometry.x # x position
  y = h.geometry.y # y position
  from scipy.sparse import coo_matrix as coo
  from scipy.sparse import bmat
  # intracell contribution
  pairs = find_first_neighbor(x,y,x,y) # get intra pairs of first neighbors
  for i in range(len(x)): # loop over intracell pairs

    if is_number(delta) and is_number(phi):  # if both are numbers
      deltac = delta*np.exp(1j*phi*np.pi) # complex SC order parameter
    elif callable(delta) and callable(phi): # if both are functions
      deltac = delta(x[i],y[i])*np.exp(1j*phi(x[i],y[i])*np.pi) 
    elif callable(phi) and is_number(delta): # if phi is function
      deltac = delta*np.exp(1j*phi(x[i],y[i])*np.pi) 
    elif callable(delta) and is_number(phi): # if delta is function
      deltac = delta(x[i],y[i])*np.exp(1j*phi*np.pi) 
    else:  # error if unrecognized
      print type(delta),type(phi)  
      raise
    # notation is
        # psi_up
        # psi_dn
        # psi_dn_dag
        # psi_up_dag
    if h.has_spin:
      # couples electron in even orbital with hole in odd orbital
            # in the curren notation even corresponds to up
            # and odd corresponds to down, so this term couples
            # at the same atom, up electrons with down holes
                     # index 0 is first atom up
                     # index 1 is first atom down
      intra_sc[2*i,2*i+1] = deltac    # up down electron hole
      intra_sc[2*i+1,2*i] = -deltac    # down up
  #    intra_sc[2*i,2*i] = deltac    # up down electron hole
  #    intra_sc[2*i+1,2*i+1] = -deltac    # down up
    if not h.has_spin:
      raise
  # intracell eh matrix
#  intra_eh = [[coo(intra),coo(intra_sc)],[coo(intra_sc.H)
#             ,-coo(np.conjugate(intra))]]
#             ,-coo(intra)]]
#             ,-coo(intra.H)]]
#  intra_eh = bmat(intra_eh).todense()
  intra_eh = build_eh(intra,coupling=intra_sc)
  if h.dimensionality == 0:   # if 0 dimensional return
    return (intra_eh,None)
  # intercell contribution
  if h.dimensionality == 1: # if one dimensional calculate neighbor contribution
    inter = h.inter  # inter cell potential
    # intercell eh matrix, no mixing terms
    inter_eh = [[coo(inter),None],[None,-coo(np.conjugate(inter))]]
    inter_eh = bmat(inter_eh).todense()
    inter_eh = build_eh(inter)  # create electron hole matrix
    return (intra_eh,inter_eh)
示例#25
0
def _single_clr_edge_and_node_info_from_sites(c: cooler.Cooler,
                                              sites: Dict[str, np.ndarray],
                                              balance: Optional[bool] = True,
                                              join: Optional[bool] = False):
    '''
    Given some cooler and a dictionary of sites (with chromosomes as keys), return the submatrices retrieved from these slices within the Hi-C map. Submatrices are returned in sparse COO format with an edge_idxs dictionary, an edge_attrs dictionary and a node_info dictionary. Optionally users can balance the Hi-C matrix before retrieval of matrix information. SInce multiple chromosomes and slices per chromosome can be supplied, user may optionally join regions into one larger region consisting of the given slices concatenated together. This function does not actually do the joining procedure since the passed slices may not be disjoint.  
    
    :param cooler: Cooler file object
    :type edge_index: cooler.Cooler
    :param slices: Dictionary with chromosomes as keys and lists of sites as values. Multiple sites are allowed per chromosome.
    :type slices: Dict[str,List[np.ndarray]]
    :param balance: Whether to perform matrix balancing on the Hi-C matrix before retrieving individual slices.
    :type balance: Optional[bool]
    :param join: Boolean determining whether to retrieve Hi-C martrix information corresponding to the interface between slices. This is only recommended if slices are disjoint since the interface isn't well defined if slices aren't disjoint.
    :type join: Optional[bool]
    '''
    # Iterate through slices, adding in edge indexes and edge attributes
    edge_idxs = {}
    edge_attrs = {}
    sub_graph_nodes = {}
    chroms = list(sites.keys())
    for idx, chrom1 in enumerate(chroms):
        edge_idxs[chrom1] = {}
        edge_attrs[chrom1] = {}
        sub_graph_nodes[chrom1] = {}
        for chrom2 in chroms[idx:]:
            if chrom1 != chrom2 and not join:
                continue
            mat = c.matrix(balance=balance).fetch(chrom1, chrom2)
            mat = mat[sites[chrom1], :]
            mat = mat[:, sites[chrom2]]

            mat = coo(mat)

            b1 = c.bins().fetch(chrom1).index.values[sites[chrom1]]
            b2 = c.bins().fetch(chrom2).index.values[sites[chrom2]]

            edge_index = np.concatenate(
                [b1[mat.row][None, :], b2[mat.col][None, :]],
                axis=0,
            )

            edge_data = mat.data[:, None]

            if chrom1 != chrom2:
                edge_index = np.append(edge_index, edge_index[::-1, :], axis=1)
                edge_data = np.append(edge_data, edge_data, axis=0)

                edge_data[np.isnan(edge_data)] = 0

            ind = np.lexsort((edge_index[0, :], edge_index[1, :]))
            edge_index = edge_index[:, ind]
            edge_data = edge_data[ind, :]

            edge_idxs[chrom1][chrom2] = [edge_index]
            edge_attrs[chrom1][chrom2] = [edge_data]

            if chrom1 == chrom2:
                sub_graph_nodes[chrom1][chrom2] = [b1]
            else:
                sub_graph_nodes[chrom1][chrom2] = [np.append(b1, b2)]

    return edge_idxs, edge_attrs, sub_graph_nodes
示例#26
0
def super_normal_super(g,f_sc,f_n,replicas = [1,1,1],phi=0.0,delta=0.1):
  """Creates a junction superconductor-normal-superconductor,
          - g is the geometry of the unit cell of the system
          - f_sc is the function which generates the superconductor
            which takes three arguments, geometry, SC order and phase
          - f_n generates the hamiltonian of the central part,
            result has to have electron-hole dimension
          - replicas are the replicas of the SC-normal_SC of the cell
          - phi is the infinitesimal phase difference
          - delta is the superconducting parameter """
  h_left = f_sc(g,delta=delta,phi=phi) # create hamiltonian of the left part
  h_right = f_sc(g,delta=delta,phi=-phi) # create hamiltonian of the right part
  h_central = f_n(g)  # central part
  from scipy.sparse import coo_matrix as coo
  from scipy.sparse import bmat
  from hamiltonians import hamiltonian
  hj = hamiltonian(g) # create hamiltonian of the junction
  tc = replicas[0] + replicas[1] + replicas[2] # total number of cells
  intra = [[None for i in range(tc)] for j in range(tc)]  # create intracell


  # transfor to coo matrix
  h_left.intra = coo(h_left.intra)
  h_left.inter = coo(h_left.inter)
  h_central.intra = coo(h_central.intra)
  h_central.inter = coo(h_central.inter)
  h_right.intra = coo(h_right.intra)
  h_right.inter = coo(h_right.inter)


  # intracell contributions
  for i in range(replicas[0]): 
    intra[i][i] = h_left.intra # intracell of the left lead
  init = replicas[0] # inital index
  for i in range(replicas[1]): 
    intra[init+i][init+i] = h_central.intra # intracell of the left lead
  init = replicas[0]+replicas[1] # inital index
  for i in range(replicas[2]): 
    intra[init+i][init+i] = h_right.intra # intracell of the left lead

  # intercell contributions
  for i in range(replicas[0]-1): 
    intra[i][i+1] = h_left.inter # intercell of the left lead
    intra[i+1][i] = h_left.inter.H # intercell of the left lead
  init = replicas[0] # inital index
  for i in range(replicas[1]-1): 
    intra[init+i][init+i+1] = h_central.inter # intercell of the central lead
    intra[init+i+1][init+i] = h_central.inter.H # intercell of the central lead
  init = replicas[0]+replicas[1] # inital index
  for i in range(replicas[2]-1): 
    intra[init+i][init+i+1] = h_right.inter # intercell of the right lead
    intra[init+i+1][init+i] = h_right.inter.H # intercell of the right lead

  # coupling between SC and central part, take couapling of the central
  il = replicas[0]
  intra[il-1][il] = h_central.inter # intracell of the left lead
  intra[il][il-1] = h_central.inter.H # intracell of the left lead
  il = replicas[0]+replicas[1]
  intra[il-1][il] = h_central.inter # intracell of the left lead
  intra[il][il-1] = h_central.inter.H # intracell of the left lead
  # create matrix
  intra = bmat(intra).todense()
  hj.intra = intra # add to hamiltonian junction
  hj = hj.finite_system() # convert in finite system
  return hj
示例#27
0
for i in xrange(len(T0)):
    for j in T0[i]:
        T[i][j - 1] = 1.0
print set(R.keys()) & set([1])
print np.random.normal(size=(2, 3))
x = defaultdict(dict)
a = [1, 2, 3, 4]
print a[-4:], a[-2]
row = np.array([0, 0, 1, 2, 2, 5])
col = np.array([0, 2, 2, 0, 1, 5])
data = np.array([1, 2, 3, 4, 5, 6])
m2 = csr((data, (row, col)))
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = [1, 2, 3, 4, 5]
m1 = coo((a, (b, c)))
print m2.toarray()
print m1.toarray()
print m2.todok
x = np.array([[1], [2], [3], [4], [5], [6]]).dot(np.array([[1, 2, 3, 4, 5,
                                                            6]]))
print x
kx = m2.todok().keys()
print kx
print "np", np.array(m2.todok().keys())
x1 = np.sum(kx, axis=1)
print x1
print np.take(x, x1)
y = coo((np.take(x, x1), kx))
print y.toarray()
    for chrom in CHROMS:
        if chrom not in eregs:
            eregs[chrom] = np.zeros((1, 2)).astype('int32')
        if chrom not in pregs:
            pregs[chrom] = np.zeros((1, 2)).astype('int32')
        if chrom not in estrength:
            estrength[chrom] = np.zeros((1)).astype('int32')
        if chrom not in expressed_proms:
            expressed_proms[chrom] = np.zeros((1)).astype('int32')

    print("Parsing E-P links...")
    llinks = np.load(args.linearlinks, allow_pickle=True)
    llinks = {
        key: coo((np.ones(llinks[key].shape[0]),
                  (llinks[key][:, 0], llinks[key][:, 1])),
                 shape=(pregs[key].shape[0], eregs[key].shape[0]))
        for key in llinks
    }

    if args.gamma is None:
        if args.contacts is not None:
            print(
                "No value for gamma provided. Inferring power law relationship from contacts..."
            )
            args.gamma = infer_gamma(args.contacts,
                                     binsize=5e3,
                                     thresh=1e6,
                                     normalisation=args.normalisation)
            print("Inferred gamma: {}".format(args.gamma))
        else: