Esempio n. 1
0
 def init_hidden(self, batch_size):
     return (zeros(gpu=is_remote(),
                   sizes=(self.opt.n_layers_rnn, batch_size,
                          self.opt.hidden_size_rnn)),
             zeros(gpu=is_remote(),
                   sizes=(self.opt.n_layers_rnn, batch_size,
                          self.opt.hidden_size_rnn)))
Esempio n. 2
0
def MakeCorrelatedHam(l,L,fock,U,hup,hdw):
    H_U=utils.zeros([l,l])
    H_diag=utils.zeros([l,l])
    H_t=utils.zeros([l,l])
    for i in xrange(len(fock)):
        basis=fock[i]
        for j in xrange(L):
            if basis[j]==basis[j+L] and basis[j]=='1':
                if j == 0:
                    H_U[i,i]+=U
                H_diag[i,i]+=hup[j,j]
                H_diag[i,i]+=hdw[j,j]
            if basis[j] != basis[j+L]:
                if basis[j] == '1':
                    H_diag[i,i]+=hup[j,j]
                else:
                    H_diag[i,i]+=hdw[j,j]                          
	    for k in xrange(L):
		if j < k:
		    if basis[j] != basis[k]:
		        new,phase=Swap(basis,j,k)
		        if new in fock:
		            ind = fock.index(new)
		            H_t[i,ind]=phase*hup[j,k]
		    if basis[j+L] != basis[k+L]:
		        new,phase=Swap(basis,j+L,k+L)
		        if new in fock:
		            ind = fock.index(new)
		            H_t[i,ind]=phase*hdw[j,k]    
    return H_U+H_diag+H_t
