def get_projection_transformed_point(src_x_values, src_y_values, dest_width,
                                     dest_height, target_point_x,
                                     target_point_y):
    sx1, sy1 = src_x_values[0], src_y_values[0]  # tl
    sx2, sy2 = src_x_values[1], src_y_values[1]  # bl
    sx3, sy3 = src_x_values[2], src_y_values[2]  # br
    sx4, sy4 = src_x_values[3], src_y_values[3]  # tr

    source_points_123 = pl.matrix([[sx1, sx2, sx3],
                                   [sy1, sy2, sy3],
                                   [1, 1, 1]])

    source_point_4 = [[sx4], [sy4], [1]]

    scale_to_source = pl.solve(source_points_123, source_point_4)

    l, m, t = [float(x) for x in scale_to_source]

    unit_to_source = pl.matrix([[l * sx1, m * sx2, t * sx3],
                                [l * sy1, m * sy2, t * sy3],
                                [l, m, t]])

    dx1, dy1 = 0, 0
    dx2, dy2 = 0, dest_height
    dx3, dy3 = dest_width, dest_height
    dx4, dy4 = dest_width, 0

    dest_points_123 = pl.matrix([[dx1, dx2, dx3],
                                 [dy1, dy2, dy3],
                                 [1, 1, 1]])

    dest_point_4 = pl.matrix([[dx4],
                              [dy4],
                              [1]])

    scale_to_dest = pl.solve(dest_points_123, dest_point_4)

    l, m, t = [float(x) for x in scale_to_dest]

    unit_to_dest = pl.matrix([[l * dx1, m * dx2, t * dx3],
                              [l * dy1, m * dy2, t * dy3],
                              [l, m, t]])

    source_to_unit = pl.inv(unit_to_source)

    source_to_dest = unit_to_dest @ source_to_unit

    x, y, z = [float(w) for w in (source_to_dest @ pl.matrix([
        [target_point_x],
        [target_point_y],
        [1]]))]

    x /= z
    y /= z

    y = target_point_y * 2 - y

    return x, y
Beispiel #2
0
def calcvrt0(M, Mvv, Mrv, Mvr, Mtv, Mvt, fvn, frn, ftn):
    lu = splu(Mvv)
    #Mhatrr and Mhattr
    b = lu.solve(Mvr)
    Mhatrr = -Mrv * b
    _addToDiagonal(Mhatrr, M.lx)
    Mhattr = -Mtv * b
    #Mhatrt and Mhattt
    b = lu.solve(Mvt)
    Mhatrt = -Mrv * b
    Mhattt = -Mtv * b
    _addToDiagonal(Mhattt, M.lx)

    #fhatrn
    b = lu.solve(fvn)
    a = Mrv * b
    fhatrn = frn - a

    #fhattn
    b = lu.solve(fvn)
    a = Mtv * b
    fhattn = ftn - a

    MAT = pl.bmat([[Mhatrr, Mhatrt], [Mhattr, Mhattt]])
    RHS = pl.bmat([[fhatrn], [fhattn]])

    V = pl.solve(MAT, RHS)
    r = V[:M.NM, 0]
    t = V[M.NM:, 0]
    sol = lu.solve(fvn - Mvr * r - Mvt * t)
    return sol, r, t
