Esempio n. 1
0
    def _get_irreps(self):
        eigvecs = []
        phases = np.kron(
            [np.exp(2j * np.pi * np.dot(self._q, pos))
             for pos in self._primitive.get_scaled_positions()], [1, 1, 1])
        for vec in self._eigvecs.T:
            eigvecs.append(vec * phases)

        irrep = []
        for band_indices in self._degenerate_sets:
            irrep_Rs = []
            for mat in self._ground_matrices:
                l = len(band_indices)

                if l == 1:
                    vec = eigvecs[band_indices[0]]
                    irrep_Rs.append([[np.vdot(vec, np.dot(mat, vec))]])
                    continue
                
                irrep_R = np.zeros((l, l), dtype=complex)
                for i, b_i in enumerate(band_indices):
                    vec_i = eigvecs[b_i]
                    for j, b_j in enumerate(band_indices):
                        vec_j = eigvecs[b_j]
                        irrep_R[i, j] = np.vdot(vec_i, np.dot(mat, vec_j))
                irrep_Rs.append(irrep_R)

            irrep.append(irrep_Rs)

        return irrep
Esempio n. 2
0
File: neb.py Progetto: bwibbwz/dimer
 def update_tangents(self):
     images = self.images
     t_m = images[1].get_positions() - images[0].get_positions()
     self.tangents[0] = t_m.copy()
     for i in range(1, self.nimages - 1):
         t_p = (images[i + 1].get_positions() - images[i].get_positions())
         e = self.energies[i]
         e_m = self.energies[i - 1]
         e_p = self.energies[i + 1]
         # NB: Check the below definition, it might have been flipped to use the lower energy tangent.
         if e < e_m and e > e_p:
             t = t_m.copy()
         elif e > e_m and e < e_p:
             t = t_p.copy()
         else:
             # BUG: Possible error when end images become highest.
             e_max = max(abs(e_p - e), abs(e_m - e))
             e_min = min(abs(e_p - e), abs(e_m - e))
             if e_p > e_m:
                 t = t_p * e_max + t_m * e_min
             else:
                 t = t_p * e_min + t_m * e_max
             t /= np.vdot(t, t)**0.5
             t *= (np.vdot(t_m, t_m)**0.5 + np.vdot(t_p, t_p)**0.5) / 2.0
         self.tangents[i] = t
         t_m = t_p
     self.tangents[-1] = t_m.copy()
Esempio n. 3
0
    def testMCMCFitting(self):
        print "starting mcmc"
        true, data = self.generate_data()
        model = HDPMixtureModel(3,100,100,1)
        model.seed = 1
        start = time()
        r = model.fit(data, verbose=10)
#        end = time() - start
#        print r.pis.shape
#        print r.pis, r.pis[0]
#        print r[0],r[0].pis
        print r.mus
        self.assertEqual(len(r), 2, 'results are the wrong length: %d' %len(r))
        diffs = {}
        #print 'r.mus:', r.mus()
        for i in gen_mean:
            diffs[i] = np.min(np.abs(r[0].mus-gen_mean[i]),0)
            #print r[0].mus[0], np.min(np.abs(r[0].mus[0]-gen_mean[i]),0)
            #diffs[i] = np.abs(r[0].mus()[i]-gen_mean[i])
            #print i, gen_mean[i],r[0].mus()[i], diffs[i], np.vdot(diffs[i],diffs[i])
            self.assertLessEqual( np.vdot(diffs[i],diffs[i]),1, 
                                  'diff to large: %f' % np.vdot(diffs[i], diffs[i]))
        
        for i in gen_mean:
            diffs[i] = np.min(np.abs(r[1].mus-gen_mean[i]),0)
            #diffs[i] = np.abs(r[1].mus()[i]-gen_mean[i])
            #print i, gen_mean[i],r[1].mus()[i], diffs[i], np.vdot(diffs[i],diffs[i])
            self.assertLessEqual( np.vdot(diffs[i],diffs[i]),1, 
                                  'diff to large: %f' % np.vdot(diffs[i], diffs[i]))
Esempio n. 4
0
    def test_integral_moment_first(self):
        lmax = 5 #XXX use meshgrid above l=5

        # Test first-order moments of the spherical harmonics
        for l1,m1 in lmiter(lmax, comm=world):
            s1_L = Y(l1, m1, theta_L, phi_L)
            for l2,m2 in lmiter(lmax):
                s2_L = Y(l2, m2, theta_L, phi_L)

                # Note that weights times surface area make up for sin(theta)
                v_ex = 4 * np.pi * np.vdot(s1_L, np.cos(phi_L) \
                    * np.sin(theta_L) * s2_L * weight_L)
                v_ey = 4 * np.pi * np.vdot(s1_L, np.sin(phi_L) \
                    * np.sin(theta_L) * s2_L * weight_L)
                v_ez = 4 * np.pi * np.vdot(s1_L, np.cos(theta_L) \
                    * s2_L * weight_L)

                v0_ex = intYY_ex(l1, m1, l2, m2)
                v0_ey = intYY_ey(l1, m1, l2, m2)
                v0_ez = intYY_ez(l1, m1, l2, m2)

                self.assertAlmostEqual(v_ex, v0_ex, 12, '%s != %s (l1=%2d, ' \
                    'm1=%2d, l2=%2d, m2=%2d)' % (v_ex,v0_ex,l1,m1,l2,m2))
                self.assertAlmostEqual(v_ey, v0_ey, 12, '%s != %s (l1=%2d, ' \
                    'm1=%2d, l2=%2d, m2=%2d)' % (v_ey,v0_ey,l1,m1,l2,m2))
                self.assertAlmostEqual(v_ez, v0_ez, 12, '%s != %s (l1=%2d, ' \
                    'm1=%2d, l2=%2d, m2=%2d)' % (v_ez,v0_ez,l1,m1,l2,m2))
Esempio n. 5
0
def neb_modify_force(band):
	peak_image = numpy.argmax(band.Energy)
	for i in xrange(1, band.nimages-1):
		# "improved" tangent calculation
		Forwards = putil.separation_vector_raw(band.Pos[(i+1)*3*band.NAtoms:(i+2)*3*band.NAtoms], band.Pos[(i)*3*band.NAtoms:(i+1)*3*band.NAtoms], band.PBC, band.Dim)
		Backwards = putil.separation_vector_raw(band.Pos[(i)*3*band.NAtoms:(i+1)*3*band.NAtoms], band.Pos[(i-1)*3*band.NAtoms:(i)*3*band.NAtoms], band.PBC, band.Dim)
		mForwards = putil.magnitude(Forwards)
		mBackwards = putil.magnitude(Backwards)
	
		if(band.Energy[i]>band.Energy[i-1] and band.Energy[i+1] > band.Energy[i]):
			norm = putil.normalise(Forwards)
		elif(band.Energy[i] < band.Energy[i-1] and band.Energy[i+1] < band.Energy[i]):
			norm = putil.normalise(Backwards)
		else:
			norm = putil.normalise(Backwards * math.fabs(band.Energy[i] - band.Energy[i-1]) + Forwards * math.fabs(band.Energy[i+1] - band.Energy[i]))

			
		# if climbing then move uphill independent of the rest of the band
		if(i==peak_image):
			band.Force[(i)*3*band.NAtoms:(i+1)*3*band.NAtoms] -= 2 * norm * numpy.vdot(band.Force[(i)*3*band.NAtoms:(i+1)*3*band.NAtoms], norm)
			
		else:
			# remove parallel component of real force
			band.Force[(i)*3*band.NAtoms:(i+1)*3*band.NAtoms] -= norm * numpy.vdot(band.Force[(i)*3*band.NAtoms:(i+1)*3*band.NAtoms], norm)
			# add in force due to the springs
			band.Force[(i)*3*band.NAtoms:(i+1)*3*band.NAtoms] += norm*(mForwards - mBackwards)*band.springk
			
		#band.mForce = numpy.absolute(band.Force).max()
		band.mForce = putil.magnitude(band.Force)
		band.peak_image = peak_image
		

		
	return band	
def adjointness_error(op, its=100):
    """Check adjointness of op.A and op.As for 'its' instances of random data.

    For random unit-normed x and y, this finds the error in the adjoint
    identity <Ax, y> == <x, A*y>:
        err = abs( vdot(A(x), y) - vdot(x, Astar(y)) ).

    The type and shape of the input to A are specified by inshape and indtype.

    Returns a vector of the error magnitudes.

    """
    inshape = op.inshape
    indtype = op.indtype
    outshape = op.outshape
    outdtype = op.outdtype

    x = get_random_normal(inshape, indtype)

    errs = np.zeros(its, dtype=indtype)
    for k in xrange(its):
        x = get_random_normal(inshape, indtype)
        x = x/np.linalg.norm(x)
        y = get_random_normal(outshape, outdtype)
        y = y/np.linalg.norm(y)
        ip_A = np.vdot(op.A(x), y)
        ip_Astar = np.vdot(x, op.As(y))
        errs[k] = np.abs(ip_A - ip_Astar)

    return errs
