Beispiel #1
0
    def calc_K_l(self, n_low=-1, n_high=-1):
        """Generates the K matrices used to calculate the B's.
        For the left gauge-fixing case.
        """
        if n_low < 2:
            n_low = 2
        if n_high < 1:
            n_high = self.N
            
        self.K[1] = sp.zeros((self.D[1], self.D[1]), dtype=self.typ)
            
        for n in xrange(n_low, n_high + 1):
            #if n <= self.N - self.ham_sites + 1:
            if self.ham_sites == 2:
                self.K[n], ex = tm.calc_K_l(self.K[n - 1], self.C[n - 1], self.l[n - 2], 
                                          self.r[n], self.A[n], self.A[n - 1], 
                                          sanity_checks=self.sanity_checks)
            else:
                assert False, 'left gauge fixing not yet supported for three-site Hamiltonians'

            self.h_expect[n - 1] = ex
            #else:
            #    self.K[n].fill(0)
                
        if n_high == self.N:
            self.H_expect = sp.asscalar(self.K[self.N])
Beispiel #2
0
    def calc_K_l(self, n_low=-1, n_high=-1):
        """Generates the K matrices used to calculate the B's.
        For the left gauge-fixing case.
        """
        if n_low < 2:
            n_low = 2
        if n_high < 1:
            n_high = self.N
            
        self.K[1] = sp.zeros((self.D[1], self.D[1]), dtype=self.typ)
            
        for n in xrange(n_low, n_high + 1):
            #if n <= self.N - self.ham_sites + 1:
            if self.ham_sites == 2:
                self.K[n], ex = tm.calc_K_l(self.K[n - 1], self.C[n - 1], self.l[n - 2], 
                                            self.r[n], self.A[n], self.AA[n - 1])
            else:
                assert False, 'left gauge fixing not yet supported for three-site Hamiltonians'

            self.h_expect[n - 1] = ex
            #else:
            #    self.K[n].fill(0)
                
        if n_high == self.N:
            self.H_expect = sp.asscalar(self.K[self.N])
Beispiel #3
0
    def calc_K_diss(self, LB, LC, n_low=-1, n_high=-1):
        """Generates the K matrices used to calculate the B's.
        
        This is called automatically by self.update().
        
        K[n] is contains the action of the Hamiltonian on sites n to N.
        
        K[n] is recursively defined. It depends on C[m] and A[m] for all m >= n.
        
        It directly depends on A[n], A[n + 1], r[n], r[n + 1], C[n] and K[n + 1].
        
        This is equivalent to K on p. 14 of arXiv:1103.0936v2 [cond-mat.str-el], except 
        that it is for the non-norm-preserving case.
        
        K[1] is, assuming a normalized state, the expectation value H of Ĥ.
        """
        #print "Calc_K_diss started..."
        if LB is None:
            return 0

        if n_low < 1:
            n_low = 1
        if n_high < 1:
            n_high = self.N

        # Initialize LK with K and then update it from there.
        LK = self.K
        for n in reversed(xrange(n_low, n_high + 1)):
            if n <= self.N - self.ham_sites + 1:
                if self.ham_sites == 2:
                    """                    
                    print "Conjecture: Error appears here:"
                    print "n is", n
                    print "Printing  shapes of A[n], A[n+1]."
                    print self.A[n].shape
                    print self.A[n + 1].shape
                    #AA = tm.calc_AA(self.A[n], self.A[n + 1])
                    #print AA.shape
                    print "Should be (2,1) or (2,2)..."
                    print "LK[n+1]", LK[n+1]
                    print LK[n+1].shape
                    """
                    LK[n], ex = self.calc_K_common(LK[n + 1], LC[n],
                                                   self.l[n - 1],
                                                   self.r[n + 1], self.A[n],
                                                   self.A[n + 1])
                else:
                    assert False, "3-Site interaction detected. Not implemented for the dissipative case!"
                    LK[n], ex = tm.calc_K_3s(self.K[n + 1], LC[n],
                                             self.l[n - 1], self.r[n + 2],
                                             self.A[n], self.AAA[n])

                self.h_expect[n] = ex
            else:
                self.K[n].fill(0)

        if n_low == 1:
            self.H_expect = sp.asscalar(LK[1])
        return LK
Beispiel #4
0
def contract(A, B):
    M0 = sp.dot(H(A[1][0]), B[1][0]) + sp.dot(H(A[1][1]), B[1][1])
    N = sp.shape(A)[0]
    for n in range(2, N):
        Ml = A[n]
        Mr = B[n]
        out = mult_3(H(Ml[0]), M0, Mr[0]) + mult_3(H(Ml[1]), M0, Mr[1])
        M0 = out
    return sp.asscalar(M0)