Beispiel #3
0
def calcScatteringMatrix(M,P,x):
	## FE analysis to acquire scattering matrices (see Dossou2006) instead of solving for one incident
	##  condition as done in FE().
	#
	#@param M		Model object containing geometrical information
	#@param P		Physics object containing physical parameters
	#@param x		The design domain with 0 corresponding to eps1 and 1 corresponding to eps2
	#						and intermediate values to weighted averages in between. See physics.interpolate
	#@return			Dictionary containing the matrices R,T,R',T' that the scattering matrix consists of.
	#						as well as normal data
	#
	#see also FE()
	A,B = P.interpolate(x)
	Mvv = assembleMvv(A,B,M,P)
	Mrv,Mvr,Mtv,Mvt,fvn,frn = assembleMxxfx(M,P)

	lu = splu(Mvv)
	#Mhatrr and Mhattr
	b = lu.solve(Mvr)
	Mhatrr = -Mrv*b
	_addToDiagonal(Mhatrr, M.lx)
	Mhattr = -Mtv*b

	#Mhatrt and Mhattt
	b = lu.solve(Mvt)
	Mhatrt = -Mrv*b
	Mhattt = -Mtv*b
	_addToDiagonal(Mhattt, M.lx)

	#fhatrn
	b = lu.solve(fvn)
	a = Mrv*b
	fhatrn = frn-a

	#fhattn
	b = lu.solve(fvn)
	a = Mtv*b
	fhattn = -a

	MAT = pl.bmat([[Mhatrr, Mhatrt],
						[Mhattr, Mhattt]])

	RHS = pl.bmat([[ Mhatrr-2*M.lx*pl.identity(M.NM), Mhatrt],
						[Mhattr, Mhattt-2*M.lx*pl.identity(M.NM)]])
	#Solve Eq (53) in Dossou 2006
	RTtilde = pl.solve(MAT,RHS)
	RIn = RTtilde[:M.NM,:M.NM]
	TIn = RTtilde[M.NM:,:M.NM]
	ROut = RTtilde[M.NM:,M.NM:]
	TOut = RTtilde[:M.NM,M.NM:]

	results = {}
	results["RIn"] = RIn
	results["TIn"] = TIn
	results["ROut"] = ROut
	results["TOut"] = TOut
	results.update(M.getParameters())
	results.update(P.getParameters())
	return results
 def f_Gamma(c):
     # Once the optimal c is found, find the ellipsoid shape matrix
     
     # Variable Gamma_plus (for \Gamma_{i+1})
     Gamma_plus = variable(2,2,name='Gamma_plus')
     
     # Constraints
     c0 = belongs(Gamma_plus, semidefinite_cone)
     c1 = belongs(Gamma - Gamma_plus, semidefinite_cone)
     c2 = belongs(2*c*Gamma_plus - Gamma_plus*J - J.T*Gamma_plus, semidefinite_cone)
     
     # Objective function
     obj = -exp(-2*c*dT)*det_rootn(Gamma_plus)
     
     # Find solution
     p = program(minimize(obj), [c0, c1, c2])
     p.solve(quiet = True)
     return Gamma_plus.value
Beispiel #5
0
 def sigmaAt(self, X, noises):
     numTestLabels = X.shape[1]
     numTrainlabels = self.trainData.shape[1]
     sigmas = zeros(numTestLabels)
     for i in range(numTestLabels):
         c = self._kernel(X[:, i], X[:, i], self._theta) + noises[i]
         k = self._k(X[:, i])
         sigmas[i] = c - k.dot(solve(self.K, k))
     return sqrt(sigmas)
Beispiel #6
0
 def predictAt(self, X, **kwargs):
     numTestLabels = X.shape[1]
     numTrainlabels = self.trainData.shape[1]
     t = zeros(numTestLabels)
     bias = kwargs.get('bias', 0)
     for i in range(numTestLabels):
         k = self._k(X[:, i])
         t[i] = k.dot(solve(self.K, self.trainLabels - bias)) + bias
     return t
def smooth(y,smoothBeta=smoothBeta):
    m = len(y)
    
    p = pl.diff(pl.eye(m),3).transpose()
    A = pl.eye(m)+smoothBeta*pl.dot(p.transpose(),p)
    
    smoothY = pl.solve(A, y)
    
    return smoothY
Beispiel #8
0
 def predictAt (self, X, **kwargs):
     numTestLabels = X.shape[1]
     numTrainlabels = self.trainData.shape[1]
     t = zeros (numTestLabels)
     bias = kwargs.get ('bias', 0)
     for i in range (numTestLabels):
         k = self._k (X[:,i])
         t[i] = k.dot (solve (self.K, self.trainLabels - bias)) + bias
     return t
Beispiel #9
0
 def sigmaAt (self, X, noises):
     numTestLabels = X.shape[1]
     numTrainlabels = self.trainData.shape[1]
     sigmas = zeros (numTestLabels)
     for i in range (numTestLabels):
         c = self._kernel (X[:,i], X[:,i], self._theta) + noises[i]
         k = self._k (X[:,i])
         sigmas[i] = c - k.dot (solve (self.K, k))
     return sqrt (sigmas)