Esempio n. 7
0
    def braket(self, other, space="g"):
        """
        Returns the scalar product <u1|u2> of the periodic part of two wavefunctions 
        computed in G-space or r-space, depending on the value of space.

        Args:
            other: 
                Other wave (right-hand side)
            space: 
                Integration space. Possible values ["g", "gsphere", "r"]
                if "g" or "r" the scalar product is computed in G- or R-space on the FFT box.
                if space="gsphere" the integration is done on the G-sphere. Note that
                this option assumes that self and other have the same list of G-vectors. 
        """
        space = space.lower()

        if space == "g":  
            ug1_mesh = self.gsphere.tofftmesh(self.mesh, self.ug)
            ug2_mesh = other.gsphere.tofftmesh(self.mesh, other.ug)
            return np.vdot(ug1_mesh, ug2_mesh)

        elif space == "gsphere":
            return np.vdot(self.ug, other.ug)

        elif space == "r":
            return np.vdot(self.ur, other.ur) * self.mesh.dv

        else:
            raise ValueError("Wrong space: %s" % space)
Esempio n. 8
0
    def  __compute_velocities_at_collision(obj1, obj2):

        v_obj1 = np.array([obj1.velocity.x, obj1.velocity.y], dtype=np.float64)
        v_obj2 = np.array([obj2.velocity.x, obj2.velocity.y], dtype=np.float64)

        v_normal = np.array([v_obj1[0] - v_obj2[0], v_obj1[1] - v_obj2[1]])
        #print v_obj1, v_obj2
        #print v_normal

        if not np.linalg.norm(v_normal):
            #print "No colision..."
            return obj1.velocity, obj2.velocity

        v_unit_normal = np.divide(v_normal, np.linalg.norm(v_normal))
        v_unit_tangent = np.array([-1*v_unit_normal[1], v_unit_normal[0]])

        v_obj1_normal = np.vdot(v_unit_normal, v_obj1)
        v_obj1_tangent = np.vdot(v_unit_tangent, v_obj1)
        v_obj2_normal = np.vdot(v_unit_normal, v_obj2)
        v_obj2_tangent = np.vdot(v_unit_tangent, v_obj2)

        v_obj1_new_normal = (v_obj1_normal*(obj1.mass - obj2.mass) + 2*obj2.mass*v_obj2_normal)/(obj1.mass + obj2.mass)
        v_obj2_new_normal = (v_obj2_normal*(obj2.mass - obj1.mass) + 2*obj1.mass*v_obj1_normal)/(obj1.mass + obj2.mass)

        vec_obj1_normal = np.dot(v_obj1_new_normal, v_unit_normal)
        vec_obj1_tangent = np.dot(v_obj1_tangent, v_unit_tangent)
        vec_obj2_normal = np.dot(v_obj2_new_normal, v_unit_normal)
        vec_obj2_tangent = np.dot(v_obj2_tangent, v_unit_tangent)

        v_obj1_final = np.add(vec_obj1_normal, vec_obj1_tangent)
        v_obj2_final = np.add(vec_obj2_normal, vec_obj2_tangent)

        return Velocity(v_obj1_final[0], v_obj1_final[1]), Velocity(v_obj2_final[0], v_obj2_final[1])
Esempio n. 9
0
    def calc_orbital_params(self):
        #Calculates Keplerian orbital parameters based on the state vectors
        #This method should be called after each change to velocity vector

        #a = - mu / (v^2 - 2 * mu/r)
        v_2 = numpy.vdot(self.v, self.v)
        r_ = numpy.linalg.norm(self.r)
        # TODO: this won't work for parabolic trajectories (as the denominator is 0)!
        self.a = -EARTH_MU / (v_2 - 2 * EARTH_MU / r_)

        #T = 2*Pi*sqrt(a^3/ni)
        # TODO: again, orbital period is not defined for non-bound orbits
        self.T = 2.0 * numpy.pi * numpy.sqrt(self.a**3 / EARTH_MU)

        #Calculate specific relative angular momentum h = r X v
        h = numpy.cross(self.r, self.v)
        h_2 = numpy.vdot(h, h)
        h_ = numpy.sqrt(h_2)

        #Calculate eccentricity vector e = (v X h) / EARTH_MU - r/|r|
        e = numpy.cross(self.v, h) / EARTH_MU - self.r/r_
        self.e = numpy.linalg.norm(e)

        i_rad = numpy.arccos(h[2] / h_) #h[2] = hz
        self.i = numpy.degrees(i_rad)
        #However, some soruces state that if hz < 0 then inclination is 180 deg - i; should check this
        #n is the vector pointing to the ascending node
        n = numpy.array((-h[1], h[0], 0))
        n_ = numpy.linalg.norm(n)
        if i_rad == 0.0:
            o_rad = 0.0
        else:
            if n[1] >= 0.0: #ie. if h[0] >= 0
                o_rad = numpy.arccos(n[0] / n_)
            else:
                o_rad = 2 * numpy.pi - numpy.arccos(n[0] / n_)
        self.o = numpy.degrees(o_rad)

        #Calculate ni (true anomaly)
        q = numpy.vdot(self.r, self.v) #What the hell is q?
        ni_x = h_2 / (r_ * EARTH_MU) - 1.0
        ni_y = h_ * q / (r_ * EARTH_MU)
        self.ni = numpy.degrees(numpy.arctan2(ni_y, ni_x))

        if self.e == 0.0:
            #For circular orbit w is 0 by convention
            self.w = 0.0
        else:
            if n_ == 0.0:
                #For equatorial orbit
                self.w = numpy.degrees(numpy.arctan2(e[1], e[0]))
            else:
                self.w = numpy.degrees(numpy.arccos(numpy.vdot(n, e) / (n_ * self.e)))
        if e[2] < 0.0:
            self.w = 360.0 - self.w
        if self.w < 0.0:
            self.w = 360.0 + self.w

        self.rp = self.a * (1.0 - self.e) #Periapsis distance
        self.ra = self.a * (1.0 + self.e) #Apoapsis distance
Esempio n. 10
0
    def step(self, f):
        coords = self.coords
        if self.v is None:
            self.v = np.zeros((len(coords)))
        else:
            vf = np.vdot(f, self.v)
            if vf > 0.0:
                self.v = (1.0 - self.a) * self.v + self.a * f / np.sqrt(
                    np.vdot(f, f)) * np.sqrt(np.vdot(self.v, self.v))
                if self.Nsteps > self.Nmin:
                    self.dt = min(self.dt * self.finc, self.dtmax)
                    self.a *= self.fa
                self.Nsteps += 1
            else:
                self.v[:] *= 0.0
                self.a = self.astart
                self.dt *= self.fdec
                self.Nsteps = 0

        self.v += self.dt * f
        dr = self.dt * self.v
        if False:  # how do we determine maxstep?
            normdr = np.sqrt(np.vdot(dr, dr))
        else:
            normdr = max(np.abs(dr))
        if normdr > self.maxstep:
            dr = self.maxstep * dr / normdr
        self.coords = coords + dr
Esempio n. 11
0
def check_weights( weights, edges, vol, tol=1.0e-14 ):
    '''Check if the given weights are correct.'''

    print 'Checking weights %g, %g, %g...' % (weights[0], weights[1], weights[2]),

    # try out the weight with a bunch of other random vectors
    m = 1000
    found_mismatch = False
    for i in xrange(m):
        u = np.random.rand(2) + 1j * np.random.rand(2)
        v = np.random.rand(2) + 1j * np.random.rand(2)

        control_value = np.vdot(u, v) * vol
        p1 = 0.0
        for j in xrange(3):
            p1 += np.vdot(u, edges[j]) * np.vdot(edges[j], v) * weights[j]

        err = abs(control_value-p1)
        if err > tol:
            found_mismatch = True;
            print 'Found mismatch by %g.\n' % err
            break

    if not found_mismatch:
        print 'Cool.'

    return