Beispiel #5
0
    def calc_K_diss(self, LB, LC, n_low=-1, n_high=-1):
        """Generates the K matrices used to calculate the B's.
        
        This is called automatically by self.update().
        
        K[n] is contains the action of the Hamiltonian on sites n to N.
        
        K[n] is recursively defined. It depends on C[m] and A[m] for all m >= n.
        
        It directly depends on A[n], A[n + 1], r[n], r[n + 1], C[n] and K[n + 1].
        
        This is equivalent to K on p. 14 of arXiv:1103.0936v2 [cond-mat.str-el], except 
        that it is for the non-norm-preserving case.
        
        K[1] is, assuming a normalized state, the expectation value H of Ĥ.
        """
        #print "Calc_K_diss started..."
        if LB is None:
            return 0        
        
        if n_low < 1:
            n_low = 1
        if n_high < 1:
            n_high = self.N
            
        # Initialize LK with K and then update it from there.
        LK = self.K
        for n in reversed(xrange(n_low, n_high + 1)):
            if n <= self.N - self.ham_sites + 1:
                if self.ham_sites == 2:
                    """                    
                    print "Conjecture: Error appears here:"
                    print "n is", n
                    print "Printing  shapes of A[n], A[n+1]."
                    print self.A[n].shape
                    print self.A[n + 1].shape
                    #AA = tm.calc_AA(self.A[n], self.A[n + 1])
                    #print AA.shape
                    print "Should be (2,1) or (2,2)..."
                    print "LK[n+1]", LK[n+1]
                    print LK[n+1].shape
                    """
                    LK[n], ex = self.calc_K_common(LK[n + 1], LC[n], self.l[n - 1], 
                                              self.r[n + 1], self.A[n], self.A[n + 1])
                else:
                    assert False, "3-Site interaction detected. Not implemented for the dissipative case!"
                    LK[n], ex = tm.calc_K_3s(self.K[n + 1], LC[n], self.l[n - 1], 
                                              self.r[n + 2], self.A[n], self.AAA[n])

                self.h_expect[n] = ex
            else:
                self.K[n].fill(0)
                
        if n_low == 1:
            self.H_expect = sp.asscalar(LK[1])
        return LK
Beispiel #6
0
def contract(A, B):
    M0 = sp.dot(matmul.H(A[1][0]), B[1][0]) + sp.dot(matmul.H(A[1][1]),
                                                     B[1][1])
    for n in range(2, N + 1):
        Ml = A[n]
        Mr = B[n]
        out = mult(matmul.H(Ml[0]), M0, Mr[0]) + mult(matmul.H(Ml[1]), M0,
                                                      Mr[1])
        M0 = out
    return sp.asscalar(M0)
Beispiel #7
0
def align_image_local_optim(image, target, T, PF=None, plot=False, **kws):

    rescale = kws.pop("rescale", 1)  # Extract and remove "rescale" from kws and if not in there, default to 1

    if PF is None:
        PF = PatternFinder(partitions=10)

    # Convert initialGuess transformation matrix into an ndarray with six entries for the DOFs
    # initialGuess = sp.asarray([sp.asscalar(T.translation[0]),
    #                            sp.asscalar(T.translation[1]),
    #                            T.rotation])
    initialGuess = sp.asarray([sp.asscalar(T.translation[0]),
                               sp.asscalar(T.translation[1]),
                               T.rotation,T.scale[0],T.scale[1],T.shear])

    target_scaled = transform.rescale(target, rescale)
    im_scaled = transform.rescale(image, rescale)

    # Set (and upload to GPU) the image already now,
    # because during optimization it is not changed at all.
    PF.set_image(im_scaled)

#     if plot==True:
    logger = logging.getLogger('stackalign')
    #Calculate normalized error
    logger.info(print_parameters(T,
                                 loss_fcn(initialGuess, PF, target_scaled, im_scaled, rescale, plot)))

    res = sp.optimize.minimize(loss_fcn,
                               initialGuess,
                               args=(PF, target_scaled, im_scaled, rescale, plot),
                               method='BFGS',
                               **kws)

    final_trans = transform.AffineTransform (rotation=res.x[2],shear=res.x[5],
                                             scale=[res.x[3],res.x[4]],translation=[res.x[0],res.x[1]])
    # final_trans = transform.AffineTransform (rotation=res.x[2], translation=[res.x[0],res.x[1]])


    logger.info(print_parameters(final_trans, res.fun))

    return final_trans, res