def FE(nelx,nely,x,penal,problem):
    KE = lk()   
    K = py.zeros((2*(nelx+1)*(nely+1), 2*(nelx+1)*(nely+1)))
    #K = lil_matrix((2*(nelx+1)*(nely+1), 2*(nelx+1)*(nely+1)))
    #F = lil_matrix((2*(nely+1)*(nelx+1),1))
    F = py.zeros((2*(nely+1)*(nelx+1),1))
    U = py.zeros((2*(nely+1)*(nelx+1),1))
    #U = lil_matrix((2*(nely+1)*(nelx+1),1))
        
    #print 'K', K, 'F', F, 'U', U
    for elx in range(nelx):
      for ely in range(nely):
        n1 = (nely+1)*elx+ely 
        n2 = (nely+1)* (elx+1)+ely
        #print 'n', n1, n2
        edof = [2*n1,2*n1+1, 2*n2,2*n2+1, 2*n2+2,2*n2+3, 2*n1+2,2*n1+3]
        #print 'edof', edof
        E =x[ely,elx]**penal
        #print E*KE, K+.01
        for i in range(8):
            for j in range(8):
                #print edof[i],edof[j]
                   K[edof[i],edof[j]]=K[edof[i],edof[j]]+E*KE[i,j]
        #K[edof,:][:,edof] = K[edof,:][:,edof] + E*KE
        #print 'KXX',K[edof,:][:,edof]
    #py.transpose(K)    
    #print 'Final', K
    ''' DEFINE LOADS AND SUPPORTS 
    Left fixed, right tip load'''
    
    if (problem == 1):
        forcedDof = [2*(nelx+1)*(nely+1)-nely-1] # y force
        fixeddofs = py.arange(2*(nely+1))# left edge
        #print forcedDof, fixeddofs
    elif (problem == 2):
        forcedDof = 2*(nelx+1)*(nely+1) -1
        fixeddofs = py.arange(2*(nely+1))
    elif (problem == 3):
        forcedDof = py.array([2*(nelx+1)*(nely+1)-nely-1, 5*20*2+20-1]) # y force
        fixeddofs = py.arange(2*(nely+1)) # left edge
            
    F[forcedDof,0] = -1.0
    alldofs     = py.arange(2*(nely+1)*(nelx+1))
    freedofs    = list(set(alldofs) - set(fixeddofs))
    #K = K.todense
    #print K[freedofs,:][:,freedofs]
    #print F[freedofs,:]
    U[freedofs,:] = py.solve(K[freedofs,:][:,freedofs], F[freedofs,:]);
      
    U[fixeddofs,:]= 0;
    #input('abc')
    #print 'U',py.shape(U), U
    return U
            def sdp(c):
                # For fixed c solve the semidefinite program for Algorithm 4
                
                # Variable Gamma_plus (for \Gamma_{i+1})
                Gamma_plus = variable(2,2,name='Gamma_plus')

                # Constraints
                c0 = belongs(Gamma_plus, semidefinite_cone)
                c1 = belongs(Gamma - Gamma_plus, semidefinite_cone)
                c2 = belongs(2*c*Gamma_plus - Gamma_plus*J - J.T*Gamma_plus, semidefinite_cone)

                # Objective function
                obj = -exp(-2*c*dT)*det_rootn(Gamma_plus)
                
                # Find solution
                p = program(minimize(obj), [c0, c1, c2])
                return p.solve(quiet = True)
 def sdp(c):
     # For fixed c solve the semidefinite program for Algorithm 4
     
     # Variable Gamma_plus (for \Gamma_{i+1})
     d_plus = variable(2*n, 1, name='d_plus')
     
     # Constraints
     constr = []
     for j in range(2*n):
         ctt =  less_equals(d_plus[j,0], 0)
         constr.append( less_equals(-d_plus[j,0], 0))
         constr.append( less_equals( d_plus[j,0], d[j,0]))
         constr.append( less_equals( J[j,j]*d_plus[j,0] + sum([abs(J[i,j])*d_plus[i,0] for i in range(2*n)]) - abs(J[j,j])*d_plus[j,0], c* d_plus[j,0]))
     
     # Objective function
     obj = geo_mean(d_plus)
     # Find solution
     p = program(maximize(obj), constr)
     
     return exp(c*dT)/p.solve(quiet = False)