Esempio n. 12
0
def bilinear_concentric_potential(r_g, dr_g, f_g, ft_g, l1, l2, alpha, rfilt=None):
    """Calculate corrections for concentric functions and potentials::

                 /     _   _a    _   _a    ~   _   _a  ~ _   _a   _
        v      = | f  (r - R ) V(r - R ) - f  (r - R ) V(r - R ) dr
         m1,m2   /  L1,L2                    L1,L2

    where f(r) and ft(r) are bilinear product of two localized functions which
    are radial splines times real spherical harmonics (l1,m1) or (l2,m2) and::

          _       1       _ -1              ~ _    erf(alpha*r)  _ -1
        V(r) = --------- |r|        ^       V(r) = ------------ |r|
               4 pi eps0                            4 pi eps0

    Note that alpha (and rfilt) should conform with the cutoff radius.
    """
    work_g = erf(alpha*r_g)

    if rfilt is None:
        M = np.vdot(f_g - ft_g * work_g, r_g * dr_g)
    else:
        M = np.vdot((f_g - ft_g * work_g)[r_g>=rfilt], \
            (r_g * dr_g)[r_g>=rfilt])

        # Replace 1/r -> (3-r^2/rfilt^2)/(2*rfilt) for r < rfilt
        M += np.vdot((f_g - ft_g * work_g)[r_g<rfilt], \
            (r_g**2/(2*rfilt) * (3-(r_g/rfilt)**2) * dr_g)[r_g<rfilt])

    v_mm = np.empty((2*l1+1, 2*l2+1), dtype=float)
    for m1 in range(2*l1+1):
        for m2 in range(2*l2+1):
            v_mm[m1,m2] = M * intYY(l1, m1-l1, l2, m2-l2)
    return v_mm
Esempio n. 13
0
def CGSolve(u0x,u0y,lamb,mu,b,epsilon,dfx,dfy) :
    # Solves JTJ[ux,uy]=b
    #lambd,mu,epsilon,dfx,dfy are needed in the computation of JTJ
    # [u0x,u0y] is the starting point of the iteration algo
    nitmax=100;
    ux=u0x;
    uy=u0y;
    # Computes JTJu
    Ax,Ay=JTJ(ux,uy,dfx,dfy,lamb,mu,epsilon);
    rx=b[0]-Ax
    ry=b[1]-Ay
    px=rx
    py=ry
    rsold=np.linalg.norm(rx)**2+np.linalg.norm(ry)**2
    for i in range(nitmax) :
        Apx,Apy=JTJ(px,py,dfx,dfy,lamb,mu,epsilon);
        alpha=rsold/(np.vdot(rx[:],Apx[:])+np.vdot(ry[:],Apy[:]))
        ux=ux+alpha*px
        uy=uy+alpha*py
        rx=rx-alpha*Apx
        ry=ry-alpha*Apy
        rsnew=np.linalg.norm(rx)**2+np.linalg.norm(ry)**2
        if np.sqrt(rsnew)<1e-10 :
            return [ux,uy]
        px=rx+rsnew/rsold*px
        py=ry+rsnew/rsold*py
        rsold=rsnew
    return [ux,uy]
Esempio n. 14
0
def berryphase(H,path,ns):
    '''
    Calculate the Berry phase of some bands of a Hamiltonian along a certain path.

    Parameters
    ----------
    H : callable
        Input function which returns the Hamiltonian as a 2D array.
    path : iterable of dict
        The path along which to calculate the Berry phase.
    ns : iterable of int
        The sequences of bands whose Berry phases are wanted.

    Returns
    -------
    1d ndarray
        The wanted Berry phase of the selected bands.
    '''
    ns=np.array(ns)
    for i,parameters in enumerate(path):
        new=eigh(H(**parameters))[1][:,ns]
        if i==0:
            result=np.ones(len(ns),new.dtype)
            evs,old=new,new
        else:
            for j in range(len(ns)):
                result[j]*=np.vdot(old[:,j],new[:,j])
            old=new
    else:
        for j in range(len(ns)):
            result[j]*=np.vdot(old[:,j],evs[:,j])
    return np.angle(result)/np.pi
Esempio n. 15
0
def berrycurvature(H,kx,ky,mu,d=10**-6):
    '''
    Calculate the Berry curvature of the occupied bands for a Hamiltonian with the given chemical potential using the Kubo formula.

    Parameters
    ----------
    H : callable
        Input function which returns the Hamiltonian as a 2D array.
    kx,ky : float
        The two parameters which specify the 2D point at which the Berry curvature is to be calculated.
        They are also the input parameters to be conveyed to the function H.
    mu : float
        The chemical potential.
    d : float, optional
        The spacing to be used to calculate the derivatives.

    Returns
    -------
    float
        The calculated Berry curvature for function H at point kx,ky with chemical potential mu.
    '''
    result=0
    Vx=(H(kx+d,ky)-H(kx-d,ky))/(2*d)
    Vy=(H(kx,ky+d)-H(kx,ky-d))/(2*d)
    Es,Evs=eigh(H(kx,ky))
    for n in range(Es.shape[0]):
        for m in range(Es.shape[0]):
            if Es[n]<=mu and Es[m]>mu:
                result-=2*(np.vdot(np.dot(Vx,Evs[:,n]),Evs[:,m])*np.vdot(Evs[:,m],np.dot(Vy,Evs[:,n]))/(Es[n]-Es[m])**2).imag
    return result
def g(point, contact_point, force_direction, ball_loc, t):
    """ point is a possible retraction point. 
    contact_point the place to hit the ball(coords), force_direction which
    way to move the foot"""
    # line equation = ball_loc + t*direction
    # distance to the ooi
    #distance = ( np.linalg.norm( np.cross((ball_loc[:2] - point[:2]), force_direction[:2], 0, 0) ) / 
    #    np.linalg.norm(force_direction[:2]))
    direction = force_direction
    force_direction = force_direction + contact_point
    direction = force_direction
    distance = np.linalg.norm(np.cross(point[:2] - contact_point[:2], point[:2] -
        force_direction[:2], 0 , 0)) / np.linalg.norm(abs(force_direction[:2] -
            contact_point[:2]))
    #the smaller the distance, the bigger the number
    distance = 100 / distance

    retract_distance_x = math.sqrt(np.vdot(contact_point[0] - point[0],
        contact_point[0] - point[0]))
    retract_distance_y = math.sqrt(np.vdot(contact_point[1] - point[1],
        contact_point[1] - point[1]))
    retract_distance_z = math.sqrt(np.vdot(contact_point[2] - point[2], contact_point[2] - point[2]))

    retract_distance = 0
    # the retraction distance gets favored in the x and y directions
    retract_distance =  (direction[0] * retract_distance_x +
            direction[1] *
            retract_distance_y + 0.3 *  retract_distance_z)
            #force_direction[1] * retract_distance_y + force_direction[2] *  retract_distance_z)
    return (retract_distance, distance)
Esempio n. 17
0
    def step(self,r,f):
        r = np.array(r)
        f = np.reshape(f,(-1,3))
        if self.v is None:
            self.v = np.zeros((len(f), 3))
        else:
            try:
                vf = np.vdot(self.v,f)
            except ValueError:
                self.v = np.zeros((len(f), 3))
                vf = np.vdot(self.v,f)

            if vf > 0.0:
                self.v = ((1.0 - self.a) * self.v + 
                          (self.a * f / 
                           np.sqrt(np.vdot(f, f)) * np.sqrt(np.vdot(self.v, self.v))))
                if self.Nsteps > self.Nmin:
                    self.dt = min(self.dt * self.finc, self.dtmax)
                    self.a *= self.fa
                self.Nsteps += 1
            else:
                self.v *= 0.0
                self.a = self.astart
                self.dt *= self.fdec
                self.Nsteps = 0

        self.v += self.dt * f
        dr = self.dt * self.v
        dr = self.determine_step(dr)
        return r + dr.reshape(r.shape)
Esempio n. 18
0
File: rsh.py Progetto: qsnake/gpaw
def intYgradY(l1, m1, l2, m2, r_g, dr_g, A_g, B_g, dBdr_g, v=None):
    """Calculates::

                  pi 2pi
                  /  /    *           / __               \  2
          A     = |  |   A(r) y (u,v) | \/  B(r) y (u,v) | r sin(u) dv du dr
           vLL'   /  /         lm     \   v       l'm'   /
                  0  0

    where u = theta and v = phi in the usual notation. Note that the result
    is only non-zero if `|l1-l2|` is odd and `|m1-m2|` <= 1 (stricter rule applies).
    """
    if v is None:
        D = [intYY_ex(l1,m1,l2,m2), \
             intYY_ey(l1,m1,l2,m2), \
             intYY_ez(l1,m1,l2,m2)]
        G = [intYdYdtheta_ex(l1,m1,l2,m2) + intYdYdphi_ex(l1,m1,l2,m2), \
             intYdYdtheta_ey(l1,m1,l2,m2) + intYdYdphi_ey(l1,m1,l2,m2), \
             intYdYdtheta_ez(l1,m1,l2,m2) + intYdYdphi_ez(l1,m1,l2,m2)]
        D, G = np.array(D), np.array(G)
    elif v == 0:
        D = intYY_ex(l1,m1,l2,m2)
        G = intYdYdtheta_ex(l1,m1,l2,m2) + intYdYdphi_ex(l1,m1,l2,m2)
    elif v == 1:
        D = intYY_ey(l1,m1,l2,m2)
        G = intYdYdtheta_ey(l1,m1,l2,m2) + intYdYdphi_ey(l1,m1,l2,m2)
    elif v == 2:
        D = intYY_ez(l1,m1,l2,m2)
        G = intYdYdtheta_ez(l1,m1,l2,m2) + intYdYdphi_ez(l1,m1,l2,m2)
    else:
        raise ValueError
    return D * np.vdot(A_g, dBdr_g * r_g**2 * dr_g) \
        + G * np.vdot(A_g, B_g * r_g * dr_g)
