def new_solver(bilin, lin):
    #løser
    sparse_A = sp.csr_matrix(bilin)
    sparse_sol = solver(sparse_A, lin)
    solution = np.asarray(sparse_sol)
    #legger inn løsningen av ligningssystemet på riktig plass, i.e. setter dirichlet-nodene til verdi 0.
    return solution
Esempio n. 2
0
    def seamless_blend(self, mixed=False):
        """Perform blending with given images

        Returns:
            result: Output image after blending

        Raises:
            ValueError: Throw exception if input images are not of
                same dimensions
        """
        # Throw error if the input dimensions are not same
        if not self.__check_input_dimensions():
            raise ValueError('Input dimensions of all images should be same')

        # Get number of channels
        channels = self.source.shape[-1]
        result = np.copy(self.target).astype(int)

        self.laplacian()

        # Replace with new intensities
        if len(self.source.shape) == 2:
            self.evaluate_RHS(self.source, self.target)

            # Solve the system of equations
            u = solver(self.A, self.B)

            for i, pixel in enumerate(self.masked_pixels):
                result[pixel] = u[0][i]

        else:
            for i in range(channels):
                self.evaluate_RHS(self.source[:, :, i], self.target[:, :, i],
                                  mixed)

                # Solve the system of equations
                u = solver(self.A, self.B)[0].round()
                self.debug = u
                tmp = np.copy(self.target[:, :, i]).astype(int)
                self.debug2 = tmp

                for j, pixel in enumerate(self.masked_pixels):
                    tmp[pixel] = u[j]

                result[:, :, i] = tmp

        return result
Esempio n. 3
0
def shapeopt(RBF, Kinit, Vinit, iel, LSFip):
    # Variables
    nelx = variables.nelx
    nely = variables.nely
    f = variables.f
    si_max = variables.si_max
    kappa = variables.kappa
    rhomin = variables.rhomin
    edof = variables.edof

    # Discard/free DOFs
    ndof = np.max(edof) + 1
    dofs = np.arange(ndof)
    disc = np.setdiff1d(edof[iel == 0, :], edof[iel != 0, :])
    free = np.setdiff1d(dofs, np.append(variables.fix, disc))
    dofs[np.append(variables.fix, disc)] = -1

    # Optimizer initialization (MMA)
    mma = optimizers.MMA(variables.nele,
                         dmax=si_max,
                         dmin=-si_max,
                         movelimit=0.2,
                         asy=(0.5, 1.2, 0.65),
                         scaling=True)
    x = RBF[:, :, 2].T.reshape(-1).copy()
    iter = 1
    while iter < 10.5:
        # Stiffness matrix
        phi = LSFip.dot(x[:])
        rho = rhomin + (1 - rhomin) * (1 / (1 + np.exp(-kappa * phi)))
        K = FCM.K(Kinit, iel, rho)

        # Reverse Cuthill-McKee ordering
        ind = sp.csgraph.reverse_cuthill_mckee(K, symmetric_mode=True)
        free = dofs[ind][dofs[ind] != -1]

        # Solve (reduced) system
        u = np.zeros((np.size(K, 0), ))
        u[free] = solver(K[free, :][:, free], f[free])

        # Compliance objective and its sensitivity
        [C, dC] = obj(Kinit, iel, LSFip, u, phi, rho, f, free)

        # Volume fraction constraint and its sensitivity
        [g, dg] = constr(Vinit, iel, LSFip, phi, rho)

        # Shape optimization
        dx = mma.solve(x, C, dC, g, dg, iter)
        x = x + dx

        # Update log
        print(['%.3f' % i for i in [iter, C, g]])
        iter += 1

    RBF[:, :, 2] = x.reshape(nely, nelx).T
    return RBF