Beispiel #13
0
def solve(A, B):
    return pl.solve(A, B)
Beispiel #14
0
def pseudoSpect(A, npts=200, s=2., gridPointSelect=100, verbose=True,
                lstSqSolve=True):
    """ 
    original code from http://www.cs.ox.ac.uk/projects/pseudospectra/psa.m
    % psa.m - Simple code for 2-norm pseudospectra of given matrix A.
    %         Typically about N/4 times faster than the obvious SVD method.
    %         Comes with no guarantees!   - L. N. Trefethen, March 1999.
    
    parameter: A: the matrix to analyze
               npts: number of points at the grid
               s: axis limits (-s ... +s)
               gridPointSelect: ???
               verbose: prints progress messages
               lstSqSolve: if true, use least squares in algorithm where
                  solve could be used (probably) instead. (replacement for
                  ldivide in MatLab)
    """
    
    from scipy.linalg import schur, triu
    from pylab import (meshgrid, norm, dot, zeros, eye, diag, find,  linspace,                       
                       arange, isreal, inf, ones, lstsq, solve, sqrt, randn,
                       eig, all)

    ldiv = lambda M1,M2 :lstsq(M1,M2)[0] if lstSqSolve else lambda M1,M2: solve(M1,M2)

    def planerot(x):
        '''
        return (G,y)
        with a matrix G such that y = G*x with y[1] = 0    
        '''
        G = zeros((2,2))
        xn = x / norm(x)
        G[0,0] = xn[0]
        G[1,0] = -xn[1]
        G[0,1] = xn[1]
        G[1,1] = xn[0]
        return G, dot(G,x)

    xmin = -s
    xmax = s
    ymin = -s
    ymax = s;  
    x = linspace(xmin,xmax,npts,endpoint=False)
    y = linspace(ymin,ymax,npts,endpoint=False)
    xx,yy = meshgrid(x,y)
    zz = xx + 1j*yy
     
    #% Compute Schur form and plot eigenvalues:
    T,Z = schur(A,output='complex');
        
    T = triu(T)
    eigA = diag(T)
    
    # Reorder Schur decomposition and compress to interesting subspace:
    select = find( eigA.real > -250)           # % <- ALTER SUBSPACE SELECTION
    n = len(select)
    for i in arange(n):
        for k in arange(select[i]-1,i,-1): #:-1:i
            G = planerot([T[k,k+1],T[k,k]-T[k+1,k+1]] )[0].T[::-1,::-1]
            J = slice(k,k+2)
            T[:,J] = dot(T[:,J],G)
            T[J,:] = dot(G.T,T[J,:])
          
    T = triu(T[:n,:n])
    I = eye(n);
    
    # Compute resolvent norms by inverse Lanczos iteration and plot contours:
    sigmin = inf*ones((len(y),len(x)));
    #A = eye(5)
    niter = 0
    for i in arange(len(y)): # 1:length(y)        
        if all(isreal(A)) and (ymax == -ymin) and (i > len(y)/2):
            sigmin[i,:] = sigmin[len(y) - i,:]
        else:
            for jj in arange(len(x)):
                z = zz[i,jj]
                T1 = z * I - T 
                T2 = T1.conj().T
                if z.real < gridPointSelect:    # <- ALTER GRID POINT SELECTION
                    sigold = 0
                    qold = zeros((n,1))
                    beta = 0
                    H = zeros((100,100))                
                    q = randn(n,1) + 1j*randn(n,1)                
                    while norm(q) < 1e-8:
                        q = randn(n,1) + 1j*randn(n,1)                
                    q = q/norm(q)
                    for k in arange(99):
                        v = ldiv(T1,(ldiv(T2,q))) - dot(beta,qold)
                        #stop
                        alpha = dot(q.conj().T, v).real
                        v = v - alpha*q
                        beta = norm(v)
                        qold = q
                        q = v/beta
                        H[k+1,k] = beta
                        H[k,k+1] = beta
                        H[k,k] = alpha
                        if (alpha > 1e100):
                            sig = alpha 
                        else:
                            sig = max(abs(eig(H[:k+1,:k+1])[0]))
                        if (abs(sigold/sig-1) < .001) or (sig < 3 and k > 2):
                            break
                        sigold = sig
                        niter += 1
                        #print 'niter = ', niter
                
                  #%text(x(jj),y(i),num2str(k))         % <- SHOW ITERATION COUNTS
                    sigmin[i,jj] = 1./sqrt(sig);
                #end
                #  end
        if verbose:
            print 'finished line ', str(i), ' out of ', str(len(y))
    
    return x,y,sigmin