Esempio n. 19
0
def plot_ritz(A, n, iters):
    ''' Plot the relative error of the Ritz values of `A'.
    '''
    Amul = A.dot
    b = np.random.rand(A.shape[0])
    Q = np.empty((len(b), iters+1), dtype = np.complex128)
    H = np.zeros((iters+1, iters), dtype = np.complex128)
    Q[:, 0] = b / la.norm(b)
    eigvals = np.sort(abs(la.eig(A)[0]))[::-1]
    eigvals = eigvals[:n]
    abs_err = np.zeros((iters,n))

    for j in xrange(iters):
        Q[:, j+1] = Amul(Q[:, j])
        for i in xrange(j+1):
            H[i,j] = np.vdot(Q[:,i].conjugate(), (Q[:, j+1]))
            Q[:,j+1] = Q[:,j+1] - H[i,j] * (Q[:,i])

        H[j+1, j] = np.sqrt(np.vdot(Q[:, j+1], Q[:, j+1].conjugate()))
        Q[:,j+1] = Q[:,j+1] / H[j+1, j]

        if j < n:
            rit = np.zeros(n, dtype = np.complex128)
            rit[:j+1] = np.sort(la.eig(H[:j+1, :j+1])[0])[::-1]
            abs_err[j,:] = abs(eigvals - rit) / abs(eigvals)
        else:
            rit = np.sort(la.eig(H[:j+1,:j+1])[0])[::-1]
            rit = rit[:n]
            abs_err[j,:] = abs(eigvals - rit) / abs(eigvals)

    for i in xrange(n):
        plt.semilogy(abs_err[:,i])
    plt.show()
Esempio n. 20
0
    def computeResidual(self):
        self.res = self.cAv - self.cvEig * self.cv
        self.dres = np.vdot(self.res, self.res) ** 0.5
        #
        # gram-schmidt for residual vector
        #
        for i in xrange(self.currentSize):
            self.dgks[i] = np.vdot(self.vlist[i, :], self.res)
            self.res -= self.dgks[i] * self.vlist[i, :]
        #
        # second gram-schmidt to make them really orthogonal
        #
        for i in xrange(self.currentSize):
            self.dgks[i] = np.vdot(self.vlist[i, :], self.res)
            self.res -= self.dgks[i] * self.vlist[i, :]
        self.resnorm = np.linalg.norm(self.res)
        self.res /= self.resnorm

        orthog = 0.0
        for i in xrange(self.currentSize):
            orthog += np.vdot(self.res, self.vlist[i]) ** 2.0
            if orthog > 1e-8:
                sys.exit("Exiting davidson procedure ... orthog = %24.16f" % orthog)
        orthog = orthog ** 0.5
        if not self.deflated:
            if VERBOSE:
                print "%3d %20.14f %20.14f  %10.4g" % (self.ciEig, self.cvEig.real, self.resnorm.real, orthog.real)
        # else:
        #    print "%3d %20.14f %20.14f %20.14f (deflated)" % (self.ciEig, self.cvEig,
        #                                                      self.resnorm, orthog)

        self.iteration += 1
Esempio n. 21
0
    def step(self,f):
        atoms = self.atoms
        if self.v is None:
            self.v = np.zeros((len(atoms), 3))
        else:
            vf = np.vdot(f, self.v)
            if vf > 0.0:
                self.v = (1.0 - self.a) * self.v + self.a * f / np.sqrt(
                    np.vdot(f, f)) * np.sqrt(np.vdot(self.v, self.v))
                if self.Nsteps > self.Nmin:
                    self.dt = min(self.dt * self.finc, self.dtmax)
                    self.a *= self.fa
                self.Nsteps += 1
            else:
                self.v[:] *= 0.0
                self.a = self.astart
                self.dt *= self.fdec
                self.Nsteps = 0

        self.v += self.dt * f
        dr = self.dt * self.v
        normdr = np.sqrt(np.vdot(dr, dr))
        if normdr > self.maxmove:
            dr = self.maxmove * dr / normdr
        r = atoms.get_positions()
        atoms.set_positions(r + dr)
        self.dump((self.v, self.dt))
def target_distrib(guess, *arg):
    """
    Keyword Arguments:
    x -- the vector of params

    *args are:
    arg[0] -- a target class object
    arg[1] -- Cl_old, fluc_lm_old
    """
    #print guess, arg
    dlm,strings,params,nl,bl = arg[0]
    Cl_old, fluc_lm_old = arg[1]
    dd = cb.update_dic(params,guess,strings)
    Cl_new = cb.generate_spectrum(dd)[:,1]
    Cl_new[:2] = 1.e-35
    #print "new = ",Cl_new[50]
    #print "old = ",Cl_old[50]
    renorm = CG.renorm_term(Cl_new,bl,nl)
    mf_lm_new = hp.almxfl(CG.generate_mfterm(dlm,Cl_new,bl,nl),renorm)
    fluc_lm_type2 = hp.almxfl(CG.generate_w1term(Cl_new,bl,nl)+CG.generate_w0term(Cl_new),renorm)
    #print "new = ",fluc_lm_type2[50]
    #print "old = ",fluc_lm_old[50]
    fluc_lm_determ = hp.almxfl(fluc_lm_old,np.sqrt(Cl_new/Cl_old))
    tt1 = -1/2.*np.real(np.vdot((dlm-hp.almxfl(mf_lm_new,bl)).T,hp.almxfl((dlm-hp.almxfl(mf_lm_new,bl)),1/nl)))
    #print tt1
    tt2 = -1/2. *np.real(np.vdot((mf_lm_new).T,hp.almxfl((mf_lm_new),1./Cl_new)))
    #print tt2
    tt3 = -1/2. *np.real(np.vdot((fluc_lm_determ).T,hp.almxfl((fluc_lm_determ),1/nl*bl**2)))
    #print tt3
    #tt4 = - 1./2 *(np.arange(1,np.size(Cl_new)+1)*np.log(Cl_new)).sum()
    ##print tt4
    return [tt1,tt2,tt3],Cl_new,fluc_lm_type2
Esempio n. 23
0
    def testListFitting(self):
        true1, data1 = self.generate_data()
        true2, data2 = self.generate_data()


        model = DPMixtureModel(3, 2000, 100, 1, type='BEM')
        rs = model.fit([data1, data2])
        assert(len(rs) == 2)
        for r in rs:
            print 'mu ', r.mus
            diffs = {}
            for i in gen_mean:

                diffs[i] = np.min(np.abs(r.mus - gen_mean[i]), 0)
                # print i, gen_mean[i], diffs[i], np.vdot(diffs[i],diffs[i])
                assert(np.vdot(diffs[i], diffs[i]) < 2)

        fcm1 = FCMdata('test_fcm1', data1, ['fsc', 'ssc'], [0, 1])
        fcm2 = FCMdata('test_fcm2', data2, ['fsc', 'ssc'], [0, 1])

        c = FCMcollection('fcms', [fcm1, fcm2])

        rs = model.fit(c)
        assert(len(rs) == 2)
        for r in rs:
            print 'mu ', r.mus
            diffs = {}
            for i in gen_mean:

                diffs[i] = np.min(np.abs(r.mus - gen_mean[i]), 0)
                # print i, gen_mean[i], diffs[i], np.vdot(diffs[i],diffs[i])
                assert(np.vdot(diffs[i], diffs[i]) < 2)