def geomextr(dens):

    nelx = variables.nelx
    nely = variables.nely
    nele = variables.nele
    RBF = variables.RBF

    X, Y = np.meshgrid(np.linspace(-3, 3, 7), np.linspace(3, -3, 7))
    indices = (X - Y * nelx).reshape(-1).astype(int)
    jA = np.empty(nele * 49, )
    sA = np.empty(nele * 49, )
    cc = 0
    for ely in range(0, nely):
        for elx in range(0, nelx):
            x = elx + 0.5
            y = ely + 0.5
            imin = max([elx - 3, 0])
            imax = min([elx + 4, nelx])
            jmin = max([ely - 3, 0])
            jmax = min([ely + 4, nely])
            Rexp = np.zeros((7, 7))
            Rexp[max([0,3-elx]):min([7,nelx-elx+3]),max(0,3-ely):min([7,nely-ely+3])] = \
                 np.exp(-(RBF[imin:imax,jmin:jmax,0]-x)**2-(RBF[imin:imax,jmin:jmax,1]-y)**2)
            jA[cc * 49:(cc + 1) * 49] = indices  #column, RBF
            sA[cc * 49:(cc + 1) * 49] = Rexp.T.reshape(-1)
            cc = cc + 1
            indices = indices + 1
    iA = np.repeat(np.arange(nele), 49).astype(int)
    jA = np.minimum(np.maximum(jA, 0), nele - 1).astype(int)
    A = sp.sparse.coo_matrix((sA, (iA, jA)), shape=(nele, nele)).tocsr()

    # Find initial weights LSF
    RBF[:, :, 2] = solver(A, dens).reshape(nely, nelx).T

    # Threshold the LSF on a contour value satisfying the volfrac constraint
    phi, wgts = LSF(variables, RBF)
    th = spopt.newton(area, 0.5, args=(variables, phi, wgts))

    # Change LSF to have solid-void contour on phi=0
    si_th = solver(A, np.ones(nele, ) * th).reshape(nely, nelx).T
    RBF[:, :, 2] = RBF[:, :, 2] - si_th

    return RBF
Esempio n. 5
0
  def solve(self, target):
      # create a copy of target for the residual
      res = target.copy(name="residual")

      # extract numpy vectors from target and res
      sol_coeff = target.as_numpy
      res_coeff = res.as_numpy

      n = 0
      while True:
          scheme(target, res)
          absF = math.sqrt( np.dot(res_coeff,res_coeff) )
          if absF < 1e-10:
              break
          scheme.jacobian(target,self.jacobian)
          sol_coeff -= solver(self.jacobian.as_numpy, res_coeff)
          n += 1
def sparsesolver3(bilin, lin, N, dirichlet, qs):

    bilin_sum = sp.lil_matrix((N, N))
    for i in range(len(qs)):
        bilin_sum += bilin[i] * qs[i]

    #fjerner dirichlet-noder
    bilin_sum[dirichlet, :] = 0
    bilin_sum[dirichlet, dirichlet] = 1
    lin[dirichlet] = 0
    #løser
    sparse_A = sp.csr_matrix(bilin_sum)
    sparse_sol = solver(sparse_A, lin)
    solution = np.asarray(sparse_sol)
    #legger inn løsningen av ligningssystemet på riktig plass, i.e. setter dirichlet-nodene til verdi 0.
    solution[dirichlet] = 0
    return solution
Esempio n. 7
0
 def _matvec(self, x_coeff):
     return solver(self.jacobian.as_numpy, x_coeff, tol=1e-10)[0]
Esempio n. 8
0
        def apply_prec(x):
            """Apply the block diagonal preconditioner"""
            m1 = P1.shape[0]
            m2 = P2.shape[0]
            n1 = P1.shape[1]
            n2 = P2.shape[1]

            res1 = P1.dot(x[:n1])
            res2 = P2.dot(x[n1:])
            return np.concatenate([res1, res2])
        p_shape = (P1.shape[0]+P2.shape[0], P1.shape[1]+P2.shape[1])
        return LinearOperator(p_shape, apply_prec, dtype=np.dtype('complex128'))


from scipy.sparse.linalg import gmres as solver
soln,err = solver(blocked,f_0,M=pre(blocked,bempp_space))

soln_fem = soln[:fem_size]
soln_bem = soln[fem_size:]


u=dolfin.Function(fenics_space)
u.vector()[:]=soln_fem

soln_bem_u = trace_matrix*soln_fem# - u_inc.coefficients

g_n_soln = bempp.api.GridFunction(bempp_space,coefficients=soln_bem)
g_soln = bempp.api.GridFunction(trace_space,coefficients=soln_bem_u)


# Plot a slice
Esempio n. 9
0
    print("done assembling bem")
    blocked = bempp.api.BlockedDiscreteOperator(blocks)
    precond = bempp.api.BlockedDiscreteOperator(precond_blocks)

    from scipy.sparse.linalg import gmres as solver
    it_count = 0

    def iteration_counter(x):
        global it_count
        it_count += 1

    print("solving")
    soln, err = solver(blocked,
                       f_0,
                       M=precond,
                       callback=iteration_counter,
                       tol=1E-8,
                       maxiter=50000,
                       restart=2000)

    print("converged after ", it_count, "steps")

    soln_fem = soln[:fem_size]
    soln_bem = soln[fem_size:]

    u = ngs.GridFunction(fem_space)

    u.vec.FV().NumPy()[:] = np.array(soln_fem.real, dtype=np.float_)

    #u_im=dolfin.Function(fenics_space)
    #u_im.vector()[:]=np.array(soln_fem.imag,dtype=np.float_)