Beispiel #15
0
def single_shooting(model, initial_u=0.4, plot=True):
    """Run single shooting of model model with a constant u.
    
    The function returns the optimal u.
    
    Notes:
     * Currently written specifically for VDP.
     * Currently only supports one input/control signal.
    
    Parameters:
    model -- the model which is to be simulated. Only models with one control
             signal is supported.
             
    Keyword parameters:
    initial_u -- the initial input U_0 used to initialize the optimization
                 with.
    
    """
    assert len(model.u) == 1, "More than one control signal is " \
                                         "not supported as of today."

    start_time = model.opt_interval_get_start_time()
    end_time = model.opt_interval_get_final_time()

    u = model.u
    u0 = N.array([initial_u])
    print "Initial u:", u

    gradient = None
    gradient_u = None

    def f(cur_u):
        """The cost evaluation function."""
        model.reset()
        u[:] = cur_u
        print "u is", u
        big_gradient, last_y, gradparams, sens = _shoot(
            model, start_time, end_time)

        model.set_x_p(last_y, 0)
        model.set_dx_p(model.dx, 0)
        model.set_u_p(model.u, 0)
        cost = model.opt_eval_J()

        gradient_u = cur_u.copy()
        gradient = big_gradient[gradparams['u_start']:gradparams['u_end']]

        print "Cost:", cost
        print "Grad:", gradient
        return cost

    def df(cur_u):
        """The gradient of the cost function.
        
        NOT USED right now.
        """
        model.reset()
        u[:] = cur_u
        print "u is", u
        big_gradient, last_y, gradparams, sens = _shoot(
            model, start_time, end_time)

        model.set_x_p(last_y, 0)
        model.set_dx_p(model.dx, 0)
        model.set_u_p(model.u, 0)
        cost = model.opt_eval_J()

        gradient_u = cur_u.copy()
        gradient = big_gradient[gradparams['u_start']:gradparams['u_end']]

        print "Cost:", cost
        print "Grad:", gradient
        return gradient

    p = NLP(f, u0, maxIter=1e3, maxFunEvals=1e2)
    p.df = df
    if plot:
        p.plot = 1
    else:
        p.plot = 0
    p.iprint = 1

    u_opt = p.solve('scipy_slsqp')
    return u_opt
Beispiel #16
0
    def run_optimization(self, plot=True, _only_check_gradients=False):
        """Start/run optimization procedure and the optimum unless.
        
        Set the keyword parameter 'plot' to False (default=True) if plotting
        should not be conducted.
        """
        grid = self.get_grid()
        model = self.get_model()

        # Initial try
        p0 = self.get_p0()

        # Less than (-0.5 < u < 1)
        # TODO: These are currently hard coded. They shouldn't be.
        #NLT = len(grid) * len(model.u)
        #Alt = N.zeros( (NLT, len(p0)) )
        #Alt[:, (len(grid) - 1) * len(model.x):] = -N.eye(len(grid) *
        #                                              len(model.u))
        #blt = -0.5*N.ones(NLT)

        # TODO: These are currently hard coded. They shouldn't be.
        #N_xvars = (len(grid) - 1) * len(model.x)
        #N_uvars = len(grid) * len(model.u)
        #N_vars = N_xvars + N_uvars
        #Alt = -N.eye(N_vars)
        #blt = N.zeros(N_vars)
        #blt[0:N_xvars] = -N.ones(N_xvars)*0.001
        #blt[N_xvars:] = -N.ones(N_uvars)*1;

        # Get OpenOPT handler
        p = NLP(
            self.f,
            p0,
            maxIter=1e3,
            maxFunEvals=1e3,
            #A=Alt, # See TODO above
            #b=blt, # See TODO above
            df=self.df,
            ftol=1e-4,
            xtol=1e-4,
            contol=1e-4)
        if len(grid) > 1:
            p.h = self.h
            p.dh = self.dh

        if plot:
            p.plot = 1
        p.iprint = 1

        if _only_check_gradients:
            # Check gradients against finite difference quotients
            p.checkdf(maxViolation=0.05)
            p.checkdh()
            return None

        #opt = p.solve('ralg') # does not work - serious convergence issues
        opt = p.solve('scipy_slsqp')

        if plot:
            plot_control_solutions(model, grid, opt.xf)

        return opt