def power_method(file_name, error_tol, u0):

    # Creates a matrix from the .dat file
    A = np.genfromtxt(file_name, delimiter=" ")

    m = int(A.shape[0]) #rows of A

    u = np.asarray(np.asmatrix(u0))
    uRows = int(u.shape[0]) #rows of u
    uCols = int(u.shape[1]) #columns of u

    # Sets the tolerance
    tol = error_tol

    # Sets the initial number of iterations
    iteration = 0

    # Sets an array with one entry 0 to use for the error in the while loop
    eigenvalues = [0]

    # While number of iterations is less than 100, the matrix
    # A is raised to a power equal to the iteration and multiplied
    # by the original u0 that was given as an input. The dominant
    # eigenvector is found and from that, the dominant eigenvalue
    # is found.
    while iteration < 100:
        copyA = LA.matrix_power(A, iteration+1)
        x = np.zeros(shape=(m, uCols))
        for i in range(m):
            for j in range(uCols):
                for k in range(uRows):
                    x[i][j] += (copyA[i][k] * u[k][j]) #Multiplies matrix A and u
        eigenvector = x / LA.norm(x) # Finds the dominant eigenvector
        eigenRows = int(eigenvector.shape[0]) #rows of dominant eigenvector
        eigenCols = int(eigenvector.shape[1]) #columns of eigenvector

        Ax = np.zeros(shape = (m, eigenCols))

        for i in range(m):
            for j in range(eigenCols):
                for k in range(eigenRows):
                    Ax[i][j] += A[i][k] * eigenvector[k][j]
        Axx = np.vdot(Ax, eigenvector)
        xx = np.vdot(eigenvector, eigenvector)
        eigenvalue = Axx / xx # Finds the dominant eigenvalue

        eigenvalues.append(eigenvalue)

        if (np.absolute(eigenvalues[iteration+1] - eigenvalues[iteration])) <= tol:
            break

        iteration += 1

    print "Dominant eigenvalue = ", eigenvalue
    print "Dominant eigenvector =\n", eigenvector

    if iteration >= 100:
        print "Did not converge after 100 iterations."
    else:
        print "Took " + str(iteration) + " iterations to converge."
Esempio n. 25
0
def main():
    size=300
    A,P=setA(size,0.0+1j*0.0)
    b = np.random.rand(size,1) + 0j*np.random.rand(size,1)
    b /= np.sqrt( np.vdot(b,b) )

    xstart = np.dot(np.linalg.inv(A),b)
    xstart += 1./1.*(np.random.rand(size,1) + 0j*np.random.rand(size,1))
    condition_number = np.linalg.cond(A)
    r0=b-np.dot(A,xstart)
    res=np.vdot(r0,r0) ** 0.5
    finalx=np.dot(np.linalg.inv(A),b)
    print " ::: Making A,b matrix :::"
    print "  - condition number = %12.8f" % condition_number
    print "  - x0 residual      = %12.8f" % np.real(res)
    #for i in xrange(size):
    #    print "%20.16f %20.16f" % (np.real(finalx[i]), np.imag(finalx[i]))

    def multiplyA(vector,args):
        return np.dot(A,vector).reshape(len(vector))
    def multiplyA_precon(vector,args):
        return np.multiply(P.reshape(len(vector)),np.dot(A,vector).reshape(len(vector))).reshape(len(vector))
    gmin = gMinRes(multiplyA,b,xstart,P)

    #b = np.multiply(b,P)
    #gmin = gMinRes(multiplyA_precon,b,xstart,P)
    sol = gmin.get_solution()

    print "|Ax-b| = ", np.linalg.norm(np.dot(A,sol) - b)
Esempio n. 26
0
def test_fft(ndims):
    x=randmat( ndims )


    if doreal:
        xver = numpy.fft.rfftn(x)
    else:
        xver = numpy.fft.fftn(x)
    
    open('/tmp/fftexp.dat','w').write(dopack( flatten(xver) , True ) )

    x2=dofft(x,doreal)
    err = xver - x2
    errf = flatten(err)
    xverf = flatten(xver)
    errpow = numpy.vdot(errf,errf)+1e-10
    sigpow = numpy.vdot(xverf,xverf)+1e-10
    snr = 10*math.log10(abs(sigpow/errpow) )
    print 'SNR (compared to NumPy) : %.1fdB' % float(snr)

    if snr<minsnr:
        print 'xver=',xver
        print 'x2=',x2
        print 'err',err
        sys.exit(1)
Esempio n. 27
0
File: net3.py Progetto: jarano93/Net
    def feedforward(self, input): # ok
        """runs the net with given input and saves hidden activations"""

        local_input = np.array(input)
        if len(local_input) != self.input_len:
            raise ValueError("Input dimensions not match expected dimensions")
        
        self.input = np.append(local_input, 1)
        for j in range(self.layer0_len):
            self.activation0[j] = np.vdot(self.weight0[:,j], self.input)
        self.hmap0 = np.tanh(self.activation0)
        # print self.hmap0
        
        for k in range(self.layer1_len):
            self.activation1[k] = np.vdot(self.weight1[:,k], self.hmap0)
        self.hmap1 = np.tanh(self.activation1)
        # print self.hmap1
        
        for l in range(self.layer2_len):
            self.activation2[l] = np.vdot(self.weight2[:,l], self.hmap1)
        self.hmap2 = np.tanh(self.activation2)
        # print self.hmap2
        
        for m in range(self.output_len):
            self.output[m] = np.vdot(self.weight3[:,m], self.hmap2)
Esempio n. 28
0
    def step(self, f):
        """Perform the optimization step."""
        atoms = self.atoms
        r = atoms.get_positions()
        curv = atoms.get_curvature()
        f0p = f.copy()
        r0 = r.copy()
        direction = f0p.copy()
        if self.cg_on:
            direction = self.get_cg_direction(direction)
        direction = normalize(direction)
        if curv > 0.0:
            step = direction * self.max_step
        else:
            r0t = r0 + direction * self.trial_step
            f0tp = self.atoms.get_projected_forces(r0t)
            F = np.vdot((f0tp + f0p), direction) / 2.0
            C = np.vdot((f0tp - f0p), direction) / self.trial_step
            step = (-F / C + self.trial_step / 2.0) * direction
            if norm(step) > self.max_step:
                step = direction * self.max_step
        self.log(f0p, norm(step))

        atoms.set_positions(r + step)

        self.f0 = f.flat.copy()
        self.r0 = r.flat.copy()
    def test_minres_sparse_indef_precon(self):
        # Create sparse symmetric problem.
        num_unknowns = 100
        A = self._create_sparse_herm_indef_matrix(num_unknowns)
        M = self._create_hpd_matrix( num_unknowns )
        rhs = np.ones( (num_unknowns,1) )
        x0 = np.zeros( (num_unknowns,1) )

        # Solve using spsolve.
        xexact = scipy.sparse.linalg.spsolve(A, rhs)
        xexact = np.reshape(xexact, (len(xexact),1))
        # Solve using MINRES.
        tol = 1.0e-10
        out = nm.minres( A, rhs, x0, tol=tol, maxiter=100*num_unknowns, explicit_residual=True, exact_solution=xexact, M=M)

        # Make sure the method converged.
        self.assertEqual(out['info'], 0)

        # compute M-norm of residual
        res = rhs - A * out['xk']
        Mres = np.dot(M, res)
        norm_res = np.sqrt(np.vdot(res, Mres))

        # compute M-norm of rhs
        Mrhs = np.dot(M, rhs)
        norm_rhs = np.sqrt(np.vdot(rhs, Mrhs))

        # Check the residual.
        self.assertAlmostEqual( norm_res/norm_rhs, 0.0, delta=tol )
        # Check error.
        self.assertAlmostEqual( np.linalg.norm(xexact - out['xk']) - out['errvec'][-1], 0.0, delta=1e-10 )
Esempio n. 30
0
    def testListFitting(self):
        true1, data1 = self.generate_data()
        true2, data2 = self.generate_data()

        model = DPMixtureModel(3, 2000, 100, 1, type="BEM")
        rs = model.fit([data1, data2])
        assert len(rs) == 2
        for r in rs:
            print "mu ", r.mus
            diffs = {}
            for i in gen_mean:

                diffs[i] = np.min(np.abs(r.mus - gen_mean[i]), 0)
                # print i, gen_mean[i], diffs[i], np.vdot(diffs[i],diffs[i])
                assert np.vdot(diffs[i], diffs[i]) < 2

        fcm1 = FCMdata("test_fcm1", data1, ["fsc", "ssc"], [0, 1])
        fcm2 = FCMdata("test_fcm2", data2, ["fsc", "ssc"], [0, 1])

        c = FCMcollection("fcms", [fcm1, fcm2])

        rs = model.fit(c)
        assert len(rs) == 2
        for r in rs:
            print "mu ", r.mus
            diffs = {}
            for i in gen_mean:

                diffs[i] = np.min(np.abs(r.mus - gen_mean[i]), 0)
                # print i, gen_mean[i], diffs[i], np.vdot(diffs[i],diffs[i])
                assert np.vdot(diffs[i], diffs[i]) < 4
target = target[target == target_value]

print(samples_v2.shape[0])

pad = 2
h_kernel = np.array([[1, 1], [-1, -1]], np.int32)
z_kernel = np.array([[1, -1], [1, -1]], np.int32)
hardcoded_kernel_size = 9
for blocksize in [9]:
    for C in [-2]:
        for img in samples_v2:
            # ff_copy = img.copy()
            # ff_mean = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, blocksize, C)

            horizontal = np.zeros(img.shape, np.uint8)
            vertical = np.zeros(img.shape, np.uint8)
            for x in range(0, img.shape[0] - pad - 1):
                for y in range(0, img.shape[0] - pad - 1):
                    roi = img[y:y + pad, x:x + pad]
                    h = np.vdot(h_kernel, roi)
                    z = np.vdot(z_kernel, roi)
                    horizontal[y, x] = max(min(h, 255), 0)
                    vertical[y, x] = max(min(z, 255), 0)

            # horizontal = cv.subtract(horizontal, img)
            cv.imshow("img", img)
            cv.imshow("horizontal", horizontal)
            cv.imshow("vertical", vertical)
            cv.imshow("both", cv.bitwise_and(vertical, horizontal))
            if cv.waitKey(0) & 0xFF == ord('q'):
                exit(0)