Esempio n. 3
0
 def init_hidden(self, batch_size):  # initialize hidden states
     h = zeros(WORD_LSTM_NUM_LAYERS * WORD_LSTM_NUM_DIRS,
               batch_size,
               WORD_LSTM_HIDDEN_SIZE // WORD_LSTM_NUM_DIRS)  # hidden states
     c = zeros(WORD_LSTM_NUM_LAYERS * WORD_LSTM_NUM_DIRS,
               batch_size,
               WORD_LSTM_HIDDEN_SIZE // WORD_LSTM_NUM_DIRS)  # cell states
     return (h, c)
Esempio n. 4
0
 def init_hidden():  # initialize hidden states
     h = zeros(NUM_LAYERS * NUM_DIRS, BATCH_SIZE,
               HIDDEN_SIZE // NUM_DIRS)  # hidden state
     if RNN_TYPE == "LSTM":
         c = zeros(NUM_LAYERS * NUM_DIRS, BATCH_SIZE,
                   HIDDEN_SIZE // NUM_DIRS)  # cell state
         return h, c
     return h
Esempio n. 5
0
 def init_hidden(self, batch_size):
     if self.opt.bidirectional:
         return (zeros(gpu=is_remote(),
                       sizes=(self.opt.n_layers_rnn * 2, batch_size,
                              self.opt.hidden_size_rnn)),
                 zeros(gpu=is_remote(),
                       sizes=(self.opt.n_layers_rnn * 2, batch_size,
                              self.opt.hidden_size_rnn)))
     else:
         return (zeros(gpu=is_remote(),
                       sizes=(self.opt.n_layers_rnn, batch_size,
                              self.opt.hidden_size_rnn)),
                 zeros(gpu=is_remote(),
                       sizes=(self.opt.n_layers_rnn, batch_size,
                              self.opt.hidden_size_rnn)))
Esempio n. 6
0
def embed(hlat, nimp, nocc):
    nlat = hlat.shape[0]
    elat, clat = numpy.linalg.eigh(hlat)
    cocc = clat[:, 0:nocc]
    dimp = N.dot(cocc, cocc.T)[:nimp, :nimp]

    # projected overlap
    # Ct P C
    s_imp = N.dot(cocc.T, N.dot(pimp(nimp, nlat), cocc))
    sigma, u = numpy.linalg.eigh(s_imp)

    # rotated basis
    cbar = N.dot(cocc, u)

    # embedding projector pemb
    pemb = utils.zeros([nlat, nimp * 2])

    for i in xrange(nimp):
        pemb[i, i] = 1.
    cbath = N.dot(N.eye(nlat) - pimp(nimp, nlat), cbar)

    iptr = 0
    core = []
    for i, s in enumerate(sigma):
        # entangled orbitals
        if abs(s) > 1.e-8:
            pemb[:, nimp + iptr] = cbath[:, i] / (1 - s)**0.5
            iptr += 1
        else:
            core.append(i)

    # core projector pcore
    pcore = cbath[:, core]

    # virtual projector pvirt
    # generate from the null space of pemb+pcore
    pemb_core = N.hstack([pemb, pcore])
    dm_emb_core = N.dot(pemb_core, pemb_core.T)
    wts, vecs = numpy.linalg.eigh(dm_emb_core)

    pvirt = utils.zeros([nlat, nlat - nocc - nimp])
    iptr = 0
    for i, w in enumerate(wts):
        if abs(w) < 1.e-8:
            pvirt[:, iptr] = vecs[:, i]
            iptr += 1

    return pemb, pcore, pvirt
Esempio n. 7
0
def embed(hlat,nimp,nocc):
    nlat=hlat.shape[0]
    elat, clat=numpy.linalg.eigh(hlat)
    cocc=clat[:,0:nocc]
    dimp=N.dot(cocc,cocc.T)[:nimp,:nimp]

    # projected overlap
    # Ct P C
    s_imp=N.dot(cocc.T,N.dot(pimp(nimp,nlat),cocc))
    sigma, u=numpy.linalg.eigh(s_imp)

    # rotated basis
    cbar=N.dot(cocc,u)

    # embedding projector pemb
    pemb=utils.zeros([nlat,nimp*2])

    for i in xrange(nimp):
        pemb[i,i]=1.
    cbath=N.dot(N.eye(nlat)-pimp(nimp,nlat),cbar)

    iptr=0
    core=[]
    for i, s in enumerate(sigma):
        # entangled orbitals
        if abs(s)>1.e-8:
            pemb[:,nimp+iptr]=cbath[:,i]/(1-s)**0.5
            iptr+=1
        else:
            core.append(i)

    # core projector pcore
    pcore=cbath[:,core]

    # virtual projector pvirt
    # generate from the null space of pemb+pcore
    pemb_core=N.hstack([pemb,pcore])
    dm_emb_core=N.dot(pemb_core, pemb_core.T)
    wts,vecs=numpy.linalg.eigh(dm_emb_core)

    pvirt=utils.zeros([nlat,nlat-nocc-nimp])
    iptr=0
    for i, w in enumerate(wts):
        if abs(w)<1.e-8:
            pvirt[:,iptr]=vecs[:,i]
            iptr+=1
            
    return pemb, pcore, pvirt
Esempio n. 8
0
def add(mpsa, mpsb):
    """
    add two mps
    """
    if mpsa == None:
        return [mt.copy() for mt in mpsb]
    elif mpsb == None:
        return [mt.copy() for mt in mpsa]

    assert len(mpsa) == len(mpsb)
    nsites = len(mpsa)
    pdim = mpsa[0].shape[1]
    assert pdim == mpsb[0].shape[1]

    mpsab = [None] * nsites

    mpsab[0] = N.dstack([mpsa[0], mpsb[0]])
    for i in xrange(1, nsites - 1):
        mta = mpsa[i]
        mtb = mpsb[i]
        mpsab[i] = utils.zeros(
            [mta.shape[0] + mtb.shape[0], pdim, mta.shape[2] + mtb.shape[2]])
        mpsab[i][:mta.shape[0], :, :mta.shape[2]] = mta[:, :, :]
        mpsab[i][mta.shape[0]:, :, mta.shape[2]:] = mtb[:, :, :]

    mpsab[-1] = N.vstack([mpsa[-1], mpsb[-1]])
    return mpsab
    def init_forward_all(self, batch_size, post, post_length, h_init=None):
        if h_init is None:
            h_init = self.getInitialParameter(batch_size)
        else:
            h_init = torch.unsqueeze(h_init, 0)
        h_now = h_init[0]
        context = zeros(batch_size, self.post_size)

        def nextStep(incoming, stopmask):
            nonlocal h_now, post, post_length, context

            if self.gru_input_attn:
                h_now = self.cell_forward(torch.cat([incoming, context], dim=-1), h_now) \
                    * (1 - stopmask).float().unsqueeze(-1)
            else:
                h_now = self.cell_forward(
                    incoming, h_now) * (1 - stopmask).float().unsqueeze(-1)

            query = self.attn_query(h_now)
            attn_weight = maskedSoftmax((query.unsqueeze(0) * post).sum(-1),
                                        post_length)
            context = (attn_weight.unsqueeze(-1) * post).sum(0)

            return torch.cat([h_now, context], dim=-1), attn_weight

        return nextStep, h_now, context
Esempio n. 10
0
 def gold_viterbi_loss(self,x,y):
     unary_pot = self.bilstm(x)
     unary_pot = F.pad(unary_pot,(0,2),'constant',LOW_POT)
     gold_score = self.crf.score(unary_pot,y)
     viterbi_score,_ = self.crf(unary_pot)
     loss,_= torch.max(torch.stack([Variable(utils.zeros(gold_score.size(0))), viterbi_score - gold_score],dim=1),dim = 1)
     return loss
Esempio n. 11
0
def matrix_form(h, bra_configs, ket_configs):
    hmat = utils.zeros([len(bra_configs), len(ket_configs)])

    for i, bra in enumerate(bra_configs):
        for j, ket in enumerate(ket_configs):
            hmat[i, j] = matrix_element(h, bra, ket)
    return hmat
Esempio n. 12
0
def matrix_form(h, bra_configs, ket_configs):
    hmat=utils.zeros([len(bra_configs),len(ket_configs)])

    for i, bra in enumerate(bra_configs):
        for j, ket in enumerate(ket_configs):
            hmat[i,j]=matrix_element(h,bra,ket)
    return hmat
Esempio n. 13
0
def oimp_matrix_form(oimp, ops_configs, cocc, vocc):
    # matrix elements of
    # sum < | oimp | > where oimp acts only on the imp+bath space
    # cocc, vocc: lists of core, virtual labels
    assert not oimp.fermion  # operator should have an even number of c/d operators
    start = {}
    end = {}
    nconfigs = [len(configs) for (ops, configs) in ops_configs]
    ops = [opi for (opi, configi) in ops_configs]
    for i, opi in enumerate(ops):
        start[opi] = sum(nconfigs[:i])
        end[opi] = start[opi] + nconfigs[i]
    full_mat = utils.zeros([sum(nconfigs), sum(nconfigs)])

    for i, (opi, configsi) in enumerate(ops_configs):
        opit = opi.t()
        mat = qoperator.matrix_form(oimp, configsi, configsi)
        for j, (opj, configj) in enumerate(ops_configs):
            if isinstance(opit, models.Unit) and isinstance(opj, models.Unit):
                norm = 1.
                full_mat[start[opi]:end[opi], start[opj]:end[opj]] = norm * mat
            elif isinstance(opi, models.ContractedC) and isinstance(
                    opj, models.ContractedC):
                norm = norm_c(opit, opj, cocc, vocc)
                full_mat[start[opi]:end[opi], start[opj]:end[opj]] = norm * mat
            elif isinstance(opi, models.ContractedD) and isinstance(
                    opj, models.ContractedD):
                norm = norm_d(opit, opj, cocc, vocc)
                full_mat[start[opi]:end[opi], start[opj]:end[opj]] = norm * mat
            elif isinstance(opi, models.ContractedCD) and isinstance(
                    opj, models.ContractedCD):
                norm = norm_cd(opit, opj, cocc, vocc)
                full_mat[start[opi]:end[opi], start[opj]:end[opj]] = norm * mat

    return full_mat
Esempio n. 14
0
def si_anderson_imp_ext_ni_h(t,u,nocc,nimp,nsites):
    ncore=2*nocc-2*nimp
    cocc=range(4*nimp,4*nimp+ncore)
    #cb_edge = 1.
    #gap = 2.0*cb_edge/(nsites-2)
    hlat=utils.zeros([nsites,nsites])
    hlat[0,1:] = t
    hlat[1:,0] = t
    cbstates = [0, 1./3, -1./3, 2./3, -2./3, 1., -1.]
    for i in xrange(nsites-1):
        hlat[i+1,i+1] = cbstates[i]
    '''    
    for i in xrange(nsites-1):
        hlat[i+1,i+1] = -cb_edge + i*gap
        hlat[0,i+1] = t
        hlat[i+1,0] = t
    #hlat[0,0] += u/2
    #hlat[0,0] = -0.5*u
    hu=utils.zeros([nsites,nsites])
    #hu[0,0] = 0.5*u
    '''       
    hlat_sp=_spinify(hlat)    
    pemb,pcore,pvirt=embed.embed(hlat,nimp,nocc)    
    pall=N.hstack([pemb,pcore,pvirt])
    hall=N.dot(pall.T,N.dot(hlat,pall))
    hall_sp=_spinify(hall)
    hall_sp_diag=N.diag(hall_sp)
    e0=sum(hall_sp_diag[cocc])
    return hlat, hall, hlat_sp, hall_sp, e0
Esempio n. 15
0
def _spinify(mat):
    sp_mat = utils.zeros([mat.shape[0] * 2, mat.shape[1] * 2])
    for i in xrange(mat.shape[0]):
        for j in xrange(mat.shape[1]):
            sp_mat[2 * i, 2 * j] = mat[i, j]
            sp_mat[2 * i + 1, 2 * j + 1] = mat[i, j]
    return sp_mat
Esempio n. 16
0
    def teacherForcing(self, inp, gen):
        embedding = inp.embedding  # length * valid_num * embedding_dim
        length = inp.resp_length  # valid_num
        wiki_cv = inp.wiki_cv  # valid_num * (2 * eh_size)
        wiki_cv = wiki_cv.unsqueeze(0).repeat(embedding.shape[0], 1, 1)

        gen.h, gen.h_n = self.GRULayer.forward(torch.cat([embedding, wiki_cv],
                                                         dim=-1),
                                               length - 1,
                                               h_init=inp.init_h,
                                               need_h=True)

        gen.w = self.wLinearLayer(self.drop(gen.h))
        gen.w = torch.clamp(gen.w, max=5.0)
        gen.vocab_p = torch.exp(gen.w)
        wikiState = torch.transpose(
            torch.tanh(self.wCopyLinear(inp.wiki_hidden)), 0, 1)
        copyW = torch.exp(
            torch.clamp(torch.unsqueeze(
                torch.transpose(
                    torch.sum(
                        torch.unsqueeze(gen.h, 1) *
                        torch.unsqueeze(wikiState, 0), -1), 1, 2), 2),
                        max=5.0))

        inp.wiki_sen = inp.wiki_sen[:, :inp.wiki_hidden.shape[1]]
        copyHead = zeros(1, inp.wiki_sen.shape[0], inp.wiki_hidden.shape[1],
                         self.param.volatile.dm.vocab_size).scatter_(
                             3,
                             torch.unsqueeze(torch.unsqueeze(inp.wiki_sen, 0),
                                             3), 1)
        gen.copy_p = torch.matmul(copyW, copyHead).squeeze(2)
        gen.p = gen.vocab_p + gen.copy_p + 1e-10
        gen.p = gen.p / torch.unsqueeze(torch.sum(gen.p, 2), 2)
        gen.p = torch.clamp(gen.p, 1e-10, 1.0)
Esempio n. 17
0
    def __init__(self, dat_file, offset):
        self.dat_file = dat_file
        self.offset = offset

        self.subdir_ptrs = []
        self.file_ptrs = []

        f = self.dat_file.stream
        f.seek(offset)
        row = f.read(0x08)
        assert zeros(row)

        # sub-directories

        f.seek(offset + 0x08)
        for i in range(62):
            row = f.read(0x08)
            block_size, dir_offset = struct.unpack("<LL", row)
            if block_size == 0:
                break
            # assert block_size == self.dat_file.block_size
            self.subdir_ptrs.append((i, block_size, dir_offset))

        f.seek(offset + (0x08 * 63))
        self.count = struct.unpack("<L", f.read(4))[0]
        self.subdir_ptrs = self.subdir_ptrs[:self.count + 1]

        # files

        for i in range(self.count):
            d = f.read(0x20)
            unk1, file_id, file_offset, size1, timestamp, version, size2, unk2 = \
                struct.unpack("<LLLLLLLL", d)
            if size1 > 0:
                self.file_ptrs.append((i, unk1, file_id, file_offset, size1, timestamp, version, size2, unk2))
Esempio n. 18
0
def _spinify(mat):
    sp_mat=utils.zeros([mat.shape[0]*2,mat.shape[1]*2])
    for i in xrange(mat.shape[0]):
        for j in xrange(mat.shape[1]):
            sp_mat[2*i,2*j]=mat[i,j]            
            sp_mat[2*i+1,2*j+1]=mat[i,j]
    return sp_mat
Esempio n. 19
0
    def __init__(self, linear_program):
        self._objective_function = linear_program.objective_function
        self._constraints_count = linear_program.constraints_count
        self._real_variables_count = linear_program.variables_count
        self.should_initialize = False
        self._using_artificial_variable = False
        self._variables_count = self._constraints_count + self._real_variables_count
        self.pivots_count = 0

        if min(linear_program.righthand_side) < 0:
            self.should_initialize = True

        # 1 col for free variable, 1 row for objective_function
        self._tableau = zeros((self._constraints_count + 1, self._variables_count + 1))

        # lefthand-side:
        # real variales
        self._tableau[self._CONSTRAINT_ROW_START_INDEX:, self._VARIABLES_COL_START_INDEX: self._real_variables_count + 1] = linear_program.lefthand_side
        # slack variables - we assume every line is <= (LE) so we just need to add a slack variable per constraint
        slack_start_index = self._VARIABLES_COL_START_INDEX + self._real_variables_count
        self._tableau[self._CONSTRAINT_ROW_START_INDEX:, slack_start_index: slack_start_index + self._constraints_count] = eye(self._constraints_count)

        # righthand-side:
        self._tableau[self._CONSTRAINT_ROW_START_INDEX:, self._VARIABLES_FREE_VARIABLE_COL_INDEX] = linear_program.righthand_side * -1

        # initially all slack variables are basic
        self._basic_vars = np.zeros((self._variables_count + 1,), dtype='int')  # including free variable, unused and should always be 0
        self._basic_vars[slack_start_index: slack_start_index + self._constraints_count] = range(1, self._constraints_count + 1)
        self._tight_vars = np.array(range(self._real_variables_count, self._variables_count + 1), dtype='int')
        self._tight_vars[0] = 0

        assert len(self._basic_vars) == self._tableau.shape[1], 'basic variables array must be the same size as tablue row size'
Esempio n. 20
0
def oimp_matrix_form(oimp,ops_configs,cocc,vocc):
    # matrix elements of 
    # sum < | oimp | > where oimp acts only on the imp+bath space
    # cocc, vocc: lists of core, virtual labels
    assert not oimp.fermion # operator should have an even number of c/d operators
    start={}
    end={}
    nconfigs=[len(configs) for (ops, configs) in ops_configs]
    ops=[opi for (opi, configi) in ops_configs]
    for i, opi in enumerate(ops):
        start[opi]=sum(nconfigs[:i])
        end[opi]=start[opi]+nconfigs[i]

    full_mat=utils.zeros([sum(nconfigs),sum(nconfigs)])
    
    for i, (opi, configsi) in enumerate(ops_configs):
        opit=opi.t()
        mat=qoperator.matrix_form(oimp,configsi,configsi)
        for j, (opj, configj) in enumerate(ops_configs):
            if isinstance(opit,models.Unit) and isinstance(opj,models.Unit):
                norm=1.
                full_mat[start[opi]:end[opi],start[opj]:end[opj]]=norm*mat
            elif isinstance(opi,models.ContractedC) and isinstance(opj,models.ContractedC):
                norm=norm_c(opit,opj,cocc,vocc)
                full_mat[start[opi]:end[opi],start[opj]:end[opj]]=norm*mat
            elif isinstance(opi,models.ContractedD) and isinstance(opj,models.ContractedD):
                norm=norm_d(opit,opj,cocc,vocc)
                full_mat[start[opi]:end[opi],start[opj]:end[opj]]=norm*mat
            elif isinstance(opi,models.ContractedCD) and isinstance(opj,models.ContractedCD):
                norm=norm_cd(opit,opj,cocc,vocc)
                full_mat[start[opi]:end[opi],start[opj]:end[opj]]=norm*mat


    return full_mat
Esempio n. 21
0
def add(mpsa, mpsb, mpsaqn=None, mpsbqn=None):
    """
    add two mps
    """
    if mpsa == None:
        return [mt.copy() for mt in mpsb], mpsbqn
    elif mpsb == None:
        return [mt.copy() for mt in mpsa], mpsaqn

    assert len(mpsa) == len(mpsb)

    nsites = len(mpsa)

    mpsab = [None] * nsites

    mpsab[0] = N.dstack([mpsa[0], mpsb[0]])
    for i in xrange(1, nsites - 1):
        mta = mpsa[i]
        mtb = mpsb[i]
        pdim = mta.shape[1]
        assert pdim == mtb.shape[1]
        mpsab[i] = utils.zeros(
            [mta.shape[0] + mtb.shape[0], pdim, mta.shape[2] + mtb.shape[2]])
        mpsab[i][:mta.shape[0], :, :mta.shape[2]] = mta[:, :, :]
        mpsab[i][mta.shape[0]:, :, mta.shape[2]:] = mtb[:, :, :]

    mpsab[-1] = N.vstack([mpsa[-1], mpsb[-1]])

    if mpsaqn != None and mpsbqn != None:
        mpsabqn = []
        for i in xrange(len(mpsaqn)):
            mpsabqn.append(mpsaqn[i] + mpbqn[i])
        return mpsab, mpsabqn
    else:
        return mpsab, None
Esempio n. 22
0
 def _preprocess_batch(self, data):
     incoming = Storage()
     incoming.data = data = Storage(data)
     data.batch_size = data.sent.shape[0]
     data.sent = cuda(torch.LongTensor(data.sent))  # length * batch_size
     data.sent_attnmask = zeros(*data.sent.shape)
     for i, length in enumerate(data.sent_length):
         data.sent_attnmask[i, :length] = 1
     return incoming
Esempio n. 23
0
def Evaluate_VPsi0(psi0,fock,fock_minus,fock_plus,plus,minus):
    if minus:        
        coeff=utils.zeros(len(fock_minus))        
        for i in xrange(len(fock)):
            bas=fock[i]
            if bas[0] == '1':
                new = '0'+bas[1:]
                ind=fock_minus.index(new)
                coeff[ind]=psi0[i]
        
    if plus:
        coeff=utils.zeros(len(fock_plus))
        for i in xrange(len(fock)):
            bas=fock[i]
            if bas[0] == '0':
                new = '1'+bas[1:]
                ind=fock_plus.index(new)
                coeff[ind]=psi0[i]
    return coeff
Esempio n. 24
0
def create(pdim, config):
    """
    Create dim=1 MPS
    pdim: physical dimension
    """
    nsites = len(config)
    mps = [utils.zeros([1, pdim, 1]) for i in xrange(nsites)]
    for i, p in enumerate(config):
        mps[i][0, p, 0] = 1.
    return mps
Esempio n. 25
0
    def get_current_solution(self):
        solution = zeros(self._real_variables_count)
        for i in range(1, self._real_variables_count + 1):
            if self._basic_vars[i] == 0:
                continue

            # solution variable indices start from 0
            solution[i - 1] = -self._tableau[self._basic_vars[i], 0] / self._tableau[self._basic_vars[i], i]

        return solution
Esempio n. 26
0
def oimp_matrix_bra_ket_form(oimp, ops_bra_configs, ops_ket_configs, cocc,
                             vocc):
    # imp is an operator that acts only on the imp and bath orbitals.
    # (e.g. himp)
    bra_start = {}
    bra_end = {}
    ket_start = {}
    ket_end = {}
    bra_nconfigs = [len(bra_configs) for (ops, bra_configs) in ops_bra_configs]
    ket_nconfigs = [len(ket_configs) for (ops, ket_configs) in ops_ket_configs]
    bra_ops = [opi for (opi, bra_configs) in ops_bra_configs]
    ket_ops = [opi for (opi, ket_configs) in ops_ket_configs]
    for i, opi in enumerate(bra_ops):
        bra_start[opi] = sum(bra_nconfigs[:i])
        bra_end[opi] = bra_start[opi] + bra_nconfigs[i]

    for i, opi in enumerate(ket_ops):
        ket_start[opi] = sum(ket_nconfigs[:i])
        ket_end[opi] = ket_start[opi] + ket_nconfigs[i]

    full_mat = utils.zeros([sum(bra_nconfigs), sum(ket_nconfigs)])

    for i, (opi, bra_configsi) in enumerate(ops_bra_configs):

        opit = opi.t()
        for j, (opj, ket_configsj) in enumerate(ops_ket_configs):

            # <imp1.core|opi oimp opj|core.imp2>:
            # parity is opi.parity*oimp.parity*core.parity
            # but assume core is even
            mat = qoperator.matrix_form(oimp, bra_configsi, ket_configsj)
            parity = 1.
            if oimp.fermion and opi.fermion:
                parity = -1.
            if isinstance(opit, models.Unit) and isinstance(opj, models.Unit):
                norm = 1.
                full_mat[bra_start[opi]:bra_end[opi],
                         ket_start[opj]:ket_end[opj]] = norm * mat * parity
            elif isinstance(opi, models.ContractedC) and isinstance(
                    opj, models.ContractedC):
                norm = norm_c(opit, opj, cocc, vocc)
                full_mat[bra_start[opi]:bra_end[opi],
                         ket_start[opj]:ket_end[opj]] = norm * mat * parity
            elif isinstance(opi, models.ContractedD) and isinstance(
                    opj, models.ContractedD):
                norm = norm_d(opit, opj, cocc, vocc)
                full_mat[bra_start[opi]:bra_end[opi],
                         ket_start[opj]:ket_end[opj]] = norm * mat * parity
            elif isinstance(opi, models.ContractedCD) and isinstance(
                    opj, models.ContractedCD):
                norm = norm_cd(opit, opj, cocc, vocc)
                full_mat[bra_start[opi]:bra_end[opi],
                         ket_start[opj]:ket_end[opj]] = norm * mat * parity

    return full_mat
Esempio n. 27
0
def mps_fci(mps):
    """
    convert MPS into a fci vector
    """
    pdim = mps[0].shape[1]
    nsites = len(mps)
    confs = fci.fci_configs(nsites, pdim)
    fvec = utils.zeros((pdim, ) * nsites)
    for conf in confs:
        fvec[conf] = ceval(mps, conf)
    return fvec
Esempio n. 28
0
def solve_perturb_complex(omega, s, h, e0, c0, v, delta=0., sign_ham=1.):
    lhs_diag = omega * s - sign_ham * (h - e0 * s)
    lhs_off = sign_ham * delta * s
    rhs_block = N.dot(v, c0)

    dim = s.shape[0]
    lhs_full = utils.zeros([2 * dim, 2 * dim])
    lhs_full[0:dim, 0:dim] = lhs_diag
    lhs_full[0:dim, dim:] = -lhs_off
    lhs_full[dim:, dim:] = lhs_diag
    lhs_full[dim:, 0:dim] = lhs_off

    rhs_full = utils.zeros([2 * dim])
    rhs_full[0:dim] = rhs_block

    #sol=scipy.linalg.lstsq(lhs_full,rhs_full)
    #psi1=sol[0]
    sol = N.dot(scipy.linalg.inv(lhs_full), rhs_full)
    psi1 = sol
    return psi1[0:dim], psi1[dim:]
Esempio n. 29
0
def si_anderson_imp_ext_h(h0,u,nocc,nimp,nsites):
    nsites_sp=nsites*2
    sites_imp=range(0,4*nimp)
    sites_ext=range(4*nimp,2*nsites)

    t_dict={}
    for i in xrange(nsites_sp):
        for j in xrange(nsites_sp):
            if abs(h0[i,j]) > 1.e-12:
                t_dict[i,j]=h0[i,j]
    
    t_dict[0,0]=-u/2
    t_dict[1,1]=-u/2

    u_dict={}
    u_dict[0,1]=u

    # h in imp+ext space
    hop=models.GeneralHubbard(t_dict,u_dict)

    t_imp={}
    for i in sites_imp:
        for j in sites_imp:
            if abs(h0[i,j]) > 1.e-12:
                t_imp[i,j]=h0[i,j]

    t_imp[0,0]=-u/2
    t_imp[1,1]=-u/2
    #print 'sites_imp: ',sites_imp

    t_ext={}
    for i in sites_ext:
        for j in sites_ext:
            if abs(h0[i,j]) > 1.e-12:
                t_ext[i,j]=h0[i,j]

    hext=models.ContractedCD(t_ext)

    himp=models.GeneralHubbard(t_imp,u_dict)

    hcs_imp=[]
    hds_imp=[]
    hcs_ext=[]
    hds_ext=[]
    
    for i in sites_imp:
        imp_coeffs=utils.zeros(len(sites_imp))
        imp_coeffs[i]=1.
        hcs_imp.append(models.ContractedC(sites_imp,imp_coeffs))
        hds_imp.append(models.ContractedD(sites_imp,imp_coeffs))
        hcs_ext.append(models.ContractedC(sites_ext,h0[sites_ext,i]))
        hds_ext.append(models.ContractedD(sites_ext,h0[i,sites_ext]))

    return hop, himp, hcs_imp, hds_imp, hcs_ext, hds_ext, hext
Esempio n. 30
0
def solve_perturb_complex(omega,s,h,e0,c0,v,delta=0.,sign_ham=1.):
    lhs_diag=omega*s-sign_ham*(h-e0*s)
    lhs_off=sign_ham*delta*s
    rhs_block=N.dot(v,c0)
    
    dim=s.shape[0]
    lhs_full=utils.zeros([2*dim,2*dim])
    lhs_full[0:dim,0:dim]=lhs_diag
    lhs_full[0:dim,dim:]=-lhs_off
    lhs_full[dim:,dim:]=lhs_diag
    lhs_full[dim:,0:dim]=lhs_off

    rhs_full=utils.zeros([2*dim])
    rhs_full[0:dim]=rhs_block

    #sol=scipy.linalg.lstsq(lhs_full,rhs_full)
    #psi1=sol[0]
    sol=N.dot(scipy.linalg.inv(lhs_full),rhs_full)
    psi1=sol
    return psi1[0:dim],psi1[dim:]
Esempio n. 31
0
def MakeHerm(mat):
    mat_herm=utils.zeros(mat.shape)
    mat_conj=mat.conjugate()  
    for i in xrange(mat.shape[0]): 
        for j in xrange(mat.shape[0]):
            if i == j:
		mat_herm[i,i]=mat[i,i]
	    elif j > i:
                mat_herm[i,j]=mat[i,j]
	    else:
                mat_herm[i,j]=mat_conj[i,j]
    return mat_herm
Esempio n. 32
0
def hubbard_imp_ext_h(h0, u, nocc, nimp, nsites):
    nsites_sp = nsites * 2
    sites_imp = range(0, 4 * nimp)
    sites_ext = range(4 * nimp, 2 * nsites)

    t_dict = {}
    for i in xrange(nsites_sp):
        for j in xrange(nsites_sp):
            if abs(h0[i, j]) > 1.e-12:
                t_dict[i, j] = h0[i, j]

    t_dict[0, 0] = 0
    t_dict[1, 1] = 0

    u_dict = {}
    u_dict[0, 1] = u

    # h in imp+ext space
    hop = models.GeneralHubbard(t_dict, u_dict)

    t_imp = {}
    for i in sites_imp:
        for j in sites_imp:
            if abs(h0[i, j]) > 1.e-12:
                t_imp[i, j] = h0[i, j]

    t_imp[0, 0] = 0
    t_imp[1, 1] = 0

    t_ext = {}
    for i in sites_ext:
        for j in sites_ext:
            if abs(h0[i, j]) > 1.e-12:
                t_ext[i, j] = h0[i, j]

    hext = models.ContractedCD(t_ext)

    himp = models.GeneralHubbard(t_imp, u_dict)

    hcs_imp = []
    hds_imp = []
    hcs_ext = []
    hds_ext = []

    for i in sites_imp:
        imp_coeffs = utils.zeros(len(sites_imp))
        imp_coeffs[i] = 1.
        hcs_imp.append(models.ContractedC(sites_imp, imp_coeffs))
        hds_imp.append(models.ContractedD(sites_imp, imp_coeffs))
        hcs_ext.append(models.ContractedC(sites_ext, h0[sites_ext, i]))
        hds_ext.append(models.ContractedD(sites_ext, h0[i, sites_ext]))

    return hop, himp, hcs_imp, hds_imp, hcs_ext, hds_ext, hext
Esempio n. 33
0
    def __init__(self,
                 name='gat_agg',
                 verbose=False,
                 input_dim=None,
                 output_dim=None,
                 act=tf.nn.relu,
                 bias=True,
                 weight=True,
                 dropout=0.,
                 atn_type=1,
                 atn_drop=False):
        super(GATAgg, self).__init__(name=name, verbose=verbose)

        self.input_dim = input_dim
        self.output_dim = output_dim
        self.act = act
        self.bias = bias
        self.weight = weight
        self.dropout = dropout
        self.atn_type = atn_type
        self.atn_drop = dropout if atn_drop else 0.

        with tf.variable_scope(self.name):
            if self.weight:
                self.vars['weights'] = glorot(shape=[input_dim, output_dim],
                                              name='weights')
            else:
                assert input_dim == output_dim

            self.vars['atn_weights_1'] = glorot([output_dim, 1],
                                                name='atn_weights_1')
            self.vars['atn_weights_2'] = glorot([output_dim, 1],
                                                name='atn_weights_2')
            self.vars['atn_bias_1'] = zeros([1], name='atn_bias_1')
            self.vars['atn_bias_2'] = zeros([1], name='atn_bias_2')

            if self.bias:
                self.vars['bias'] = zeros([output_dim], name='bias')

        self._log_vars()
Esempio n. 34
0
def make_t1amp_ao(h, omega, perturb, nocc):
    eigs,cmo=numpy.linalg.eigh(h)
    nsites=h.shape[0]

    perturb_mo=N.dot(cmo.T,N.dot(perturb,cmo))

    t1amp=utils.zeros([nsites,nsites])
    for i in xrange(nocc):
        for a in xrange(nocc,nsites):
            t1amp[a,i]=perturb_mo[i,a]/(omega-(eigs[a]-eigs[i]))

    t1amp_ao=N.dot(cmo,N.dot(t1amp,cmo.T))
    return t1amp_ao
Esempio n. 35
0
def make_t1amp_ao(h, omega, perturb, nocc):
    eigs, cmo = numpy.linalg.eigh(h)
    nsites = h.shape[0]

    perturb_mo = N.dot(cmo.T, N.dot(perturb, cmo))

    t1amp = utils.zeros([nsites, nsites])
    for i in xrange(nocc):
        for a in xrange(nocc, nsites):
            t1amp[a, i] = perturb_mo[i, a] / (omega - (eigs[a] - eigs[i]))

    t1amp_ao = N.dot(cmo, N.dot(t1amp, cmo.T))
    return t1amp_ao
Esempio n. 36
0
def MakeSingleParticleHam(nsites, V, cb_edge):
    hlat = utils.zeros(
        [nsites, nsites]
    )  #the indexing of hlat is imp, cbsite1, -cbsite1, ... , cbsite(nsites-2)/2,-cbsite(nsites-2)/2
    hlat[0, 1:] = V  #ASSUMES a constant impurity to conduction band hopiing
    hlat[1:, 0] = V
    cb_states = [0]  #list of conduction band energy levels
    for i in range((nsites - 2) / 2):
        cb_states.append((i + 1) / ((nsites - 2) / 2))
        cb_states.append(-(i + 1) / ((nsites - 2) / 2))
    for i in xrange(nsites - 1):
        hlat[i + 1, i + 1] = cb_states[i]
    return hlat
Esempio n. 37
0
def MakeHam(l,L,fock,U,V,cb_edge):
	H_imp = utils.zeros([l,l])
	H_cb = utils.zeros([l,l])
	H_hyb = utils.zeros([l,l])
	#H_U = zeros((l,l),float)
	for i in xrange(l):
	    basis = fock[i]
	    if basis[0] != basis[L]:
		H_imp[i,i] = -U/2
	    #if basis[0] == basis[L] and basis[0] == '1':
		#H_U[i,i] = 1.
	    for j in range(1,L):
		if basis[j] == basis[j+L] and basis[j] == '1':
		    H_cb[i,i] += 2.*cbdiagelements(cb_edge,L,j-1)
		if basis[j] != basis[j+L]:
		    H_cb[i,i] += cbdiagelements(cb_edge,L,j-1)

		if basis[0] != basis[j]:
		    new = basis[j] + basis[1:j] + basis[0] + basis[(j+1):]
		    if j == 1:
			phase = 1.
		    else:
			phase = (-1.)**(sum_digits(int(basis[1:j])))
		    if new in fock:
		        ind = fock.index(new)
		        H_hyb[i,ind] = phase*V
		if basis[L] != basis[j+L]:
		    new = basis[:L] + basis[j+L] + basis[L+1:j+L] + basis[L] + basis[(j+L+1):]
		    if j == 1:
			phase = 1.
		    else:
			phase = (-1.)**(sum_digits(int(basis[L+1:j+L])))
		    if new in fock:	
		        ind = fock.index(new)
		        H_hyb[i,ind] = phase*V

	H = H_imp + H_cb + H_hyb
	return H
Esempio n. 38
0
def make_greens_ao(h, omega, perturb, nocc):
    eigs,cmo=numpy.linalg.eigh(h)
    nsites=h.shape[0]

    perturb_mo=N.dot(cmo.T,perturb)
    #damp=utils.zeros([nocc])
    #camp=utils.zeros([nsites-nocc])
    
    damp=utils.zeros([nsites])
    camp=utils.zeros([nsites])

    for i in xrange(nocc):
        damp[i]=perturb_mo[i]/(omega-eigs[i])
        #print i, perturb_mo[i]/(omega-eigs[i]), damp[i]
    for a in xrange(nocc,nsites):
        camp[a]=perturb_mo[a]/(omega-eigs[a])

    #damp_ao=N.dot(cmo[:,:nocc],damp)
    damp_ao=N.dot(cmo,damp)
    #camp_ao=N.dot(cmo[:,nocc:],camp)
    camp_ao=N.dot(cmo,camp)

    return damp_ao,camp_ao
Esempio n. 39
0
def make_greens_ao(h, omega, perturb, nocc):
    eigs, cmo = numpy.linalg.eigh(h)
    nsites = h.shape[0]

    perturb_mo = N.dot(cmo.T, perturb)
    #damp=utils.zeros([nocc])
    #camp=utils.zeros([nsites-nocc])

    damp = utils.zeros([nsites])
    camp = utils.zeros([nsites])

    for i in xrange(nocc):
        damp[i] = perturb_mo[i] / (omega - eigs[i])
        #print i, perturb_mo[i]/(omega-eigs[i]), damp[i]
    for a in xrange(nocc, nsites):
        camp[a] = perturb_mo[a] / (omega - eigs[a])

    #damp_ao=N.dot(cmo[:,:nocc],damp)
    damp_ao = N.dot(cmo, damp)
    #camp_ao=N.dot(cmo[:,nocc:],camp)
    camp_ao = N.dot(cmo, camp)

    return damp_ao, camp_ao
Esempio n. 40
0
def orth_matrix(n=10):
    Y = utils.rand(n, 1)
    X = utils.zeros(n, n)
    if n > 2:
        for j in xrange(n - 1):
            x = utils.rand(n, 1)
            while abs(abs(utils.corr(x, Y)) - j / (n - 1.0)) > 0.005:
                x = utils.rand(n, 1)
            if utils.corr(x, Y) < 0:
                x *= -1
            X[:, j] = x.ravel()

    X[:, n - 1] = Y.ravel()

    return X, Y
Esempio n. 41
0
def matrix_oneside_form(qop,ops_configs):
    """
    alternative algorithm to matrix_form
    """
    nconfigs=[len(configs) for (ops, configs) in ops_configs]
    full_mat=utils.zeros([sum(nconfigs),sum(nconfigs)])

    for i, (opi, bra_configsi) in enumerate(ops_configs):
        iptr=sum(nconfigs[:i])
        for j, (opj, ket_configsj) in enumerate(ops_configs):
            jptr=sum(nconfigs[:j])
            mat=matrix_opop_element(qop, opi, bra_configsi, opj, ket_configsj)
            full_mat[iptr:iptr+nconfigs[i],jptr:jptr+nconfigs[j]]=mat

    return full_mat
Esempio n. 42
0
def matrix_form(qop,ops_configs):
    """
    < bra opi | qop | opj ket >
    where <bra opi| and |opj ket> are the same set
    """
    nconfigs=[len(configs) for (ops, configs) in ops_configs]
    full_mat=utils.zeros([sum(nconfigs),sum(nconfigs)])

    for i, (opi, bra_configsi) in enumerate(ops_configs):
        iptr=sum(nconfigs[:i])
        for j, (opj, ket_configsj) in enumerate(ops_configs):
            jptr=sum(nconfigs[:j])
            prod_op=qoperator.ProductQOp([opi.t(),qop,opj])
            mat=qoperator.matrix_form(prod_op,bra_configsi,ket_configsj)
            full_mat[iptr:iptr+nconfigs[i],jptr:jptr+nconfigs[j]]=mat
    return full_mat
Esempio n. 43
0
def _second_order_energy(h0,nocc,perturb,omega):
    # non-interacting density-density response function
    # perturb is a 1-particle [nsites,nsites] perturbation matrix
    # if perturb[0,0]=1 and all else are 0, this corresponds to
    # density-density response
    eigs,cmo=scipy.linalg.eigh(h0)
    nsites=h0.shape[0]

    perturb_mo=N.dot(cmo.T,N.dot(perturb,cmo))
    t1amp=utils.zeros([nsites,nsites])
    ret_val=0.
    for i in xrange(nocc):
        for a in xrange(nocc,nsites):
            t1amp[a,i]=perturb_mo[a,i]/(omega-(eigs[a]-eigs[i]))
            ret_val+=t1amp[a,i]*perturb_mo[i,a]
    return ret_val
Esempio n. 44
0
def oimp_matrix_bra_ket_form(oimp,ops_bra_configs,ops_ket_configs,cocc,vocc):
    # imp is an operator that acts only on the imp and bath orbitals.
    # (e.g. himp)
    bra_start={}
    bra_end={}
    ket_start={}
    ket_end={}
    bra_nconfigs=[len(bra_configs) for (ops, bra_configs) in ops_bra_configs]
    ket_nconfigs=[len(ket_configs) for (ops, ket_configs) in ops_ket_configs]
    bra_ops=[opi for (opi, bra_configs) in ops_bra_configs]
    ket_ops=[opi for (opi, ket_configs) in ops_ket_configs]
    for i, opi in enumerate(bra_ops):
        bra_start[opi]=sum(bra_nconfigs[:i])
        bra_end[opi]=bra_start[opi]+bra_nconfigs[i]

    for i, opi in enumerate(ket_ops):
        ket_start[opi]=sum(ket_nconfigs[:i])
        ket_end[opi]=ket_start[opi]+ket_nconfigs[i]

    full_mat=utils.zeros([sum(bra_nconfigs),sum(ket_nconfigs)])
    
    for i, (opi, bra_configsi) in enumerate(ops_bra_configs):
        opit=opi.t()
        
        for j, (opj, ket_configsj) in enumerate(ops_ket_configs):
            # <imp1.core|opi oimp opj|core.imp2>:
            # parity is opi.parity*oimp.parity*core.parity
            # but assume core is even
            mat=qoperator.matrix_form(oimp,bra_configsi,ket_configsj)
            parity=1.
            if oimp.fermion and opi.fermion:
                parity=-1.

            if isinstance(opit,models.Unit) and isinstance(opj,models.Unit):
                norm=1.
                full_mat[bra_start[opi]:bra_end[opi],ket_start[opj]:ket_end[opj]]=norm*mat*parity
            elif isinstance(opi,models.ContractedC) and isinstance(opj,models.ContractedC):
                norm=norm_c(opit,opj,cocc,vocc)
                full_mat[bra_start[opi]:bra_end[opi],ket_start[opj]:ket_end[opj]]=norm*mat*parity
            elif isinstance(opi,models.ContractedD) and isinstance(opj,models.ContractedD):
                norm=norm_d(opit,opj,cocc,vocc)
                full_mat[bra_start[opi]:bra_end[opi],ket_start[opj]:ket_end[opj]]=norm*mat*parity
            elif isinstance(opi,models.ContractedCD) and isinstance(opj,models.ContractedCD):
                norm=norm_cd(opit,opj,cocc,vocc)
                full_mat[bra_start[opi]:bra_end[opi],ket_start[opj]:ket_end[opj]]=norm*mat*parity

    return full_mat
Esempio n. 45
0
def matrix_bra_ket_form(qop,ops_bra_configs,ops_ket_configs):
    """
    < bra opi | qop | opj ket >
    where <bra opi| and |opj ket> can be different sets
    """
    bra_nconfigs=[len(configs) for (ops, configs) in ops_bra_configs]
    ket_nconfigs=[len(configs) for (ops, configs) in ops_ket_configs]
    full_mat=utils.zeros([sum(bra_nconfigs),sum(ket_nconfigs)])

    for i, (opi, bra_configsi) in enumerate(ops_bra_configs):
        iptr=sum(bra_nconfigs[:i])
        for j, (opj, ket_configsj) in enumerate(ops_ket_configs):
            jptr=sum(ket_nconfigs[:j])
            prod_op=qoperator.ProductQOp([opi.t(),qop,opj])
            mat=qoperator.matrix_form(prod_op,bra_configsi,ket_configsj)
            full_mat[iptr:iptr+bra_nconfigs[i],jptr:jptr+ket_nconfigs[j]]=mat
    return full_mat
Esempio n. 46
0
def matrix_opop_element(h, bra_op, bra_configs, ket_op, ket_configs):
    hmat=utils.zeros([len(bra_configs),len(ket_configs)])
    hket_op=qoperator.ProductQOp([h,ket_op])
    for i, bra_config in enumerate(bra_configs):
        new_bra_configs, bints=bra_op(bra_config)
        bra_dict=collections.defaultdict(float)
        for nbc, bi in zip(new_bra_configs,bints):
            bra_dict[tuple(nbc)]+=bi
        
        for j, ket_config in enumerate(ket_configs):
            new_ket_configs, kints=hket_op(ket_config)

            for nkc, kj in zip(new_ket_configs,kints):
                try:
                    hmat[i,j]+=bra_dict[tuple(nkc)]*kj
                except:
                    pass

    return hmat
def orth_matrix(n=10):
    Y = utils.rand(n, 1)
    X = utils.zeros(n, n)
    if n > 2:
        for j in xrange(n - 1):
            x = utils.rand(n, 1)
            while abs(abs(utils.corr(x, Y)) - j / (n - 1.0)) > 0.005:
                x = utils.rand(n, 1)
            if utils.corr(x, Y) < 0:
                x *= -1
            X[:, j] = x.ravel()

    X[:, n - 1] = Y.ravel()

    return X, Y


#def check_ortho(M, err_msg):
#    K = np.dot(M.T, M)
#    assert_array_almost_equal(K, np.diag(np.diag(K)), err_msg=err_msg)
Esempio n. 48
0
def si_anderson_imp_ext_ni_h(t,nocc,nimp,nsites):
    ncore=2*nocc-2*nimp
    cocc=range(4*nimp,4*nimp+ncore)

    hlat=utils.zeros([nsites,nsites])
    for i in xrange(nsites):
        for j in xrange(nsites):
            if abs(i-j)==1:
                hlat[i,j]=t

    hlat_sp=_spinify(hlat)    

    pemb,pcore,pvirt=embed.embed(hlat,nimp,nocc)
    
    pall=N.hstack([pemb,pcore,pvirt])
    hall=N.dot(pall.T,N.dot(hlat,pall))
    hall_sp=_spinify(hall)

    hall_sp_diag=N.diag(hall_sp)
    e0=sum(hall_sp_diag[cocc])

    return hlat, hall, hlat_sp, hall_sp, e0
Esempio n. 49
0
def hext_matrix_form(hext,ops_configs,cocc,vocc,e0):
    # matrix elements of 
    # sum < | oext | > where oimp acts only on the imp+bath space
    # cocc, vocc: lists of core, virtual labels
    # e0: core energy
    start={}
    end={}
    nconfigs=[len(configs) for (ops, configs) in ops_configs]
    ops=[opi for (opi, configi) in ops_configs]
    for i, opi in enumerate(ops):
        start[opi]=sum(nconfigs[:i])
        end[opi]=start[opi]+nconfigs[i]

    full_mat=utils.zeros([sum(nconfigs),sum(nconfigs)])

    # hext
    for i, (opi, configi) in enumerate(ops_configs):
        opit=opi.t()
        mat_imp=N.eye(len(configi))
        for j, (opj, configj) in enumerate(ops_configs):
            if isinstance(opit,models.Unit) and isinstance(opj,models.Unit):
                val=eval_h(hext,cocc,vocc,e0)
                full_mat[start[opi]:end[opi],start[opj]:end[opj]]+=mat_imp*val

            elif isinstance(opit,models.ContractedD) and isinstance(opj,models.ContractedC):
                val=eval_dv_h_cv(opit,hext,opj,cocc,vocc,e0)
                full_mat[start[opi]:end[opi],start[opj]:end[opj]]+=mat_imp*val

            elif isinstance(opit,models.ContractedC) and isinstance(opj,models.ContractedD):
                val=eval_co_h_do(opit,hext,opj,cocc,vocc,e0)
                full_mat[start[opi]:end[opi],start[opj]:end[opj]]+=mat_imp*val

            elif isinstance(opit,models.ContractedCD) and isinstance(opj,models.ContractedCD):
                val=eval_codv_h_cvdo(opit,hext,opj,cocc,vocc,e0)
                full_mat[start[opi]:end[opi],start[opj]:end[opj]]+=mat_imp*val

    return full_mat
import sympy as sp

from utils import poles, zeros

def G(s):
    return 1 / (1.25 * (s + 1) * (s + 2)) * sp.Matrix([[s - 1, s],
                                                       [-6, s - 2]])
                                                
print 'Poles: ' , poles(G)
print 'Zeros: ' , zeros(G)
Esempio n. 51
0
def fp(x,W,b,r):
	if r.shape[0] is not x.shape[0]:
		r = utils.zeros([x.shape[0],r.shape[1]])
   	mmprod(x,W,r)
   	madd_col_vec(r,b,r)
from __future__ import print_function
import numpy as np

from utils import poles, zeros

def G(s):
    return 1 / (s + 2) * np.matrix([[s - 1,  4],
                                    [4.5, 2 * (s - 1)]])
print('Poles: ' , poles(G))
print('Zeros: ' , zeros(G))
Esempio n. 53
0
A = checkdimensions(A)
B = checkdimensions(B)
C = checkdimensions(C)
D = checkdimensions(D)
    
AB = np.concatenate((A,B),axis=1)
CD = np.concatenate((C,D), axis=1)
M  = np.concatenate((AB,CD),axis=0)

rowA, colA = np.shape(A)
rowB, colB = np.shape(B)
rowC, colC = np.shape(C)
rowD, colD = np.shape(D)

I = np.eye(rowA,colA)
top = np.concatenate((I,np.zeros((rowB,colB))),axis=1)
bottom = np.concatenate((np.zeros((rowC,colC)),np.zeros((rowD,colD))),axis=1)
Ig = sp.Matrix(np.concatenate((top,bottom),axis=0))

z = sp.Symbol('z')
zIg = z * Ig
f = zIg - M
zf = f.det()
zero = sp.solve(zf, z)
print("Zero calcualted by manual method = ",zero)

# or using utils function which I only discovered after doing all this
zeros = zeros(None,A,B,C,D)
print("Zero calculated by utils = ",zeros)
        
Esempio n. 54
0
def ph_greens():
    # main loop for general density-density (ph) response functions
    utils.dtype=N.complex128
    nimp=2

    nimp_sp=2*nimp
    nocc=12
    nsites=24
    nsites_sp=nsites*2
    ndim=2
    sz=0
    # sites numbered in order as imp+bath ... ext
    sites_imp=range(0,2*nimp_sp)
    sites_ext=range(2*nimp_sp,nsites_sp)
    ncore=2*nocc-2*nimp
    cocc=range(2*nimp_sp,2*nimp_sp+ncore)
    vocc=range(2*nimp_sp+ncore,nsites_sp)

    N.set_printoptions(precision=3)

    t=-1. # hopping
    delta=0.01 # broadening

#    for u in [0.0,4.0,10.0]:
    for u in [4.0]:

        # Single impurity Anderson model
        mu=0.
        hlat,hall,hlat_sp,hall_sp,e0=models_embed.si_anderson_imp_ext_ni_h(t,nocc,nimp,nsites)
        hop,himp,hcs_imp,hds_imp,hcs_ext,hds_ext,hext=models_embed.si_anderson_imp_ext_h(hall_sp,u,nocc,nimp,nsites)

#        single site Hubbard in DMET basis
#        mu=u/2
#        hlat,hall,hlat_sp,hall_sp,e0=models_embed.hubbard_imp_ext_ni_h(t,u,nocc,nimp,nsites)
#        hop,himp,hcs_imp,hds_imp,hcs_ext,hds_ext,hext=models_embed.hubbard_imp_ext_h(hall_sp,u,nocc,nimp,nsites)

        # g.s embedding basis
        pemb,pcore,pvirt=embed.embed(hlat,nimp,nocc)

        # perturbation operator
        perturb=utils.zeros([nsites,nsites])
        perturb[0,0]=1.

        p_coeffs={}
        p_coeffs[0,0]=1.
        p_coeffs[1,1]=1.
        perturbop=models.ContractedCD(p_coeffs)

        fd=file("ph_siam.out."+str(u),"w")
        for omega in N.arange(2.0,8.0,0.1):
    
            ops_dict=response_embed.mb_ph_ops(hlat,perturb,omega+1j*delta,nimp,nocc,pemb,pcore,pvirt)
            configs_dict=response_embed.mb_configs(nsites,nimp,nimp_sp,2*nocc-nimp_sp,0)
            neutral_ops_configs=response_embed.mb_ph_ops_configs(ops_dict,configs_dict)

            # basis is setup, now build matrix representations
            perturb_mat=opbasis_ni.oimp_matrix_form(perturbop,neutral_ops_configs,cocc,vocc)

            # h, neutral configs
            himp_mat=opbasis_ni.oimp_matrix_form(himp,neutral_ops_configs,cocc,vocc)
            himp_ext_mat=opbasis_ni.himp_ext_matrix_form(hcs_imp,hds_ext,hds_imp,hcs_ext,neutral_ops_configs,cocc,vocc)
            hext_mat=opbasis_ni.hext_matrix_form(hext,neutral_ops_configs,cocc,vocc,e0)
            
            hmat=himp_mat+himp_ext_mat+hext_mat

            unit_mat=opbasis_ni.oimp_matrix_form(models.Unit(),neutral_ops_configs,cocc,vocc)

            # get neutral ground-state energy
#            print 'overlap: '
#            for i,w in enumerate(unit_mat):
#                for j,v in enumerate(w):
#                    if abs(unit_mat[i,j]) > 1.e-12:
#                        print i+1,j+1,unit_mat[i,j]
            #hmat[4:,:] = 0.
            #hmat[:,4:] = 0.
            #print 'hamil: '
            #for i,w in enumerate(hmat):
            #    for j,v in enumerate(w):
            #        if abs(hmat[i,j]) > 1.e-12:
            #            print i+1,j+1,hmat[i,j]
#
            es,cs=la.peigh(hmat,unit_mat,thresh=1.e-10)
            e0=es[0]
            psi0=cs[:,0]
            #print 'psi0:' 
            #print psi0
            #print 'energy: ',e0
            # all matrices setup, solve linear response (complex)
            psi1=la.solve_perturb(omega-1j*delta,unit_mat,hmat,e0,psi0,perturb_mat,project=True)

            ph_gf=N.dot(N.conj(psi1),N.dot(perturb_mat,psi0))

            ph_gf0=_second_order_energy(hlat,nocc,perturb,omega+1j*delta)

            #print omega, ph_gf.imag,ph_gf0.imag
            print omega, ph_gf,2*ph_gf0,e0
            print >>fd, omega-mu, -ph_gf.imag,-2*ph_gf0.imag
Esempio n. 55
0
def PEAK_MIMO(w_start, w_end, error_poles_direction, wr, deadtime_if=0):
    '''
    This function is for multivariable system analysis of controllability.
    gives:
    minimum peak values on S and T with or without deadtime
    R is the expected worst case reference change, with condition that ||R||2<= 2
    wr is the frequency up to where reference tracking is required
    enter value of 1 in deadtime_if if system has dead time
    
    Parameters
    ----------
    var : type
        Description (optional).

    Returns
    -------
    var : type
        Description.
    '''

    # TODO use mimotf functions
    Zeros_G = zeros(G)
    Poles_G = poles(G)
    print('Poles: ' , Zeros_G)
    print('Zeros: ' , Poles_G)

    #just to save unnecessary calculations that is not needed
    #sensitivity peak of closed loop. eq 6-8 pg 224 skogestad

    if np.sum(Zeros_G)!= 0:
        if np.sum(Poles_G)!= 0:

            #two matrices to save all the RHP zeros and poles directions
            yz_direction = np.matrix(np.zeros([G(0.001).shape[0], len(Zeros_G)]))
            yp_direction = np.matrix(np.zeros([G(0.001).shape[0], len(Poles_G)]))


            for i in range(len(Zeros_G)):

                [U, S, V] = np.linalg.svd(G(Zeros_G[i]+error_poles_direction))
                yz_direction[:, i] = U[:, -1]


            for i in range(len(Poles_G)):
                #error_poles_direction is to to prevent the numerical method from breaking
                [U, S, V] = np.linalg.svd(G(Poles_G[i]+error_poles_direction))
                yp_direction[:, i] = U[:, 0]

            yz_mat1 = np.matrix(np.diag(Zeros_G))*np.matrix(np.ones([len(Zeros_G), len(Zeros_G)]))
            yz_mat2 = yz_mat1.T

            Qz = (yz_direction.H*yz_direction)/(yz_mat1+yz_mat2)

            yp_mat1 = np.matrix(np.diag(Poles_G))*np.matrix(np.ones([len(Poles_G), len(Poles_G)]))
            yp_mat2 = yp_mat1.T

            Qp = (yp_direction.H*yp_direction)/(yp_mat1+yp_mat2)

            yzp_mat1 = np.matrix(np.diag(Zeros_G))*np.matrix(np.ones([len(Zeros_G), len(Poles_G)]))
            yzp_mat2 = np.matrix(np.ones([len(Zeros_G), len(Poles_G)]))*np.matrix(np.diag(Poles_G))

            Qzp = yz_direction.H*yp_direction/(yzp_mat1-yzp_mat2)

            if deadtime_if==0:
                #this matrix is the matrix from which the SVD is going to be done to determine the final minimum peak
                pre_mat = (sc_lin.sqrtm((np.linalg.inv(Qz)))*Qzp*(sc_lin.sqrtm(np.linalg.inv(Qp))))

                #final calculation for the peak value
                Ms_min = np.sqrt(1+(np.max(np.linalg.svd(pre_mat)[1]))**2)
                print('')
                print('Minimum peak values on T and S without deadtime')
                print('Ms_min = Mt_min = ', Ms_min)
                print('')

            #Skogestad eq 6-16 pg 226 using maximum deadtime per output channel to give tightest lowest bounds
            if deadtime_if == 1:
                #create vector to be used for the diagonal deadtime matrix containing each outputs' maximum dead time
                #this would ensure tighter bounds on T and S
                #the minimum function is used because all stable systems have dead time with a negative sign

                dead_time_vec_max_row = np.zeros(deadtime()[0].shape[0])

                for i in range(deadtime()[0].shape[0]):
                    dead_time_vec_max_row[i] = np.max(deadtime()[0][i, :])


                def Dead_time_matrix(s, dead_time_vec_max_row):

                    dead_time_matrix = np.diag(np.exp(np.multiply(dead_time_vec_max_row, s)))
                    return dead_time_matrix

                Q_dead = np.zeros([G(0.0001).shape[0], G(0.0001).shape[0]])

                for i in range(len(Poles_G)):
                    for j in range(len(Poles_G)):
                        denominator_mat= np.transpose(np.conjugate(yp_direction[:, i]))*Dead_time_matrix(Poles_G[i], dead_time_vec_max_row)*Dead_time_matrix(Poles_G[j], dead_time_vec_max_row)*yp_direction[:, j]
                        numerator_mat = Poles_G[i]+Poles_G[i]

                        Q_dead[i, j] = denominator_mat/numerator_mat

                #calculating the Mt_min with dead time
                lambda_mat = sc_lin.sqrtm(np.linalg.pinv(Q_dead))*(Qp+Qzp*np.linalg.pinv(Qz)*(np.transpose(np.conjugate(Qzp))))*sc_lin.sqrtm(np.linalg.pinv(Q_dead))

                Ms_min=np.real(np.max(np.linalg.eig(lambda_mat)[0]))
                print('')
                print('Minimum peak values on T and S without dead time')
                print('Dead time per output channel is for the worst case dead time in that channel')
                print('Ms_min = Mt_min = ', Ms_min)
                print('')

        else:
            print('')
            print('Minimum peak values on T and S')
            print('No limits on minimum peak values')
            print('')

    #check for dead time
    #dead_G = deadtime[0]
    #dead_gd = deadtime[1]

    #if np.sum(dead_G)!= 0:
        #therefore deadtime is present in the system therefore extra precautions need to be taken
        #manually set up the dead time matrix

    #    dead_m = np.zeros([len(Poles_G), len(Poles_G)])


    #    for i in range(len(Poles_G)):
    #        for j in range(len(Poles_G))
    #            dead_m

    #eq 6-48 pg 239 for plant with RHP zeros
    #checking alignment of disturbances and RHP zeros
    RHP_alignment = [np.abs(np.linalg.svd(G(RHP_Z+error_poles_direction))[0][:, 0].H*np.linalg.svd(Gd(RHP_Z+error_poles_direction))[1][0]*np.linalg.svd(Gd(RHP_Z+error_poles_direction))[0][:, 0]) for RHP_Z in Zeros_G]

    print('Checking alignment of process output zeros to disturbances')
    print('These values should be less than 1')
    print(RHP_alignment)
    print('')

    #checking peak values of KS eq 6-24 pg 229 np.linalg.svd(A)[2][:, 0]
    #done with less tight lower bounds
    KS_PEAK = [np.linalg.norm(np.linalg.svd(G(RHP_p+error_poles_direction))[2][:, 0].H*np.linalg.pinv(G(RHP_p+error_poles_direction)), 2) for RHP_p in Poles_G]
    KS_max = np.max(KS_PEAK)

    print('Lower bound on K')
    print('KS needs to larger than ', KS_max)
    print('')

    #eq 6-50 pg 240 from Skogestad
    #eg 6-50 pg 240 from Skogestad for simultanious disturbance matrix
    #Checking input saturation for perfect control for disturbance rejection
    #checking for maximum disturbance just at steady state

    [U_gd, S_gd, V_gd] = np.linalg.svd(Gd(0.000001))
    y_gd_max = np.max(S_gd)*U_gd[:, 0]
    mod_G_gd_ss = np.max(np.linalg.inv(G(0.000001))*y_gd_max)



    print('Perfect control input saturation from disturbances')
    print('Needs to be less than 1 ')
    print('Max Norm method')
    print('Checking input saturation at steady state')
    print('This is done by the worse output direction of Gd')
    print(mod_G_gd_ss)
    print('')

    #
    #
    #

    print('Figure 1 is for perfect control for simultaneous disturbances')
    print('All values on each of the graphs should be smaller than 1')
    print('')

    print('Figure 2 is the plot of G**1 gd')
    print('The values of this plot needs to be smaller or equal to 1')
    print('')


    w = np.logspace(w_start, w_end, 100)



    mod_G_gd = np.zeros(len(w))
    mod_G_Gd = np.zeros([np.shape(G(0.0001))[0], len(w)])

    for i in range(len(w)):
        [U_gd, S_gd, V_gd] = np.linalg.svd(Gd(1j*w[i]))
        gd_m = np.max(S_gd)*U_gd[:, 0]
        mod_G_gd[i] = np.max(np.linalg.pinv(G(1j*w[i]))*gd_m)

        mat_G_Gd = np.linalg.pinv(G(w[i]))*Gd(w[i])
        for j in range(np.shape(mat_G_Gd)[0]):
            mod_G_Gd[j, i] = np.max(mat_G_Gd[j, :])

    #def for subplotting all the possible variations of mod_G_Gd


    plot_freq_subplot(plt, w, np.ones([2, len(w)]), 'Perfect control Gd', 'r', 1)
    plot_freq_subplot(plt, w, mod_G_Gd, 'Perfect control Gd', 'b', 1)

    plt.figure(2)
    plt.title('Input Saturation for perfect control |inv(G)*gd|<= 1')
    plt.xlabel('w')
    plt.ylabel('|inv(G)* gd|')
    plt.semilogx(w, mod_G_gd)
    plt.semilogx([w[0], w[-1]], [1, 1])
    plt.semilogx(w[0], 1.1)

    #def G_gd(w):
    #    [U_gd, S_gd, V_gd] = np.linalg.svd(Gd(1j*w))
    #    gd_m = U_gd[:, 0]
    #    mod_G_gd[i] = np.max(np.linalg.inv(G(1j*w))*gd_m)-1
    #    return mod_G_gd

    #w_mod_G_gd_1 = sc_opt.fsolve(G_gd, 0.001)


    #print 'frequencies up to which input saturation would not occur'
    #print w_mod_G_gd_1


    print('Figure 3 is disturbance condition number')
    print('A large number indicates that the disturbance is in a bad direction')
    print('')
    #eq 6-43 pg 238 disturbance condition number
    #this in done over a frequency range to see if there are possible problems at higher frequencies
    #finding yd

    dist_condition_num = [np.linalg.svd(G(w_i))[1][0]*np.linalg.svd(np.linalg.pinv(G(w_i))[1][0]*np.linalg.svd(Gd(w_i))[1][0]*np.linalg.svd(Gd(w_i))[0][:, 0])[1][0] for w_i in w]

    plt.figure(3)
    plt.title('yd Condition number')
    plt.ylabel('condition number')
    plt.xlabel('w')
    plt.loglog(w, dist_condition_num)

    #
    #
    #

    print('Figure 4 is the singular value of an specific output with input and disturbance direction vector')
    print('The solid blue line needs to be large than the red line')
    print('This only needs to be checked up to frequencies where |u**H gd| >1')
    print('')

    #checking input saturation for acceptable control  disturbance rejection
    #equation 6-55 pg 241 in Skogestad
    #checking each singular values and the associated input vector with output direction vector of Gd
    #just for square systems for now

    #revised method including all the possibilities of outputs i
    store_rhs_eq = np.zeros([np.shape(G(0.0001))[0], len(w)])
    store_lhs_eq = np.zeros([np.shape(G(0.0001))[0], len(w)])

    for i in range(len(w)):
        for j in range(np.shape(G(0.0001))[0]):
            store_rhs_eq[j, i] = np.abs(np.linalg.svd(G(w[i]))[2][:, j].H*np.max(np.linalg.svd(Gd(w[i]))[1])*np.linalg.svd(Gd(w[i]))[0][:, 0])-1
            store_lhs_eq[j, i] = sc_lin.svd(G(w[i]))[1][j]

    plot_freq_subplot(plt, w, store_rhs_eq, 'Acceptable control eq6-55', 'r', 4)
    plot_freq_subplot(plt, w, store_lhs_eq, 'Acceptable control eq6-55', 'b', 4)

    #
    #
    #

    print('Figure 5 is to check input saturation for reference changes')
    print('Red line in both graphs needs to be larger than the blue line for values w < wr')
    print('Shows the wr up to where control is needed')
    print('')

    #checking input saturation for perfect control with reference change
    #eq 6-52 pg 241

    #checking input saturation for perfect control with reference change
    #another equation for checking input saturation with reference change
    #eq 6-53 pg 241

    plt.figure(5)
    ref_perfect_const_plot(G, reference_change(), 0.01, w_start, w_end)

    print('Figure 6 is the maximum and minimum singular values of G over a frequency range')
    print('Figure 6 is also the maximum and minimum singular values of Gd over a frequency range')
    print('Blue is the minimum values and Red is the maximum singular values')
    print('Plot of Gd should be smaller than 1 else control is needed at frequencies where Gd is bigger than 1')
    print('')

    #checking input saturation for acceptable control with reference change
    #added check for controllability is the minimum and maximum singular values of system transfer function matrix
    #as a function of frequency
    #condition number added to check for how prone the system would be to uncertainty

    singular_min_G = [np.min(np.linalg.svd(G(1j*w_i))[1]) for w_i in w]
    singular_max_G = [np.max(np.linalg.svd(G(1j*w_i))[1]) for w_i in w]
    singular_min_Gd = [np.min(np.linalg.svd(Gd(1j*w_i))[1]) for w_i in w]
    singular_max_Gd = [np.max(np.linalg.svd(Gd(1j*w_i))[1]) for w_i in w]
    condition_num_G = [np.max(np.linalg.svd(G(1j*w_i))[1])/np.min(np.linalg.svd(G(1j*w_i))[1]) for w_i in w]

    plt.figure(6)
    plt.subplot(311)
    plt.title('min_S(G(jw)) and max_S(G(jw))')
    plt.loglog(w, singular_min_G, 'b')
    plt.loglog(w, singular_max_G, 'r')

    plt.subplot(312)
    plt.title('Condition number of G')
    plt.loglog(w, condition_num_G)

    plt.subplot(313)
    plt.title('min_S(Gd(jw)) and max_S(Gd(jw))')
    plt.loglog(w, singular_min_Gd, 'b')
    plt.loglog(w, singular_max_Gd, 'r')
    plt.loglog([w[0], w[-1]], [1, 1])


    plt.show()

    return Ms_min
Esempio n. 56
0
def _spinify_vec(vec):
    sp_vec=utils.zeros([vec.shape[0]*2])
    for i in xrange(vec.shape[0]):
        sp_vec[2*i]=vec[i]            
        #sp_vec[2*i+1]=vec[i]
    return sp_vec
# which is dependant on the left eigenvectors.

# Calculate eigen vectors and pole vectors
val, vec = LA.eig(A, None, 1, 0, 0, 0)

n = lin.matrix_rank(c_matrix)

P = LA.solve_lyapunov(A, -B * B.T)


# Display results
print '\nThe transfer function realization is:'
print 'G(s) = '
print np.poly1d(G.num[0], variable='s')
print "----------------"
print np.poly1d(G.den, variable='s')

print '\n1) Eigenvalues are: p1 = ', val[0], 'and p2 = ', val[1]
print '   with eigenvectors: q1 = ', vec[:, 0], 'and q2 = ', vec[:, 1]
print '   Input pole vectors are: up1 = ', in_vecs[0], 'and up2 = ', in_vecs[1]

print '\n2) The controlabillity matrix has rank', n, 'and is given as:'
print c_matrix

print '\n3) The controllability Gramian ='
print '  ', P[0, :], '\n  ', P[1, :]

print '\nMore properties'
print "\nState Controllable: " + str(control)
print 'Zeros: {0}'.format(zeros(None, A, B, C, D))
Esempio n. 58
0
def pimp(nimp, nlat):
    ret=utils.zeros([nlat,nlat])
    for i in xrange(nimp):
        ret[i,i]=1.
    return ret
Esempio n. 59
0
def _unspinify(sp_mat):
    mat=utils.zeros([sp_mat.shape[0]/2,sp_mat.shape[1]/2])
    for i in xrange(mat.shape[0]):
        for j in xrange(mat.shape[1]):
            mat[i,j]=sp_mat[2*i,2*j]
    return mat
Esempio n. 60
0
def himp_ext_matrix_form(hcs_imp,hds_ext,hds_imp,hcs_ext,ops_configs,cocc,vocc):
    # matrix elements of cross terms 
    # sum < |  hcs_imp otimes hds_ext | > + < | hds_imp otimes hcs_ext | >
    assert not len(cocc) & 1, "parities assume even #els in core"

    start={}
    end={}
    nconfigs=[len(configs) for (ops, configs) in ops_configs]
    ops=[opi for (opi, configi) in ops_configs]
    for i, opi in enumerate(ops):
        start[opi]=sum(nconfigs[:i])
        end[opi]=start[opi]+nconfigs[i]

    full_mat=utils.zeros([sum(nconfigs),sum(nconfigs)])

    for i, (opi, configi) in enumerate(ops_configs):
        opit=opi.t()
        for j, (opj, configj) in enumerate(ops_configs):
            for hc_imp, hd_ext in zip(hcs_imp,hds_ext):
                # <a1 b1.core|cimp dext|b2.core a2>: 
                # parity =-1 if fermion(b1) and core is even
                if isinstance(opit,models.Unit) and isinstance(opj,models.ContractedC):
                    mat_imp=qoperator.matrix_form(hc_imp,configi,configj)                    
                    val=eval_hd_cv(hd_ext,opj,cocc,vocc)
                    full_mat[start[opi]:end[opi],start[opj]:end[opj]]+=mat_imp*val

                elif isinstance(opit,models.ContractedCD) and isinstance(opj,models.ContractedC):
                    mat_imp=qoperator.matrix_form(hc_imp,configi,configj)                    
                    val=eval_codv_hd_cv(opit,hd_ext,opj,cocc,vocc)
                    full_mat[start[opi]:end[opi],start[opj]:end[opj]]+=mat_imp*val

                # parity is -1, since b1 is fermionic
                elif isinstance(opit,models.ContractedC) and isinstance(opj,models.Unit):
                    mat_imp=qoperator.matrix_form(hc_imp,configi,configj)                    
                    val=-eval_co_hd(opit,hd_ext,cocc,vocc) # parity=-1
                    full_mat[start[opi]:end[opi],start[opj]:end[opj]]+=mat_imp*val

                elif isinstance(opit,models.ContractedC) and isinstance(opj,models.ContractedCD):
                    mat_imp=qoperator.matrix_form(hc_imp,configi,configj)                    
                    val=-eval_co_hd_cvdo(opit,hd_ext,opj,cocc,vocc) #parity=-1
                    full_mat[start[opi]:end[opi],start[opj]:end[opj]]+=mat_imp*val

            for hd_imp, hc_ext in zip(hds_imp,hcs_ext):
                # <a1 b1.core|cext dimp|b2.core a2>: 
                # parity =-1 if fermion(b2) and core is even
                if isinstance(opit,models.Unit) and isinstance(opj,models.ContractedD):
                    mat_imp=qoperator.matrix_form(hd_imp,configi,configj)                    
                    val=-eval_hc_do(hc_ext,opj,cocc,vocc) # parity=-1
                    full_mat[start[opi]:end[opi],start[opj]:end[opj]]+=mat_imp*val

                elif isinstance(opit,models.ContractedCD) and isinstance(opj,models.ContractedD):
                    mat_imp=qoperator.matrix_form(hd_imp,configi,configj)                    
                    val=-eval_codv_hc_do(opit,hc_ext,opj,cocc,vocc) # parity=-1
                    full_mat[start[opi]:end[opi],start[opj]:end[opj]]+=mat_imp*val

                elif isinstance(opit,models.ContractedD) and isinstance(opj,models.Unit):
                    mat_imp=qoperator.matrix_form(hd_imp,configi,configj)                    
                    val=eval_dv_hc(opit,hc_ext,cocc,vocc) 
                    full_mat[start[opi]:end[opi],start[opj]:end[opj]]+=mat_imp*val

                elif isinstance(opit,models.ContractedD) and isinstance(opj,models.ContractedCD):
                    mat_imp=qoperator.matrix_form(hd_imp,configi,configj)                    
                    val=eval_dv_hc_cvdo(opit,hc_ext,opj,cocc,vocc) 
                    full_mat[start[opi]:end[opi],start[opj]:end[opj]]+=mat_imp*val
                
    return full_mat