Beispiel #8
0
 def jacobian_det(self, reference_point):
     jac = self.jacobian(reference_point)
     if sp.isscalar(jac):
         return jac
     elif sp.all(sp.array(jac.shape) == 1):
         # an array with only one entry
         return sp.asscalar(jac)
     elif len(jac.shape) == 1 or jac.shape[0] == 1 or jac.shape[1] == 1:
         return sp.linalg.norm(jac)
     elif jac.shape[0] == jac.shape[1]:
         # a square matrix
         return spl.det(jac)
     else:
         raise NotImplementedError("Computing Jacobian \"determinant\" not implemented for shpae=({0:d}, {1:d})"
                                   .format(jac.shape))
Beispiel #9
0
    def calc_K(self, n_low=-1, n_high=-1):
        """Generates the K matrices used to calculate the B's.
        
        This is called automatically by self.update().
        
        K[n] is contains the action of the Hamiltonian on sites n to N.
        
        K[n] is recursively defined. It depends on C[m] and A[m] for all m >= n.
        
        It directly depends on A[n], A[n + 1], r[n], r[n + 1], C[n] and K[n + 1].
        
        This is equivalent to K on p. 14 of arXiv:1103.0936v2 [cond-mat.str-el], except 
        that it is for the non-norm-preserving case.
        
        K[1] is, assuming a normalized state, the expectation value H of Ĥ.
        """
        if n_low < 1:
            n_low = 1
        if n_high < 1:
            n_high = self.N
            
        for n in reversed(xrange(n_low, n_high + 1)):
            if n <= self.N - self.ham_sites + 1:
                if self.ham_sites == 2:
                    self.K[n], ex = tm.calc_K(self.K[n + 1], self.C[n], self.l[n - 1], 
                                              self.r[n + 1], self.A[n], self.A[n + 1], 
                                              sanity_checks=self.sanity_checks)
                else:
                    self.K[n], ex = tm.calc_K_3s(self.K[n + 1], self.C[n], self.l[n - 1], 
                                              self.r[n + 2], self.A[n], self.A[n + 1], 
                                              self.A[n + 2],
                                              sanity_checks=self.sanity_checks)

                self.h_expect[n] = ex
            else:
                self.K[n].fill(0)
                
        if n_low == 1:
            self.H_expect = sp.asscalar(self.K[1])
    def append(self, item_list):
        """append to the container the contents of a SimPkg
        
        will only append up to the cnklen!
        
        :Parameters:
            item_list : list
                The contents of a T_REC package.
        :Return:
            list: if append was ok and did not overshoot the chunk length the
                  list will be empty! Else the residual item_list is returned.        """

        # checks
        if len(item_list) == 0:
            raise ValueError(
                'contents have to include at least the noise strip')
        if (len(item_list) - 1) % 3 != 0:
            raise ValueError(
                'invalid content count! has to be noise + 3tuples')
        # TODO: more checks ?
        # prepare
        rval = []
        noise = item_list.pop(0)
        if isinstance(noise, (N.ndarray, None.__class__)):
            if isinstance(noise, None.__class__):
                thislen = 0
            else:
                appendlen, nchan = noise.shape
                if self.noise is None:
                    self.noise = N.empty((self.cnklen, nchan))
                # normal append case
                thislen = appendlen
                if self.cnkptr + thislen >= self.cnklen:
                    thislen = self.cnklen - self.cnkptr
                # append noise
                copy_ar(noise, slice(0, thislen), self.noise,
                        slice(self.cnkptr, self.cnkptr + thislen))
                if thislen != appendlen:
                    rval.append(noise[thislen:, :].copy())
        else:
            thislen = 0
            item_list.insert(0, noise)
        # append unit data
        while len(item_list) > 0:
            # get data
            ident = item_list.pop(0)
            if isinstance(ident, N.ndarray):
                ident = N.asscalar(ident)
            wform = item_list.pop(0)
            gtrth = item_list.pop(0)
            if len(gtrth) == 0:
                continue
                # weird but it happens :/
            # do we know this ident?
            if ident not in self.units:
                self.units[ident] = {'wf_buf': [], 'gt_buf': []}
            # handle waveform
            wform_key = -1
            for i in xrange(len(self.units[ident]['wf_buf'])):
                if N.allclose(wform, self.units[ident]['wf_buf'][i]):
                    wform_key = i
                    break
            if wform_key == -1:
                self.units[ident]['wf_buf'].append(wform)
                wform_key = len(self.units[ident]['wf_buf']) - 1
            # handle ground truth
            gtrth_resid = []
            for item in gtrth:
                # interval out of scope
                if item[0] + self.cnkptr > self.cnklen:
                    gtrth_resid.append([
                        item[0] - thislen, item[1] - thislen, item[2], item[3]
                    ])
                # interval ok, but end out of scope
                elif item[1] + self.cnkptr > self.cnklen:
                    self.units[ident]['gt_buf'].append([
                        wform_key, item[0] + self.cnkptr, self.cnklen, item[2],
                        thislen - item[0] + item[2]
                    ])
                    gtrth_resid.append([
                        0, item[1] - thislen, thislen - item[0] + item[2],
                        item[3]
                    ])
                else:
                    self.units[ident]['gt_buf'].append([
                        wform_key, item[0] + self.cnkptr,
                        item[1] + self.cnkptr, item[2], item[3]
                    ])
            # rval building
            if len(gtrth_resid) > 0:
                gtrth_resid = N.vstack(gtrth_resid)
                rval.extend([ident, wform, gtrth_resid])
                if not isinstance(rval[0], (N.ndarray, None.__class__)):
                    rval.insert(0, None)
        # return
        self.cnkptr += thislen
        if self.cnkptr >= self.cnklen:
            self._finalized = True
            if self.cnkptr > self.cnklen:
                print '!! CNKPTR[%s] > CNKLEN[%s] !!' % (self.cnkptr,
                                                         self.cnklen)
        return rval
    def append(self, item_list):
        """append to the container the contents of a SimPkg
        
        will only append up to the cnklen!
        
        :Parameters:
            item_list : list
                The contents of a T_REC package.
        :Return:
            list: if append was ok and did not overshoot the chunk length the
                  list will be empty! Else the residual item_list is returned.        """

        # checks
        if len(item_list) == 0:
            raise ValueError("contents have to include at least the noise strip")
        if (len(item_list) - 1) % 3 != 0:
            raise ValueError("invalid content count! has to be noise + 3tuples")
        # TODO: more checks ?
        # prepare
        rval = []
        noise = item_list.pop(0)
        if isinstance(noise, (N.ndarray, None.__class__)):
            if isinstance(noise, None.__class__):
                thislen = 0
            else:
                appendlen, nchan = noise.shape
                if self.noise is None:
                    self.noise = N.empty((self.cnklen, nchan))
                # normal append case
                thislen = appendlen
                if self.cnkptr + thislen >= self.cnklen:
                    thislen = self.cnklen - self.cnkptr
                # append noise
                copy_ar(noise, slice(0, thislen), self.noise, slice(self.cnkptr, self.cnkptr + thislen))
                if thislen != appendlen:
                    rval.append(noise[thislen:, :].copy())
        else:
            thislen = 0
            item_list.insert(0, noise)
        # append unit data
        while len(item_list) > 0:
            # get data
            ident = item_list.pop(0)
            if isinstance(ident, N.ndarray):
                ident = N.asscalar(ident)
            wform = item_list.pop(0)
            gtrth = item_list.pop(0)
            if len(gtrth) == 0:
                continue
                # weird but it happens :/
            # do we know this ident?
            if ident not in self.units:
                self.units[ident] = {"wf_buf": [], "gt_buf": []}
            # handle waveform
            wform_key = -1
            for i in xrange(len(self.units[ident]["wf_buf"])):
                if N.allclose(wform, self.units[ident]["wf_buf"][i]):
                    wform_key = i
                    break
            if wform_key == -1:
                self.units[ident]["wf_buf"].append(wform)
                wform_key = len(self.units[ident]["wf_buf"]) - 1
            # handle ground truth
            gtrth_resid = []
            for item in gtrth:
                # interval out of scope
                if item[0] + self.cnkptr > self.cnklen:
                    gtrth_resid.append([item[0] - thislen, item[1] - thislen, item[2], item[3]])
                # interval ok, but end out of scope
                elif item[1] + self.cnkptr > self.cnklen:
                    self.units[ident]["gt_buf"].append(
                        [wform_key, item[0] + self.cnkptr, self.cnklen, item[2], thislen - item[0] + item[2]]
                    )
                    gtrth_resid.append([0, item[1] - thislen, thislen - item[0] + item[2], item[3]])
                else:
                    self.units[ident]["gt_buf"].append(
                        [wform_key, item[0] + self.cnkptr, item[1] + self.cnkptr, item[2], item[3]]
                    )
            # rval building
            if len(gtrth_resid) > 0:
                gtrth_resid = N.vstack(gtrth_resid)
                rval.extend([ident, wform, gtrth_resid])
                if not isinstance(rval[0], (N.ndarray, None.__class__)):
                    rval.insert(0, None)
        # return
        self.cnkptr += thislen
        if self.cnkptr >= self.cnklen:
            self._finalized = True
            if self.cnkptr > self.cnklen:
                print "!! CNKPTR[%s] > CNKLEN[%s] !!" % (self.cnkptr, self.cnklen)
        return rval