def test_toy_geometric(): filename = download_mesh( 'toy.msh', '1d125d3fa9f373823edd91ebae5f7a81' ) mesh, _, _, _ = voropy.read(filename) mesh = voropy.mesh_tetra.MeshTetra( mesh.node_coords, mesh.cells['nodes'], mode='geometric' ) run( mesh, volume=9.3875504672601107, convol_norms=[0.20175742659663737, 0.0093164692200450819], ce_ratio_norms=[13.497977312281323, 0.42980191511570004], cellvol_norms=[0.091903119589148916, 0.0019959463063558944], tol=1.0e-6 ) cc = mesh.get_cell_circumcenters() cc_norm_2 = fsum(cc.flat) cc_norm_inf = max(cc.flat) assert abs(cc_norm_2 - 1103.7038287583791) < 1.0e-12 assert abs(cc_norm_inf - 3.4234008596539662) < 1.0e-12 return
def _main(): args = _parse_input_arguments() # read the mesh print 'Reading the mesh...', mesh, point_data, field_data = voropy.read(args.filename) print 'done.' # build the model evaluator modeleval = gm.NlsModelEvaluator(mesh, g=field_data['g'], V=point_data['V'], A=point_data['A'], mu=field_data['mu'] ) param_range = np.linspace(args.parameter_range[0], args.parameter_range[1], args.num_parameter_steps) print 'Looking for solutions for %s in' % args.parameter print param_range print find_beautiful_states(modeleval, args.parameter, param_range, args.forcing_term ) return
def test_mark_subdomain3d(): filename = download_mesh( 'tetrahedron.msh', '27a5d7e102e6613a1e58629c252cb293', ) mesh, _, _, _ = voropy.read(filename) class Subdomain1(object): is_boundary_only = True def is_inside(self, x): return x[0] < 0.5 class Subdomain2(object): is_boundary_only = False def is_inside(self, x): return x[0] > 0.5 sd1 = Subdomain1() vertex_mask = mesh.get_vertex_mask(sd1) assert vertex_mask.sum() == 16 face_mask = mesh.get_face_mask(sd1) assert face_mask.sum() == 20 cell_mask = mesh.get_cell_mask(sd1) assert cell_mask.sum() == 0 sd2 = Subdomain2() vertex_mask = mesh.get_vertex_mask(sd2) assert vertex_mask.sum() == 10 face_mask = mesh.get_face_mask(sd2) assert face_mask.sum() == 25 cell_mask = mesh.get_cell_mask(sd2) assert cell_mask.sum() == 5 return
def test_mark_subdomain2d(): filename = download_mesh('pacman.msh', '2da8ff96537f844a95a83abb48471b6a') mesh, _, _, _ = voropy.read(filename) class Subdomain1(object): is_boundary_only = True def is_inside(self, x): return x[0] < 0.0 class Subdomain2(object): is_boundary_only = False def is_inside(self, x): return x[0] > 0.0 sd1 = Subdomain1() vertex_mask = mesh.get_vertex_mask(sd1) assert vertex_mask.sum() == 27 face_mask = mesh.get_face_mask(sd1) assert face_mask.sum() == 26 cell_mask = mesh.get_cell_mask(sd1) assert cell_mask.sum() == 0 sd2 = Subdomain2() vertex_mask = mesh.get_vertex_mask(sd2) assert vertex_mask.sum() == 214 face_mask = mesh.get_face_mask(sd2) assert face_mask.sum() == 1137 cell_mask = mesh.get_cell_mask(sd2) assert cell_mask.sum() == 371 return
def test_get_edges(): filename = download_mesh('pacman.msh', '2da8ff96537f844a95a83abb48471b6a') mesh, _, _, _ = voropy.read(filename) mesh.create_edges() edge_mask = mesh.get_edge_mask() edge_nodes = mesh.edges['nodes'][edge_mask] assert len(edge_nodes) == 1276 return
def test_pacman(self): filename = download_mesh( 'pacman.msh', '2da8ff96537f844a95a83abb48471b6a' ) mesh, _, _, _ = voropy.read(filename) self._run_test(mesh) return
def test_sphere(): filename = download_mesh('sphere.msh', '70a5dbf79c3b259ed993458ff4aa2e93') mesh, _, _, _ = voropy.read(filename) run(mesh, 12.273645818711595, [1.0177358705967492, 0.10419690304323895], [366.3982135866799, 1.7062353589387327], [0.72653362732751214, 0.05350373815413411]) # assertEqual(mesh.num_delaunay_violations(), 60) return
def test_pacman(): filename = download_mesh('pacman.msh', '2da8ff96537f844a95a83abb48471b6a') mesh, _, _, _ = voropy.read(filename, flat_cell_correction='boundary') run(mesh, 73.64573933105898, [3.5908322974649631, 0.26638548094154707], [354.8184824409405, 0.94690319745399243], [2.6213234038171014, 0.13841739494523228]) assert mesh.num_delaunay_violations() == 0 return
def test_tetrahedron(): filename = download_mesh( 'tetrahedron.msh', '27a5d7e102e6613a1e58629c252cb293' ) mesh, _, _, _ = voropy.read(filename) run( mesh, 64.1500299099584, [16.308991595922095, 7.0264329635751395], [6.898476155562041, 0.34400453539215237], [11.571692332290635, 2.9699087921277054] ) return
def test_io_2d(): vertices, cells = meshzoo.rectangle(0.0, 1.0, 0.0, 1.0, 2, 2, zigzag=True) mesh = voropy.mesh_tri.MeshTri(vertices, cells) # mesh, _, _, _ = voropy.read('pacman.vtu') assert mesh.num_delaunay_violations() == 0 mesh.show(show_axes=False, boundary_edge_color='g') mesh.show_vertex(0) _, fname = tempfile.mkstemp(suffix='.msh') mesh.write(fname) mesh2, _, _, _ = voropy.read(fname) for k in range(len(mesh.cells['nodes'])): assert tuple(mesh.cells['nodes'][k]) == tuple(mesh2.cells['nodes'][k]) return
def _main(): '''Main function. ''' args = _parse_input_arguments() # Setting the default file_mvp. if args.file_mvp is None: args.file_mvp = args.filename # Read the magnetic vector potential. mesh, point_data, field_data = voropy.read(args.file_mvp) # build the model evaluator print('Creating model evaluator...',) start = time.time() num_coords = len( mesh.node_coords ) nls_modeleval = pynosh.modelevaluator_nls.NlsModelEvaluator(mesh, V=-np.ones(num_coords), A=point_data['A'], preconditioner_type=args.preconditioner_type, num_amg_cycles = args.num_amg_cycles) if args.bordering: modeleval = pynosh.bordered_modelevaluator.BorderedModelEvaluator(nls_modeleval) else: modeleval = nls_modeleval end = time.time() print('done. (%gs)' % (end - start)) # Run through all time steps. assert len(args.timesteps) == len(args.mu), \ 'There must be as many time steps as mus (%d != %d).' \ % (len(args.timesteps), len(args.mu)) for (timestep, mu) in zip(args.timesteps, args.mu): relresvec = _solve_system(modeleval, args.filename, timestep, mu, args) print('relresvec:') print(relresvec) print('num iters:', len(relresvec)-1) if args.show_relres: pp.semilogy(relresvec, 'k') pp.show() return
def _main(): '''Main function. ''' args = _parse_input_arguments() mesh, point_data, field_data = voropy.read(args.filename, timestep=args.timestep ) N = len(mesh.node_coords) # build the model evaluator nls_modeleval = \ pynosh.modelevaluator_nls.NlsModelEvaluator( mesh, V=-np.ones(N), A=point_data['A'], preconditioner_type=args.preconditioner_type, num_amg_cycles=args.num_amg_cycles ) current_psi = np.random.rand(N, 1) + 1j * np.random.rand(N, 1) if args.bordering: modeleval = \ pynosh.bordered_modelevaluator.BorderedModelEvaluator( nls_modeleval ) # right hand side x = np.empty((N+1, 1), dtype=complex) x[0:N] = current_psi x[N] = 1.0 else: modeleval = nls_modeleval x = current_psi print 'machine eps = %g' % np.finfo(np.complex).eps mu = args.mu g = 1.0 # check the jacobian operator J = modeleval.get_jacobian(x, mu, g) print('max(|<v,Ju> - <Jv,u>|) = %g' % _check_selfadjointness(J, modeleval.inner_product) ) if args.preconditioner_type != 'none': # check the preconditioner P = modeleval.get_preconditioner(x, mu, g) print('max(|<v,Pu> - <Pv,u>|) = %g' % _check_selfadjointness(P, modeleval.inner_product) ) # Check positive definiteness of P. print('min(<u,Pu>) = %g' % _check_positivedefiniteness(P, modeleval.inner_product) ) # check the inverse preconditioner #Pinv = modeleval.get_preconditioner_inverse(x, mu, g) #print('max(|<v,P^{-1}u> - <P^{-1}v,u>|) = %g' # % _check_selfadjointness(Pinv, modeleval.inner_product # ) # check positive definiteness of P^{-1} #print('min(<u,P^{-1}u>) = %g' # % _check_positivedefiniteness(Pinv, inner_product) # ) return
def _solve_system(modeleval, filename, timestep, mu, args): # read the mesh print('Reading current psi...',) start = time.time() mesh, point_data, field_data = voropy.read(filename, timestep=timestep ) total = time.time() - start print('done (%gs).' % total) num_coords = len( mesh.node_coords ) # -------------------------------------------------------------------------- # set psi at which to create the Jacobian print('Creating initial guess and right-hand side...',) start = time.time() current_psi = (point_data['psi'][:,0] + 1j * point_data['psi'][:,1]).reshape(-1,1) # Perturb a bit. eps = 1.0e-10 perturbation = eps * (np.random.rand(num_coords) + 1j * np.random.rand(num_coords)) current_psi += perturbation.reshape(current_psi.shape) if args.bordering: phi0 = np.zeros((num_coords+1,1), dtype=complex) # right hand side x = np.empty((num_coords+1,1), dtype=complex) x[0:num_coords] = current_psi x[num_coords] = 0.0 else: # create right hand side and initial guess phi0 = np.zeros( (num_coords,1), dtype=complex ) x = current_psi # right hand side #rhs = np.ones( (num_coords,1), dtype=complex ) #rhs = np.empty( num_coords, dtype = complex ) #radius = np.random.rand( num_coords ) #arg = np.random.rand( num_coords ) * 2.0 * cmath.pi #for k in range( num_coords ): #rhs[ k ] = cmath.rect(radius[k], arg[k]) rhs = modeleval.compute_f(x=x, mu=mu, g=1.0) end = time.time() print('done. (%gs)' % (end - start)) print('||rhs|| = %g' % np.sqrt(modeleval.inner_product(rhs, rhs))) # -------------------------------------------------------------------------- # create the linear operator print('Getting Jacobian...',) start_time = time.clock() jacobian = modeleval.get_jacobian(x=x, mu=mu, g=1.0) end_time = time.clock() print('done. (%gs)' % (end_time - start_time)) # create precondictioner object print('Getting preconditioner...',) start_time = time.clock() prec = modeleval.get_preconditioner_inverse(x=x, mu=mu, g=1.0) end_time = time.clock() print('done. (%gs)' % (end_time - start_time)) # -------------------------------------------------------------------------- # Get reference solution #print 'Get reference solution (dim = %d)...' % (2*num_coords), #start_time = time.clock() #ref_sol, info, relresvec, errorvec = nm.minres_wrap( jacobian, rhs, #x0 = phi0, #tol = 1.0e-14, #M = prec, #inner_product = modeleval.inner_product, #explicit_residual = True #) #end_time = time.clock() #if info == 0: #print 'success!', #else: #print 'no convergence.', #print ' (', end_time - start_time, 's,', len(relresvec)-1 ,' iters).' if args.use_deflation: W = 1j * x AW = jacobian * W P, x0new = nm.get_projection(W, AW, rhs, phi0, inner_product = modeleval.inner_product ) else: #AW = np.zeros((len(current_psi),1), dtype=np.complex) P = None x0new = phi0 if args.krylov_method == 'cg': lin_solve = nm.cg elif args.krylov_method == 'minres': lin_solve = nm.minres #elif args.krylov_method == 'minresfo': #lin_solve = nm.minres #lin_solve_args.update({'full_reortho': True}) elif args.krylov_method == 'gmres': lin_solve = nm.gmres else: raise ValueError('Unknown Krylov solver ''%s''.' % args.krylov_method) print('Solving the system (len(x) = %d, bordering: %r)...' % (len(x), args.bordering),) start_time = time.clock() timer = False out = lin_solve(jacobian, rhs, x0new, tol = args.tolerance, Mr = P, M = prec, #maxiter = 2*num_coords, maxiter = 500, inner_product = modeleval.inner_product, explicit_residual = True, #timer=timer #exact_solution = ref_sol ) end_time = time.clock() print('done. (%gs)' % (end_time - start_time)) print('(%d,%d)' % (2*num_coords, len(out['relresvec'])-1)) # compute actual residual #res = rhs - jacobian * out['xk'] #print '||b-Ax|| = %g' % np.sqrt(modeleval.inner_product(res, res)) if timer: # pretty-print timings print(' '*22 + 'sum'.rjust(14) + 'mean'.rjust(14) + 'min'.rjust(14) + 'std dev'.rjust(14)) for key, item in out['times'].items(): print('\'%s\': %12g %12g %12g %12g' % (key.ljust(20), item.sum(), item.mean(), item.min(), item.std())) # Get the number of MG cycles. # 'modeleval.num_cycles' contains the number of MG cycles executed # for all AMG calls run. # In nm.minres, two calls to the precondictioner are done prior to the # actual iteration for the normalization of the residuals. # With explicit_residual=True, *two* calls to the preconditioner are done # in each iteration. # What we would like to have here is the number of V-cycles done per loop # when explicit_residual=False. Also, forget about the precondictioner # calls for the initialization. # Hence, cut of the first two and replace it by 0, and out of the # remainder take every other one. #nc = [0] + modeleval.tot_amg_cycles[2::2] #nc_cumsum = np.cumsum(nc) #pp.semilogy(nc_cumsum, out['relresvec'], color='0.0') #pp.show() #import matplotlib2tikz #matplotlib2tikz.save('cycle10.tex') #matplotlib2tikz.save('inf.tex') return out['relresvec']
def _main(): '''Main function. ''' args = _parse_input_arguments() # read the mesh mesh, point_data, field_data = voropy.read(args.filename, timestep=args.timestep ) # build the model evaluator modeleval = \ pynosh.modelevaluator_nls.NlsModelEvaluator(mesh = mesh, A = point_data['A'], V = point_data['V'], preconditioner_type = 'exact' ) # set the range of parameters steps = 10 mus = np.linspace(0.5, 5.5, steps) num_unknowns = len(mesh.node_coords) # initial guess for the eigenvectors #psi = np.random.rand(num_unknowns) + 1j * np.random.rand(num_unknowns) psi = np.ones(num_unknowns) #+ 1j * np.ones(num_unknowns) psi *= 0.5 #psi = 4.0 * 1.0j * np.ones(num_unknowns) print num_unknowns eigenvals_list = [] # -------------------------------------------------------------------------- g = 10.0 for mu in mus: if args.operator == 'k': # build dense KEO A = modeleval._get_keo(mu).todense() B = None elif args.operator == 'p': # build dense preconditioner P = modeleval.get_preconditioner(psi, mu, g) A = P.todense() B = None elif args.operator == 'j': # build dense jacobian J1, J2 = modeleval.get_jacobian_blocks(psi, mu, g) A = _build_stacked_operator(J1.todense(), J2.todense()) B = None elif args.operator == 'kj': J1, J2 = modeleval.get_jacobian_blocks(psi) A = _build_stacked_operator(J1.todense(), J2.todense()) modeleval._assemble_keo() K = _modeleval._keo B = _build_stacked_operator(K.todense()) elif args.operator == 'pj': J1, J2 = modeleval.get_jacobian_blocks(psi) A = _build_stacked_operator(J1.todense(), J2.todense()) P = modeleval.get_preconditioner(psi) B = _build_stacked_operator(P.todense()) else: raise ValueError('Unknown operator \'', args.operator, '\'.') print 'Compute eigenvalues for mu =', mu, '...' # get smallesteigenvalues start_time = time.clock() # use eig as the problem is not symmetric (but it is self-adjoint) eigenvals, U = eig(A, b = B, #lower = True, ) end_time = time.clock() print 'done. (', end_time - start_time, 's).' # sort by ascending eigenvalues assert norm(eigenvals.imag, np.inf) < 1.0e-14 eigenvals = eigenvals.real sort_indices = np.argsort(eigenvals.real) eigenvals = eigenvals[sort_indices] U = U[:,sort_indices] # rebuild complex-valued U U_complex = _build_complex_vector(U) # normalize for k in xrange(U_complex.shape[1]): norm_Uk = np.sqrt(modeleval.inner_product(U_complex[:,[k]], U_complex[:,[k]])) U_complex[:,[k]] /= norm_Uk ## Compare the different expressions for the eigenvalues. #for k in xrange(len(eigenvals)): # JU_complex = J1 * U_complex[:,[k]] + J2 * U_complex[:,[k]].conj() # uJu = modeleval.inner_product(U_complex[:,k], JU_complex)[0] # PU_complex = P * U_complex[:,[k]] # uPu = modeleval.inner_product(U_complex[:,k], PU_complex)[0] # KU_complex = modeleval._keo * U_complex[:,[k]] # uKu = modeleval.inner_product(U_complex[:,k], KU_complex)[0] # # expression 1 # lambd = uJu / uPu # assert abs(eigenvals[k] - lambd) < 1.0e-10, abs(eigenvals[k] - lambd) # # expression 2 # alpha = modeleval.inner_product(U_complex[:,k]**2, psi**2) # lambd = uJu / (-uJu + 1.0 - alpha) # assert abs(eigenvals[k] - lambd) < 1.0e-10 # # expression 3 # alpha = modeleval.inner_product(U_complex[:,k]**2, psi**2) # beta = modeleval.inner_product(abs(U_complex[:,k])**2, abs(psi)**2) # lambd = -1.0 + (1.0-alpha) / (uKu + 2*beta) # assert abs(eigenvals[k] - lambd) < 1.0e-10 # # overwrite for plotting # eigenvals[k] = 1- alpha eigenvals_list.append( eigenvals ) # -------------------------------------------------------------------------- # plot the eigenvalues #_plot_eigenvalue_series( mus, eigenvals_list ) for ev in eigenvals_list: pp.plot(ev, '.') #pp.plot( mus, #small_eigenvals_approx, #'--' #) #pp.legend() pp.title('eigenvalues of %s' % args.operator) #pp.ylim( ymin = 0.0 ) #pp.xlabel( '$\mu$' ) pp.show() #matplotlib2tikz.save('eigenvalues.tikz', #figurewidth = '\\figurewidth', #figureheight = '\\figureheight' #) return
def _main(): '''Main function. ''' args = _parse_input_arguments() # read the mesh mesh, point_data, field_data = voropy.read(args.filename, timestep=args.timestep ) num_nodes = len(mesh.node_coords) if not args.mu is None: mu = args.mu print 'Using mu=%g from command line.' % mu elif 'mu' in field_data: mu = field_data['mu'] else: raise ValueError('Parameter ''mu'' not found in file. Please provide on command line.') if not args.g is None: g = args.g print 'Using g=%g from command line.' % g elif 'g' in field_data: g = field_data['g'] else: raise ValueError('Parameter ''g'' not found in file. Please provide on command line.') # build the model evaluator nls_modeleval = nme.NlsModelEvaluator(mesh = mesh, V = point_data['V'], A = point_data['A'], preconditioner_type = 'exact', num_amg_cycles = 1 ) psi0 = point_data['psi'][:,0] + 1j * point_data['psi'][:,1] if args.bordering: # Build bordered system. x0 = np.empty(num_nodes+1, dtype=complex) x0[0:num_nodes] = psi0 x0[-1] = 0.0 # Use psi0 as initial bordering. modeleval = bme.BorderedModelEvaluator(nls_modeleval) else: x0 = psi0 modeleval = nls_modeleval if not args.series: # compute the eigenvalues once #p0 = 1j * psi0 #p0 /= np.sqrt(modeleval.inner_product(p0, p0)) #y0 = modeleval.get_jacobian(psi0) * p0 #print '||(ipsi) J (ipsi)|| =', np.linalg.norm(y0) ## Check with the rotation vector. #grad_psi0 = mesh.compute_gradient(psi0) #x_tilde = np.array( [-mesh.node_coords[:,1], mesh.node_coords[:,0]] ).T #p1 = np.sum(x_tilde * grad_psi0, axis=1) #mesh.write('test.e', point_data={'x grad': p1}) #nrm_p1 = np.sqrt(modeleval.inner_product(p1, p1)) #p1 /= nrm_p1 #y1 = modeleval.get_jacobian(psi0) * p1 #print '||(grad) J (grad)|| =', np.linalg.norm(y1) # Check the equality # grad(|psi|^2 psi) = 2 |psi|^2 grad(psi) + psi^2 grad(psi)*. # #p2 = mesh.compute_gradient(psi0 * abs(psi0)**2) #gradPsi0 = mesh.compute_gradient(psi0) #p2d = 2 * np.multiply(abs(psi0)**2, gradPsi0.T).T \ # + np.multiply(psi0**2, gradPsi0.conjugate().T).T #mesh.write('diff.vtu', #point_data = {'psi': psi0, 'p2': p2, 'p2d': p2d, 'diff': diff} #) # Check the equality # grad(|psi|^2) = 2 Re(psi* grad(psi)). # #p2 = mesh.compute_gradient(abs(psi0)**2) #p2d = 2 * np.multiply(psi0.conjugate(), mesh.compute_gradient(psi0).T).T.real #diff = p2 - p2d #mesh.write('diff.vtu', # point_data = {'psi': psi0, 'p2': p2, 'p2d': p2d, 'diff': diff} # ) #J = modeleval.get_jacobian(psi0) #K = modeleval._keo #x = np.random.rand(len(psi0)) #print 'x', np.linalg.norm(J*x - K*x/ mesh.control_volumes.reshape(x.shape)) eigenvals, X = _compute_eigenvalues(args.operator, args.eigenvalue_type, args.num_eigenvalues, None, x0[:,None], modeleval, mu, g ) print 'The following eigenvalues were computed:' print sorted(eigenvals) # Check residuals. print 'Residuals:' for k in xrange(len(eigenvals)): # Convert to complex representation. z = X[0::2,k] + 1j * X[1::2,k] z /= np.sqrt(modeleval.inner_product(z, z)) y0 = modeleval.get_jacobian(x0, mu, g) * z print np.linalg.norm(y0 - eigenvals[k] * z) # Normalize and store all eigenvectors & values. print 'Storing corresponding eigenstates...', k = 0 for k in xrange(len(eigenvals)): filename = 'eigen%d.vtu' % k # Convert to complex representation. z = X[0::2,k] + 1j * X[1::2,k] z /= np.sqrt(modeleval.inner_product(z, z)) mesh.write(filename, point_data = {'psi': point_data['psi'], 'A': point_data['A'], 'V': point_data['V'], 'eigen': z}, field_data = {'g': g, 'mu': mu, 'eigenvalue': eigenvals[k] } ) print 'done.' else: # initial guess for the eigenvectors X = np.ones((len(mesh.node_coords), 1)) # ---------------------------------------------------------------------- # set the range of parameters steps = 51 mus = np.linspace( 0.0, 0.5, steps ) eigenvals_list = [] #small_eigenvals_approx = [] for mu in mus: modeleval.set_parameter(mu) eigenvals, X = _compute_eigenvalues(args.operator, args.eigenvalue_type, args.num_eigenvalues, X[:, 0], modeleval, mu, g ) #small_eigenval, X = my_lobpcg( modeleval._keo, #X, #tolerance = 1.0e-5, #maxiter = len(pynoshmesh.nodes), #verbosity = 1 #) #print 'Calculated values: ', small_eigenval #alpha = modeleval.keo_smallest_eigenvalue_approximation() #print 'Linear approximation: ', alpha #small_eigenvals_approx.append( alpha ) #print eigenvals_list.append( eigenvals ) # plot all the eigenvalues as balls _plot_eigenvalue_series( mus, eigenvals_list ) #pp.legend() pp.title('%s eigenvalues of %s' % (args.eigenvalue_type, args.operator)) #pp.ylim( ymin = 0.0 ) pp.xlabel( '$\mu$' ) pp.show() #matplotlib2tikz.save('eigenvalues.tikz', #figurewidth = '\\figurewidth', #figureheight = '\\figureheight' #) # ---------------------------------------------------------------------- return