Beispiel #17
0
    print ('Informe y[%i]: '%i)
    y0.append(float(input()))

for i in range(n):
    aux=[]
    for j in range(n):
        if j==0:
            aux.append(x0[i])
        if j==1:
            aux.append(1)
    A.append(aux)
print(A)

for i in range(n):
    aux=[]
    aux.append(y0[i])
    B.append(aux)


A = py.array(A)
b = py.array(B)

z = py.solve(A, b)

print(z)

x1= float(input('Informe um valor para interpolar: '))
for i in z:
    y=x1*z[0]+z[1]

print(y)
Beispiel #18
0
def pseudoSpect(A,
                npts=200,
                s=2.,
                gridPointSelect=100,
                verbose=True,
                lstSqSolve=True):
    """ 
    original code from http://www.cs.ox.ac.uk/projects/pseudospectra/psa.m
    % psa.m - Simple code for 2-norm pseudospectra of given matrix A.
    %         Typically about N/4 times faster than the obvious SVD method.
    %         Comes with no guarantees!   - L. N. Trefethen, March 1999.
    
    parameter: A: the matrix to analyze
               npts: number of points at the grid
               s: axis limits (-s ... +s)
               gridPointSelect: ???
               verbose: prints progress messages
               lstSqSolve: if true, use least squares in algorithm where
                  solve could be used (probably) instead. (replacement for
                  ldivide in MatLab)
    """

    from scipy.linalg import schur, triu
    from pylab import (meshgrid, norm, dot, zeros, eye, diag, find, linspace,
                       arange, isreal, inf, ones, lstsq, solve, sqrt, randn,
                       eig, all)

    ldiv = lambda M1, M2: lstsq(M1, M2)[
        0] if lstSqSolve else lambda M1, M2: solve(M1, M2)

    def planerot(x):
        '''
        return (G,y)
        with a matrix G such that y = G*x with y[1] = 0    
        '''
        G = zeros((2, 2))
        xn = x / norm(x)
        G[0, 0] = xn[0]
        G[1, 0] = -xn[1]
        G[0, 1] = xn[1]
        G[1, 1] = xn[0]
        return G, dot(G, x)

    xmin = -s
    xmax = s
    ymin = -s
    ymax = s
    x = linspace(xmin, xmax, npts, endpoint=False)
    y = linspace(ymin, ymax, npts, endpoint=False)
    xx, yy = meshgrid(x, y)
    zz = xx + 1j * yy

    #% Compute Schur form and plot eigenvalues:
    T, Z = schur(A, output='complex')

    T = triu(T)
    eigA = diag(T)

    # Reorder Schur decomposition and compress to interesting subspace:
    select = find(eigA.real > -250)  # % <- ALTER SUBSPACE SELECTION
    n = len(select)
    for i in arange(n):
        for k in arange(select[i] - 1, i, -1):  #:-1:i
            G = planerot([T[k, k + 1],
                          T[k, k] - T[k + 1, k + 1]])[0].T[::-1, ::-1]
            J = slice(k, k + 2)
            T[:, J] = dot(T[:, J], G)
            T[J, :] = dot(G.T, T[J, :])

    T = triu(T[:n, :n])
    I = eye(n)

    # Compute resolvent norms by inverse Lanczos iteration and plot contours:
    sigmin = inf * ones((len(y), len(x)))
    #A = eye(5)
    niter = 0
    for i in arange(len(y)):  # 1:length(y)
        if all(isreal(A)) and (ymax == -ymin) and (i > len(y) / 2):
            sigmin[i, :] = sigmin[len(y) - i, :]
        else:
            for jj in arange(len(x)):
                z = zz[i, jj]
                T1 = z * I - T
                T2 = T1.conj().T
                if z.real < gridPointSelect:  # <- ALTER GRID POINT SELECTION
                    sigold = 0
                    qold = zeros((n, 1))
                    beta = 0
                    H = zeros((100, 100))
                    q = randn(n, 1) + 1j * randn(n, 1)
                    while norm(q) < 1e-8:
                        q = randn(n, 1) + 1j * randn(n, 1)
                    q = q / norm(q)
                    for k in arange(99):
                        v = ldiv(T1, (ldiv(T2, q))) - dot(beta, qold)
                        #stop
                        alpha = dot(q.conj().T, v).real
                        v = v - alpha * q
                        beta = norm(v)
                        qold = q
                        q = v / beta
                        H[k + 1, k] = beta
                        H[k, k + 1] = beta
                        H[k, k] = alpha
                        if (alpha > 1e100):
                            sig = alpha
                        else:
                            sig = max(abs(eig(H[:k + 1, :k + 1])[0]))
                        if (abs(sigold / sig - 1) < .001) or (sig < 3
                                                              and k > 2):
                            break
                        sigold = sig
                        niter += 1
                        #print 'niter = ', niter

                #%text(x(jj),y(i),num2str(k))         % <- SHOW ITERATION COUNTS
                    sigmin[i, jj] = 1. / sqrt(sig)
                #end
                #  end
        if verbose:
            print 'finished line ', str(i), ' out of ', str(len(y))

    return x, y, sigmin