Esempio n. 32
0
def alt_dot_product(a, b):
    dp = abs(a) * abs(b) * np.cos(np.angle(a) - np.angle(b))
    return dp


a = np.array([1 + 2j, 3 + 4j])
b = np.array([5 + 6j, 7 + 8j])
c = 2 + 2j
d = 2 + 2j

#print vdot(a, b)
#(70-8j)
#print vdot(b, a)
#(70+8j)
print np.dot(c, d)
print np.vdot(c, d)
print dot_product(c, d)
print alt_dot_product(c, d)

zero_vector = np.ndarray(shape=(1024), dtype=complex)  # Make a complex vector

xcorr = zero_vector

dut_noise_fft_avg = np.zeros(1024)
path_a_noise_fft_avg = np.zeros(1024)
path_b_noise_fft_avg = np.zeros(1024)
xcorr_avg = np.zeros(1024)
dut_noise = np.zeros(1024)
path_b_noise = np.zeros(1024)
path_b_noise = np.zeros(1024)
Esempio n. 33
0
def greed_omp_qr(x, A, m, opts=[]):
    # greed_omp_qr: Orthogonal Matching Pursuit algorithm based on QR
    # factorisation
    # Nic: translated to Python on 19.10.2011. Original Matlab Code by Thomas Blumensath
    ###########################################################################
    # Usage
    # [s, err_mse, iter_time]=greed_omp_qr(x,P,m,'option_name','option_value')
    ###########################################################################
    ###########################################################################
    # Input
    #   Mandatory:
    #               x   Observation vector to be decomposed
    #               P   Either:
    #                       1) An nxm matrix (n must be dimension of x)
    #                       2) A function handle (type "help function_format"
    #                          for more information)
    #                          Also requires specification of P_trans option.
    #                       3) An object handle (type "help object_format" for
    #                          more information)
    #               m   length of s
    #
    #   Possible additional options:
    #   (specify as many as you want using 'option_name','option_value' pairs)
    #   See below for explanation of options:
    #__________________________________________________________________________
    #   option_name    |     available option_values                | default
    #--------------------------------------------------------------------------
    #   stopCrit       | M, corr, mse, mse_change                   | M
    #   stopTol        | number (see below)                         | n/4
    #   P_trans        | function_handle (see below)                |
    #   maxIter        | positive integer (see below)               | n
    #   verbose        | true, false                                | false
    #   start_val      | vector of length m                         | zeros
    #
    #   Available stopping criteria :
    #               M           -   Extracts exactly M = stopTol elements.
    #               corr        -   Stops when maximum correlation between
    #                               residual and atoms is below stopTol value.
    #               mse         -   Stops when mean squared error of residual
    #                               is below stopTol value.
    #               mse_change  -   Stops when the change in the mean squared
    #                               error falls below stopTol value.
    #
    #   stopTol: Value for stopping criterion.
    #
    #   P_trans: If P is a function handle, then P_trans has to be specified and
    #            must be a function handle.
    #
    #   maxIter: Maximum number of allowed iterations.
    #
    #   verbose: Logical value to allow algorithm progress to be displayed.
    #
    #   start_val: Allows algorithms to start from partial solution.
    #
    ###########################################################################
    # Outputs
    #    s              Solution vector
    #    err_mse        Vector containing mse of approximation error for each
    #                   iteration
    #    iter_time      Vector containing computation times for each iteration
    #
    ###########################################################################
    # Description
    #   greed_omp_qr performs a greedy signal decomposition.
    #   In each iteration a new element is selected depending on the inner
    #   product between the current residual and columns in P.
    #   The non-zero elements of s are approximated by orthogonally projecting
    #   x onto the selected elements in each iteration.
    #   The algorithm uses QR decomposition.
    #
    # See Also
    #   greed_omp_chol, greed_omp_cg, greed_omp_cgp, greed_omp_pinv,
    #   greed_omp_linsolve, greed_gp, greed_nomp
    #
    # Copyright (c) 2007 Thomas Blumensath
    #
    # The University of Edinburgh
    # Email: [email protected]
    # Comments and bug reports welcome
    #
    # This file is part of sparsity Version 0.1
    # Created: April 2007
    #
    # Part of this toolbox was developed with the support of EPSRC Grant
    # D000246/1
    #
    # Please read COPYRIGHT.m for terms and conditions.

    ###########################################################################
    #                    Default values and initialisation
    ###########################################################################
    #[n1 n2]=size(x);
    #n1,n2 = x.shape
    #if n2 == 1
    #    n=n1;
    #elseif n1 == 1
    #    x=x';
    #    n=n2;
    #else
    #   display('x must be a vector.');
    #   return
    #end
    if x.ndim != 1:
        print 'x must be a vector.'
        return
    n = x.size

    #sigsize     = x'*x/n;
    sigsize = np.vdot(x, x) / n
    initial_given = 0
    err_mse = np.array([])
    iter_time = np.array([])
    STOPCRIT = 'M'
    STOPTOL = math.ceil(n / 4.0)
    MAXITER = n
    verbose = False
    s_initial = np.zeros(m)

    if verbose:
        print 'Initialising...'
    #end

    ###########################################################################
    #                           Output variables
    ###########################################################################
    #switch nargout
    #    case 3
    #        comp_err=true;
    #        comp_time=true;
    #    case 2
    #        comp_err=true;
    #        comp_time=false;
    #    case 1
    #        comp_err=false;
    #        comp_time=false;
    #    case 0
    #        error('Please assign output variable.')
    #    otherwise
    #        error('Too many output arguments specified')
    #end
    if 'nargout' in opts:
        if opts['nargout'] == 3:
            comp_err = True
            comp_time = True
        elif opts['nargout'] == 2:
            comp_err = True
            comp_time = False
        elif opts['nargout'] == 1:
            comp_err = False
            comp_time = False
        elif opts['nargout'] == 0:
            print 'Please assign output variable.'
            return
        else:
            print 'Too many output arguments specified'
            return
    else:
        # If not given, make default nargout = 3
        #  and add nargout to options
        opts['nargout'] = 3
        comp_err = True
        comp_time = True

    ###########################################################################
    #                       Look through options
    ###########################################################################
    # Put option into nice format
    #Options={};
    #OS=nargin-3;
    #c=1;
    #for i=1:OS
    #    if isa(varargin{i},'cell')
    #        CellSize=length(varargin{i});
    #        ThisCell=varargin{i};
    #        for j=1:CellSize
    #            Options{c}=ThisCell{j};
    #            c=c+1;
    #        end
    #    else
    #        Options{c}=varargin{i};
    #        c=c+1;
    #    end
    #end
    #OS=length(Options);
    #if rem(OS,2)
    #   error('Something is wrong with argument name and argument value pairs.')
    #end
    #
    #for i=1:2:OS
    #   switch Options{i}
    #        case {'stopCrit'}
    #            if (strmatch(Options{i+1},{'M'; 'corr'; 'mse'; 'mse_change'},'exact'));
    #                STOPCRIT    = Options{i+1};
    #            else error('stopCrit must be char string [M, corr, mse, mse_change]. Exiting.'); end
    #        case {'stopTol'}
    #            if isa(Options{i+1},'numeric') ; STOPTOL     = Options{i+1};
    #            else error('stopTol must be number. Exiting.'); end
    #        case {'P_trans'}
    #            if isa(Options{i+1},'function_handle'); Pt = Options{i+1};
    #            else error('P_trans must be function _handle. Exiting.'); end
    #        case {'maxIter'}
    #            if isa(Options{i+1},'numeric'); MAXITER     = Options{i+1};
    #            else error('maxIter must be a number. Exiting.'); end
    #        case {'verbose'}
    #            if isa(Options{i+1},'logical'); verbose     = Options{i+1};
    #            else error('verbose must be a logical. Exiting.'); end
    #        case {'start_val'}
    #            if isa(Options{i+1},'numeric') & length(Options{i+1}) == m ;
    #                s_initial     = Options{i+1};
    #                initial_given=1;
    #            else error('start_val must be a vector of length m. Exiting.'); end
    #        otherwise
    #            error('Unrecognised option. Exiting.')
    #   end
    #end
    if 'stopCrit' in opts:
        STOPCRIT = opts['stopCrit']
    if 'stopTol' in opts:
        if hasattr(opts['stopTol'], '__int__'):  # check if numeric
            STOPTOL = opts['stopTol']
        else:
            raise TypeError('stopTol must be number. Exiting.')
    if 'P_trans' in opts:
        if hasattr(opts['P_trans'], '__call__'):  # check if function handle
            Pt = opts['P_trans']
        else:
            raise TypeError('P_trans must be function _handle. Exiting.')
    if 'maxIter' in opts:
        if hasattr(opts['maxIter'], '__int__'):  # check if numeric
            MAXITER = opts['maxIter']
        else:
            raise TypeError('maxIter must be a number. Exiting.')
    if 'verbose' in opts:
        # TODO: Should check here if is logical
        verbose = opts['verbose']
    if 'start_val' in opts:
        # TODO: Should check here if is numeric
        if opts['start_val'].size == m:
            s_initial = opts['start_val']
            initial_given = 1
        else:
            raise ValueError(
                'start_val must be a vector of length m. Exiting.')
    # Don't exit if unknown option is given, simply ignore it

    #if strcmp(STOPCRIT,'M')
    #    maxM=STOPTOL;
    #else
    #    maxM=MAXITER;
    #end
    if STOPCRIT == 'M':
        maxM = STOPTOL
    else:
        maxM = MAXITER

    #    if nargout >=2
    #        err_mse = zeros(maxM,1);
    #    end
    #    if nargout ==3
    #        iter_time = zeros(maxM,1);
    #    end
    if opts['nargout'] >= 2:
        err_mse = np.zeros(maxM)
    if opts['nargout'] == 3:
        iter_time = np.zeros(maxM)

    ###########################################################################
    #                        Make P and Pt functions
    ###########################################################################
    #if          isa(A,'float')      P =@(z) A*z;  Pt =@(z) A'*z;
    #elseif      isobject(A)         P =@(z) A*z;  Pt =@(z) A'*z;
    #elseif      isa(A,'function_handle')
    #    try
    #        if          isa(Pt,'function_handle'); P=A;
    #        else        error('If P is a function handle, Pt also needs to be a function handle. Exiting.'); end
    #    catch error('If P is a function handle, Pt needs to be specified. Exiting.'); end
    #else        error('P is of unsupported type. Use matrix, function_handle or object. Exiting.'); end
    if hasattr(A, '__call__'):
        if hasattr(Pt, '__call__'):
            P = A
        else:
            raise TypeError(
                'If P is a function handle, Pt also needs to be a function handle.'
            )
    else:
        # TODO: should check here if A is matrix
        P = lambda z: np.dot(A, z)
        Pt = lambda z: np.dot(A.T, z)

    ###########################################################################
    #                 Random Check to see if dictionary is normalised
    ###########################################################################
    #    mask=zeros(m,1);
    #    mask(ceil(rand*m))=1;
    #    nP=norm(P(mask));
    #    if abs(1-nP)>1e-3;
    #        display('Dictionary appears not to have unit norm columns.')
    #    end
    mask = np.zeros(m)
    mask[math.floor(np.random.rand() * m)] = 1
    #nP = np.linalg.norm(P(mask))
    #if abs(1-nP) > 1e-3:
    #    print 'Dictionary appears not to have unit norm columns.'

    ###########################################################################
    #              Check if we have enough memory and initialise
    ###########################################################################
    #        try Q=zeros(n,maxM);
    #        catch error('Variable size is too large. Please try greed_omp_chol algorithm or reduce MAXITER.')
    #        end
    #        try R=zeros(maxM);
    #        catch error('Variable size is too large. Please try greed_omp_chol algorithm or reduce MAXITER.')
    #        end
    try:
        Q = np.zeros((n, maxM))
    except:
        print 'Variable size is too large. Please try greed_omp_chol algorithm or reduce MAXITER.'
        raise
    try:
        R = np.zeros((maxM, maxM))
    except:
        print 'Variable size is too large. Please try greed_omp_chol algorithm or reduce MAXITER.'
        raise

    ###########################################################################
    #                        Do we start from zero or not?
    ###########################################################################
    #if initial_given ==1;
    #    IN          = find(s_initial);
    #    if ~isempty(IN)
    #        Residual    = x-P(s_initial);
    #        lengthIN=length(IN);
    #        z=[];
    #        for k=1:length(IN)
    #            # Extract new element
    #             mask=zeros(m,1);
    #             mask(IN(k))=1;
    #             new_element=P(mask);
    #
    #            # Orthogonalise new element
    #             qP=Q(:,1:k-1)'*new_element;
    #             q=new_element-Q(:,1:k-1)*(qP);
    #
    #             nq=norm(q);
    #             q=q/nq;
    #            # Update QR factorisation
    #             R(1:k-1,k)=qP;
    #             R(k,k)=nq;
    #             Q(:,k)=q;
    #
    #             z(k)=q'*x;
    #        end
    #        s           = s_initial;
    #        Residual=x-Q(:,k)*z;
    #        oldERR      = Residual'*Residual/n;
    #    else
    #    	IN          = [];
    #        Residual    = x;
    #        s           = s_initial;
    #        sigsize     = x'*x/n;
    #        oldERR      = sigsize;
    #        k=0;
    #        z=[];
    #    end
    #
    #else
    #    IN          = [];
    #    Residual    = x;
    #    s           = s_initial;
    #    sigsize     = x'*x/n;
    #    oldERR      = sigsize;
    #    k=0;
    #    z=[];
    #end
    if initial_given == 1:
        #IN = find(s_initial);
        IN = np.nonzero(s_initial)[0].tolist()
        #if ~isempty(IN)
        if IN.size > 0:
            Residual = x - P(s_initial)
            lengthIN = IN.size
            z = np.array([])
            #for k=1:length(IN)
            for k in np.arange(IN.size):
                # Extract new element
                mask = np.zeros(m)
                mask[IN[k]] = 1
                new_element = P(mask)

                # Orthogonalise new element
                #qP=Q(:,1:k-1)'*new_element;
                if k - 1 >= 0:
                    qP = np.dot(Q[:, 0:k].T, new_element)
                    #q=new_element-Q(:,1:k-1)*(qP);
                    q = new_element - np.dot(Q[:, 0:k], qP)

                    nq = np.linalg.norm(q)
                    q = q / nq
                    # Update QR factorisation
                    R[0:k, k] = qP
                    R[k, k] = nq
                    Q[:, k] = q
                else:
                    q = new_element

                    nq = np.linalg.norm(q)
                    q = q / nq
                    # Update QR factorisation
                    R[k, k] = nq
                    Q[:, k] = q

                z[k] = np.dot(q.T, x)
            #end
            s = s_initial.copy()
            Residual = x - np.dot(Q[:, k], z)
            oldERR = np.vdot(Residual, Residual) / n
        else:
            #IN          = np.array([], dtype = int)
            IN = np.array([], dtype=int).tolist()
            Residual = x.copy()
            s = s_initial.copy()
            sigsize = np.vdot(x, x) / n
            oldERR = sigsize
            k = 0
            #z = np.array([])
            z = []
        #end

    else:
        #IN          = np.array([], dtype = int)
        IN = np.array([], dtype=int).tolist()
        Residual = x.copy()
        s = s_initial.copy()
        sigsize = np.vdot(x, x) / n
        oldERR = sigsize
        k = 0
        #z = np.array([])
        z = []
    #end

    ###########################################################################
    #                        Main algorithm
    ###########################################################################
    #    if verbose
    #       display('Main iterations...')
    #    end
    #    tic
    #    t=0;
    #    DR=Pt(Residual);
    #    done = 0;
    #    iter=1;
    if verbose:
        print 'Main iterations...'
    tic = time.time()
    t = 0
    DR = Pt(Residual)
    done = 0
    iter = 1

    #while ~done
    #
    #     # Select new element
    #     DR(IN)=0;
    #     # Nic: replace selection with random variable
    #     # i.e. Randomized OMP!!
    #     # DON'T FORGET ABOUT THIS!!
    #     [v I]=max(abs(DR));
    #     #I = randp(exp(abs(DR).^2 ./ (norms.^2)'), [1 1]);
    #     IN=[IN I];
    #
    #
    #     k=k+1;
    #     # Extract new element
    #     mask=zeros(m,1);
    #     mask(IN(k))=1;
    #     new_element=P(mask);
    #
    #    # Orthogonalise new element
    #     qP=Q(:,1:k-1)'*new_element;
    #     q=new_element-Q(:,1:k-1)*(qP);
    #
    #     nq=norm(q);
    #     q=q/nq;
    #    # Update QR factorisation
    #     R(1:k-1,k)=qP;
    #     R(k,k)=nq;
    #     Q(:,k)=q;
    #
    #     z(k)=q'*x;
    #
    #    # New residual
    #     Residual=Residual-q*(z(k));
    #     DR=Pt(Residual);
    #
    #     ERR=Residual'*Residual/n;
    #     if comp_err
    #         err_mse(iter)=ERR;
    #     end
    #
    #     if comp_time
    #         iter_time(iter)=toc;
    #     end
    #
    ############################################################################
    ##                        Are we done yet?
    ############################################################################
    #
    #     if strcmp(STOPCRIT,'M')
    #         if iter >= STOPTOL
    #             done =1;
    #         elseif verbose && toc-t>10
    #            display(sprintf('Iteration #i. --- #i iterations to go',iter ,STOPTOL-iter))
    #            t=toc;
    #         end
    #    elseif strcmp(STOPCRIT,'mse')
    #         if comp_err
    #            if err_mse(iter)<STOPTOL;
    #                done = 1;
    #            elseif verbose && toc-t>10
    #                display(sprintf('Iteration #i. --- #i mse',iter ,err_mse(iter)))
    #                t=toc;
    #            end
    #         else
    #             if ERR<STOPTOL;
    #                done = 1;
    #             elseif verbose && toc-t>10
    #                display(sprintf('Iteration #i. --- #i mse',iter ,ERR))
    #                t=toc;
    #             end
    #         end
    #     elseif strcmp(STOPCRIT,'mse_change') && iter >=2
    #         if comp_err && iter >=2
    #              if ((err_mse(iter-1)-err_mse(iter))/sigsize <STOPTOL);
    #                done = 1;
    #             elseif verbose && toc-t>10
    #                display(sprintf('Iteration #i. --- #i mse change',iter ,(err_mse(iter-1)-err_mse(iter))/sigsize ))
    #                t=toc;
    #             end
    #         else
    #             if ((oldERR - ERR)/sigsize < STOPTOL);
    #                done = 1;
    #             elseif verbose && toc-t>10
    #                display(sprintf('Iteration #i. --- #i mse change',iter ,(oldERR - ERR)/sigsize))
    #                t=toc;
    #             end
    #         end
    #     elseif strcmp(STOPCRIT,'corr')
    #          if max(abs(DR)) < STOPTOL;
    #             done = 1;
    #          elseif verbose && toc-t>10
    #                display(sprintf('Iteration #i. --- #i corr',iter ,max(abs(DR))))
    #                t=toc;
    #          end
    #     end
    #
    #    # Also stop if residual gets too small or maxIter reached
    #     if comp_err
    #         if err_mse(iter)<1e-16
    #             display('Stopping. Exact signal representation found!')
    #             done=1;
    #         end
    #     else
    #
    #
    #         if iter>1
    #             if ERR<1e-16
    #                 display('Stopping. Exact signal representation found!')
    #                 done=1;
    #             end
    #         end
    #     end
    #
    #     if iter >= MAXITER
    #         display('Stopping. Maximum number of iterations reached!')
    #         done = 1;
    #     end
    #
    ############################################################################
    ##                    If not done, take another round
    ############################################################################
    #
    #     if ~done
    #        iter=iter+1;
    #        oldERR=ERR;
    #     end
    #end
    while not done:

        # Select new element
        DR[IN] = 0
        #[v I]=max(abs(DR));
        #v = np.abs(DR).max()
        I = np.abs(DR).argmax()
        #IN = np.concatenate((IN,I))
        IN.append(I)

        #k = k + 1  Move to end, since is zero based

        # Extract new element
        mask = np.zeros(m)
        mask[IN[k]] = 1
        new_element = P(mask)

        # Orthogonalise new element
        if k - 1 >= 0:
            qP = np.dot(Q[:, 0:k].T, new_element)
            q = new_element - np.dot(Q[:, 0:k], qP)

            nq = np.linalg.norm(q)
            q = q / nq
            # Update QR factorisation
            R[0:k, k] = qP
            R[k, k] = nq
            Q[:, k] = q
        else:
            q = new_element

            nq = np.linalg.norm(q)
            q = q / nq
            # Update QR factorisation
            R[k, k] = nq
            Q[:, k] = q

        #z[k]=np.vdot(q , x)
        z.append(np.vdot(q, x))

        # New residual
        Residual = Residual - q * (z[k])
        DR = Pt(Residual)

        ERR = np.vdot(Residual, Residual) / n
        if comp_err:
            err_mse[iter - 1] = ERR
        #end

        if comp_time:
            iter_time[iter - 1] = time.time() - tic
        #end

        ###########################################################################
        #                        Are we done yet?
        ###########################################################################
        if STOPCRIT == 'M':
            if iter >= STOPTOL:
                done = 1
            elif verbose and time.time(
            ) - t > 10.0 / 1000:  # time() returns sec
                #display(sprintf('Iteration #i. --- #i iterations to go',iter ,STOPTOL-iter))
                print 'Iteration ' + iter + '. --- ' + (
                    STOPTOL - iter) + ' iterations to go'
                t = time.time()
            #end
        elif STOPCRIT == 'mse':
            if comp_err:
                if err_mse[iter - 1] < STOPTOL:
                    done = 1
                elif verbose and time.time(
                ) - t > 10.0 / 1000:  # time() returns sec
                    #display(sprintf('Iteration #i. --- #i mse',iter ,err_mse(iter)))
                    print 'Iteration ' + iter + '. --- ' + err_mse[iter -
                                                                   1] + ' mse'
                    t = time.time()
                #end
            else:
                if ERR < STOPTOL:
                    done = 1
                elif verbose and time.time(
                ) - t > 10.0 / 1000:  # time() returns sec
                    #display(sprintf('Iteration #i. --- #i mse',iter ,ERR))
                    print 'Iteration ' + iter + '. --- ' + ERR + ' mse'
                    t = time.time()
                #end
            #end
        elif STOPCRIT == 'mse_change' and iter >= 2:
            if comp_err and iter >= 2:
                if ((err_mse[iter - 2] - err_mse[iter - 1]) / sigsize <
                        STOPTOL):
                    done = 1
                elif verbose and time.time(
                ) - t > 10.0 / 1000:  # time() returns sec
                    #display(sprintf('Iteration #i. --- #i mse change',iter ,(err_mse(iter-1)-err_mse(iter))/sigsize ))
                    print 'Iteration ' + iter + '. --- ' + (
                        (err_mse[iter - 2] - err_mse[iter - 1]) /
                        sigsize) + ' mse change'
                    t = time.time()
                #end
            else:
                if ((oldERR - ERR) / sigsize < STOPTOL):
                    done = 1
                elif verbose and time.time(
                ) - t > 10.0 / 1000:  # time() returns sec
                    #display(sprintf('Iteration #i. --- #i mse change',iter ,(oldERR - ERR)/sigsize))
                    print 'Iteration ' + iter + '. --- ' + (
                        (oldERR - ERR) / sigsize) + ' mse change'
                    t = time.time()
                #end
            #end
        elif STOPCRIT == 'corr':
            if np.abs(DR).max() < STOPTOL:
                done = 1
            elif verbose and time.time(
            ) - t > 10.0 / 1000:  # time() returns sec
                #display(sprintf('Iteration #i. --- #i corr',iter ,max(abs(DR))))
                print 'Iteration ' + iter + '. --- ' + (
                    np.abs(DR).max()) + ' corr'
                t = time.time()
            #end
        #end

        # Also stop if residual gets too small or maxIter reached
        if comp_err:
            if err_mse[iter - 1] < 1e-14:
                done = 1
                # Nic: added verbose check
                if verbose:
                    print 'Stopping. Exact signal representation found!'
            #end
        else:
            if iter > 1:
                if ERR < 1e-14:
                    done = 1
                    # Nic: added verbose check
                    if verbose:
                        print 'Stopping. Exact signal representation found!'
                #end
            #end
        #end

        if iter >= MAXITER:
            done = 1
            # Nic: added verbose check
            if verbose:
                print 'Stopping. Maximum number of iterations reached!'
        #end

        ###########################################################################
        #                    If not done, take another round
        ###########################################################################
        if not done:
            iter = iter + 1
            oldERR = ERR
        #end

        # Moved here from front, since we are 0-based
        k = k + 1
    #end

    ###########################################################################
    #            Now we can solve for s by back-substitution
    ###########################################################################
    #s(IN)=R(1:k,1:k)\z(1:k)';
    s[IN] = scipy.linalg.solve(R[0:k, 0:k], np.array(z[0:k]))

    ###########################################################################
    #                  Only return as many elements as iterations
    ###########################################################################
    if opts['nargout'] >= 2:
        err_mse = err_mse[0:iter - 1]
    #end
    if opts['nargout'] == 3:
        iter_time = iter_time[0:iter - 1]
    #end
    if verbose:
        print 'Done'
    #end

    # Return
    if opts['nargout'] == 1:
        return s
    elif opts['nargout'] == 2:
        return s, err_mse
    elif opts['nargout'] == 3:
        return s, err_mse, iter_time