Esempio n. 10
0
def topopt():
    # Variables
    E = variables.E
    nu = variables.nu
    Emin = variables.rhomin  #material
    nelx = variables.nelx
    nely = variables.nely
    nele = variables.nele  #domain
    edof = variables.edof  #DOFs
    f = variables.f
    fix = variables.fix  #BCs, loads
    volfrac = variables.volfrac
    pen = variables.pen_SIMP  #SIMP variables
    rmin = variables.rmin
    ft = variables.ft  #SIMP variables
    # Allocate design variables (as array), initialize and allocate sens.
    x = volfrac * np.ones(nele, dtype=float)
    xPhys = x.copy()
    # FE: Build the index vectors for the for coo matrix format.
    KE = lk(E, nu)
    edof = edof[:, 0:8]  #only nodal DOF
    # Construct the index pointers for the coo format
    iK = np.kron(edof, np.ones((8, 1))).flatten().astype(int)
    jK = np.kron(edof, np.ones((1, 8))).flatten().astype(int)
    # Filter: Build (and assemble) the index+data svectors for the coo matrix format
    nfilter = int(nele * ((2 * (np.ceil(rmin) - 1) + 1)**2))
    iH = np.zeros(nfilter)
    jH = np.zeros(nfilter)
    sH = np.zeros(nfilter)
    cc = 0
    for i1 in range(nely):
        for j1 in range(nelx):
            row = j1 + i1 * nelx  #current element
            for i2 in range(int(np.maximum(i1 - (np.ceil(rmin) - 1), 0)),
                            int(np.minimum(i1 + np.ceil(rmin), nely))):
                for j2 in range(int(np.maximum(j1 - (np.ceil(rmin) - 1), 0)),
                                int(np.minimum(j1 + np.ceil(rmin), nelx))):
                    col = j2 + i2 * nelx  #neighbour element
                    iH[cc] = row
                    jH[cc] = col
                    sH[cc] = np.maximum(
                        0, rmin - np.sqrt((i1 - i2)**2 + (j1 - j2)**2))
                    cc = cc + 1
    # Finalize assembly and convert to csc format
    H = sp.coo_matrix((sH, (iH, jH)), shape=(nele, nele)).tocsc()
    Hs = H.sum(1)
    # BCs, load, displ
    ndof = 2 * (nelx + 1) * (nely + 1)
    dofs = np.arange(ndof)
    fix = fix[fix <= ndof]
    free = np.setdiff1d(dofs, fix)
    # Force vector
    f = f[0:ndof]
    u = np.zeros((ndof, ))
    # Initialize optimizers gradient vectors
    mma = optimizers.MMA(nele,
                         dmax=1,
                         dmin=0,
                         movelimit=0.2,
                         asy=(0.5, 1.2, 0.65),
                         scaling=True)
    #oc = optimizers.OC(dmax=1,dmin=0,movelimit=0.2)
    #gOC = 0
    dg = np.ones(nele)
    dC = np.ones(nele)
    ce = np.ones(nele)
    iter = 1
    while iter < 50.5:
        # Setup and solve FE problem
        sK = ((KE.flatten()[np.newaxis]).T * (Emin + (xPhys)**pen *
                                              (E - Emin))).flatten(order='F')
        K = sp.coo_matrix((sK, (iK, jK)), shape=(ndof, ndof)).tocsr()
        # Solve system
        u[free] = solver(K[free, :][:, free], f[free])
        # Objective and sensitivity
        ce = (np.dot(u[edof].reshape(nele, 8), KE) *
              u[edof].reshape(nele, 8)).sum(1)
        C = ((Emin + xPhys**pen * (E - Emin)) * ce).sum()
        dC = (-pen * xPhys**(pen - 1) * (E - Emin)) * ce
        g = ((np.sum(xPhys) / nele) / volfrac) - 1
        dg = np.ones(nele)
        # Sensitivity filtering:
        if ft == 0:
            dC = np.asarray(
                (H *
                 (x * dC))[np.newaxis].T / Hs)[:, 0] / np.maximum(0.001, x)
        elif ft == 1:
            dC = np.asarray(H * (dC[np.newaxis].T / Hs))[:, 0]
            dg = np.asarray(H * (dg[np.newaxis].T / Hs))[:, 0]
        dx = mma.solve(x, C, dC, g, dg / (volfrac * nele), iter)
        #dx,gOC=oc.solve(x,C,dC,g,dg,gOC)
        x = x + dx
        # Filter design variables
        if ft == 0: xPhys = x
        elif ft == 1: xPhys = np.asarray(H * x[np.newaxis].T / Hs)[:, 0]
        # Update log
        print(['%.3f' % i for i in [iter, C, g]])
        iter += 1
    return xPhys