Beispiel #19
0
def FE(M,P,x,printResults=True):
	## FE analysis to solve Maxwell's equations in 2D for either H or E polarisation (=Helmholtz's equation)
	##		using periodic boundary conditions and wave expansions at the boundaries. The approach was originally
	##		implemented using Fuchi2010 and later modifications from Dossou2006 (original article) were added
	#
	#@param M		Model object containing geometrical information
	#@param P		Physics object containing physical parameters
	#@param x		The design domain with 0 corresponding to eps1 and 1 corresponding to eps2
	#						and intermediate values to weighted averages in between. See physics.interpolate
	#@param printResults	print results to stdout after simulation
	#@return			sol is the discretised solution, r are the complex reflection coefficients
	#						and t are the complex transmission coefficients

	#Calculate A and B, as the would be given in the Helmholtz equation in Eq (1) in Friis2012.
	#	(this notation makes it easy to switch between E and H field due to duality)

	A,B = P.interpolate(x)
	Mvv = assembleMvv(A,B,M,P)
	Mrv,Mvr,Mtv,Mvt,fvn,frn = assembleMxxfx(M,P)

	frn[M.Nm,0] = -M.lx			#mode 0

	lu = splu(Mvv)
	#Mhatrr and Mhattr
	b = lu.solve(Mvr)
	Mhatrr = -Mrv*b
	_addToDiagonal(Mhatrr, M.lx)
	Mhattr = -Mtv*b

	#Mhatrt and Mhattt
	b = lu.solve(Mvt)
	Mhatrt = -Mrv*b
	Mhattt = -Mtv*b
	_addToDiagonal(Mhattt, M.lx)

	#fhatrn
	b = lu.solve(fvn)
	a = Mrv*b
	fhatrn = frn-a

	#fhattn
	b = lu.solve(fvn)
	a = Mtv*b
	fhattn = -a

	MAT = pl.bmat([[Mhatrr, Mhatrt],
						[Mhattr, Mhattt]])
	RHS = pl.bmat([ [fhatrn],[fhattn]])

	V  = pl.solve(MAT,RHS)
	r = V[:M.NM,0]
	t = V[M.NM:,0]

	#Solve the system using LU factorisation (as recommended in Dossou2006, p 130, bottom)
	sol = lu.solve(fvn-Mvr*r-Mvt*t)
	print(pl.shape(r))
	print(pl.shape(t))
	print(pl.shape(sol))

	r = r.view(pl.ndarray).ravel()
	t = t.view(pl.ndarray).ravel()
	#Cast solution into a form that matches the input model
	sol = sol.reshape(M.nelx+1,M.nelz+1,order='F')
	#Print simulation results
	if printResults:
		_printResultsToScreen(M,P,r,t)
	print("r")
	print(r)
	print(t)
	print(sol)

	results = {}
	results["solution"] = sol
	results["x"] = x
	results["r"] = r
	results["t"] = t
	results.update(M.getParameters())
	results.update(P.getParameters())
	return results