def __init__(self, fname, useRect=USE_RECT_ELEM_DEFAULT, overRefine=0): """ Generates a NURBS control mesh from PetIGA geometry input data (as generated, e.g., by a separate ``igakit`` script) in the file with name ``fname``. Alternatively, ``fname`` may be an ``igakit`` ``NURBS`` instance, for direct construction of the control mesh. The optional parameter ``useRect`` is a Boolean specifying whether or not to use rectangular FEs for the extraction. The optional parameter ``overRefine`` indicates how many levels of refinement to apply beyond what is needed to represent the spline functions; choosing a value greater than the default of zero may be useful for integrating functions with fine-scale features. overRefine > 0 only works for useRect=False. """ # get an igakit nurbs object from the file (or, directly from an # existing NURBS object) if (isinstance(fname, NURBS_ik)): ikNURBS = fname else: ikNURBS = PetIGA().read(fname) # create a BSpline scalar space given the knot vector(s) self.scalarSpline = BSpline(ikNURBS.degree, ikNURBS.knots, useRect, overRefine) # get the control net; already in homogeneous form nvar = len(ikNURBS.degree) if (nvar == 1): self.bnet = ikNURBS.control elif (nvar == 2): M = ikNURBS.control.shape[0] N = ikNURBS.control.shape[1] dim = ikNURBS.control.shape[2] self.bnet = zeros((M * N, dim)) for j in range(0, N): for i in range(0, M): self.bnet[ij2dof(i,j,M),:]\ = ikNURBS.control[i,j,:] else: M = ikNURBS.control.shape[0] N = ikNURBS.control.shape[1] O = ikNURBS.control.shape[2] dim = ikNURBS.control.shape[3] self.bnet = zeros((M * N * O, dim)) for k in range(0, O): for j in range(0, N): for i in range(0, M): self.bnet[ijk2dof(i,j,k,M,N),:]\ = ikNURBS.control[i,j,k,:]
def __init__(self,fname,useRect=USE_RECT_ELEM_DEFAULT): """ Generates a NURBS control mesh from PetIGA geometry input data (as generated, e.g., by a separate ``igakit`` script) in the file with name ``fname``. Alternatively, ``fname`` may be an ``igakit`` ``NURBS`` instance, for direct construction of the control mesh. The optional parameter ``useRect`` is a Boolean specifying whether or not to use rectangular FEs for the extraction. """ # get an igakit nurbs object from the file (or, directly from an # existing NURBS object) if(isinstance(fname,NURBS_ik)): ikNURBS = fname else: ikNURBS = PetIGA().read(fname) # create a BSpline scalar space given the knot vector(s) self.scalarSpline = BSpline(ikNURBS.degree,ikNURBS.knots,useRect) # get the control net; already in homogeneous form nvar = len(ikNURBS.degree) if(nvar==1): self.bnet = ikNURBS.control elif(nvar==2): M = ikNURBS.control.shape[0] N = ikNURBS.control.shape[1] dim = ikNURBS.control.shape[2] self.bnet = zeros((M*N,dim)) for j in range(0,N): for i in range(0,M): self.bnet[ij2dof(i,j,M),:]\ = ikNURBS.control[i,j,:] else: M = ikNURBS.control.shape[0] N = ikNURBS.control.shape[1] O = ikNURBS.control.shape[2] dim = ikNURBS.control.shape[3] self.bnet = zeros((M*N*O,dim)) for k in range(0,O): for j in range(0,N): for i in range(0,M): self.bnet[ijk2dof(i,j,k,M,N),:]\ = ikNURBS.control[i,j,k,:]
for i in range(0, REF_LEVEL): numNewKnots *= 2 h = 2.0 / float(numNewKnots) numNewKnots -= 1 knotList = [] for i in range(0, numNewKnots): knotList += [ float(i + 1) * h - 1.0, ] newKnots = array(knotList) ikNURBS.refine(0, newKnots) ikNURBS.refine(1, newKnots) # Output in PetIGA format if (mpirank == 0): PetIGA().write("out.dat", ikNURBS) MPI.barrier(worldcomm) ####### Preprocessing ####### if (mpirank == 0): print("Generating extraction...") # Read in the generated geometry to create a control mesh. splineMesh = NURBSControlMesh("out.dat", useRect=True) # Alternative: Create splineMesh directly from ikNURBS: #NURBSControlMesh(ikNURBS,useRect=True) # Create a spline generator for a spline with a single scalar field on the # given control mesh, where the scalar field is the same as the one used
from igakit.io import PetIGA from numpy import linspace #Geometry R = 1.0 c1 = circle(0.005 * R, (0, 0, 1)) c2 = circle(R, (0, 0, 1)) #c1 = circle(radius=R) #c2 = circle(radius=20*R) S = ruled(c1, c2).transpose().elevate(0, 1) #refine along X to_insertX = np.setdiff1d(linspace(0, 0.25, 11)[1:-1], S.knots[0]) S.refine(0, to_insertX) #to_insertX = np.setdiff1d(linspace(0.25,1.0,5)[1:-1],S.knots[0]); #S.refine(0,to_insertX) #refine along Y to_insertY = np.setdiff1d(linspace(0, 1.0, 21)[1:-1], S.knots[1]) S.refine(1, to_insertY) #S.elevate (1,1); #periodicity S.unclamp(1, continuity=1) #plt.plot(S,color='g') #plt.show() PetIGA().write("mesh.dat", S, nsd=3)
vectors[l[i + 1]] = range(j, j + dim) l = data[1].split() nSolScalars = int(l[0]) for i in range(nSolScalars): scalars[l[i + 1]] = nPrjtnScalars + dim * nPrjtnVectors + i l = data[2].split() nSolVectors = int(l[0]) for i in range(nSolVectors): j = nPrjtnScalars + dim * nPrjtnVectors + nSolScalars + i * dim vectors[l[i + 1]] = range(j, j + dim) data = {} cwdir = os.getcwd() geom = PetIGA().read('mesh.dat') inc = 1 if (nPrjtnScalars + nPrjtnVectors > 0): for filename1, filename2 in zip(glob.glob('outU*.dat'), glob.glob('outE*.dat')): if int(filename1.split(".")[0][4:]) >= bound: filename2 = "outE" + filename1.split(".")[0][4:] + ".dat" outname = "out" + filename1.split(".")[0][4:] + ".vtk" sol2 = PetIGA().read_vec(filename1, geom) sol1 = PetIGA().read_vec(filename2, geom) if (sol1.ndim == dim): sol1 = np.expand_dims(sol1, axis=dim) if (sol2.ndim == dim): sol2 = np.expand_dims(sol2, axis=dim) sol = np.concatenate((sol1, sol2), axis=dim)
Lista1 = glob.glob(fileName3) Lista2 = glob.glob(fileName4) if len(Lista2) > 0: fileName2 = fileName4 else: fileName2 = fileName3 try: meshName = sys.argv[3] except: meshName = "geometry" meshName = "./" + meshName + ".dat" # read in discretization info and potentially geometry nrb = PetIGA().read(meshName) Lista1 = glob.glob(fileName) Lista2 = glob.glob(fileName2) num1 = len(Lista1) num2 = len(Lista2) matA = numpy.ndarray([2, 2]) matB = numpy.ndarray([2, 2]) if num1 == num2: f1 = open('../../sharedResults/textSigma.txt', 'w') f2 = open('../../sharedResults/textExact.txt', 'w')
C[0, 1, :] = [0, -100, 100, 1] C[1, 1, :] = [100, -100, 100, 1] C[0, 2, :] = [0, 0, 100, 1] C[1, 2, :] = [100, 0, 100, 1] C[:, 1, :] *= val geom = NURBS([U, V], C) geom.elevate(0, max(p - 1, 0)).elevate(1, max(p - 2, 0)) h = 1. / N insert = np.linspace(h, 1. - h, N - 1) geom.refine(0, insert).refine(1, insert) if True: from igakit.io import PetIGA PetIGA().write("ClassicalShell.dat", geom, nsd=3) if False: from igakit.plot import plt plt.figure() plt.cpoint(geom) plt.cwire(geom) plt.kwire(geom) plt.surface(geom) plt.show() if False: from igakit.io import PetIGA, VTK nrb = PetIGA().read("ClassicalShell.dat") sol = PetIGA().read_vec("ClassicalShell.out", nrb) U = sol[..., :3]
U=knots; Curve = NURBS([U],C) S = revolve(Curve, circleFileName, (0,0), 1) print S.knots[0]; print S.knots[1]; #refine along X #to_insertX = np.setdiff1d(linspace(0.25,0.5,11)[1:-1],S.knots[0]); #S.refine(0,to_insertX) #refine along Y #to_insertY = np.setdiff1d(linspace(0,1.0,21)[1:-1],S.knots[1]); #S.elevate(0,1); #S.elevate(1,1); #S.refine(1,kX); #S.refine(1,kX); #S.insert(1,0.5,1) #S.rotate(1,0.5*Pi) if C2Continuity: S.elevate(0,1); S.elevate(1,1); S.unclamp(1, continuity=2); else: S.unclamp(1, continuity=1); # from igakit.io import PetIGA PetIGA().write(outputFileName, S, nsd=3)
def elastic_test(props): type = props.type() mode = props.mode() petsc_reinitialize() if mode=='tao': petsc_add_options([sys.argv[0]]+''' -tao_monitor -tao_converged_reason -tao_type nls -tao_nls_ksp_type petsc -ksp_type minres -tao_max_it 200 -ksp_max_it 500'''.split()) petsc_add_options([sys.argv[0]]+props.petsc().split()) comm = petsc_comm_world() d = props.dim() material = props.youngs_modulus(),props.poissons_ratio() rho_g = props.density()*props.gravity()*-axis_vector(d-1,d=d) # Diagnostic options petsc_add_options('ignored -tao_monitor -tao_converged_reason'.split()) if type=='iga': assert props.model()=='neo-hookean' iga = NeoHookeanElasticIGA[d](comm,material,rho_g) geom,boundary = iga_geometry(props,iga) iga.set_from_options() iga.set_up() # Boundary conditions x = iga.read_vec(boundary.name) dummy = 17 # Overwritten by set_fix_table for axis in xrange(d): for side in 0,1: for i in xrange(d): if axis==0 and side==0: iga.set_boundary_value(axis,side,i,0) iga.set_fix_table(x) if mode=='snes': snes = iga.create_snes() snes.set_from_options() elif mode=='tao': tao = iga.create_tao() tao.set_from_options() elif type=='fe': dm = dm_geometry(props,comm) degree = props.degree() degree = 1 petsc_add_options(['ignored','-petscspace_order',str(degree)]) if 0: # Would be needed for neumann petsc_add_options(['ignored','-bd_petscspace_order',str(degree)]) snes = SNES(comm) snes.set_dm(dm) fe = FE(comm,d,d), print('fe dofs = %s'%fe[0].dofs) fe_bd = fe_aux = () dm.create_default_section(('x',),fe,'wall',(0,)) start = identity_analytic(d) model = {'neo-hookean':NeoHookeanElasticModel,'laplace':LaplaceElasticModel}[props.model()] model = model[d](fe,fe_aux,fe_bd,start,material,rho_g) dm.set_model(model,mode=='tao') # Use a real objective for tao but not for snes A = dm.create_matrix() snes.set_jacobian(A,A) snes.set_from_options() if mode=='tao': tao = TaoSolver(comm) tao.set_snes(snes) tao.set_from_options() x = dm.create_global_vector() dm.project((start,),INSERT_VALUES,x) else: raise RuntimeError("unknown discretization type '%s'"%type) def check(*args): if props.check() and (mode=='snes' or type=='fe'): snes.consistency_test(x,1e-6,1e-3,2e-10,10) check() # Solve if mode=='snes': snes.add_monitor(check) snes.solve(None,x) elif mode=='tao': tao.set_initial_vector(x) tao.add_monitor(check) tao.solve() # View if props.view(): if type=='iga': geom_file = named_tmpfile(prefix='geom',suffix='.nurbs') x_file = named_tmpfile(prefix='x',suffix='.vec') iga.write(geom_file.name) iga.write_vec(x_file.name,x) from igakit.io import PetIGA geom = PetIGA().read(geom_file.name) x = PetIGA().read_vec(x_file.name,nurbs=geom) geom.control[...,:d] = x from igakit.plot import plt plt.figure() plt.cwire(geom) plt.kwire(geom) plt.surface(geom) plt.show() elif type=='fe': name = props.output() if not name: f = named_tmpfile(prefix='elastic',suffix='.vtk') name = f.name assert name.endswith('.vtk') dm.write_vtk(name,x) cmd = ['hollow-view',name] print(' '.join(cmd)) subprocess.check_call(cmd) else: raise RuntimeError("weird type '%s'"%type)
""" This python script shows the usage of igakit (https://bitbucket.org/dalcinl/igakit) to post-process results obtained using the demo code: ./demo/Poisson.c When running the C-code with the -save option, two data files are generated. One contains the geometry and discretization information, the other is the solution vector. """ from igakit.io import PetIGA, VTK from numpy import linspace # read in discretization info and potentially geometry nrb = PetIGA().read("PoissonGeometry.dat") # read in solution vector as a numpy array sol = PetIGA().read_vec("PoissonSolution.dat", nrb) # write a function to sample the nrbs object (100 points from beginning to end) uniform = lambda U: linspace(U[0], U[-1], 100) # write a binary VTK file VTK().write( "PoissonVTK.vtk", # output filename nrb, # igakit NURBS object fields=sol, # sol is the numpy array to plot sampler=uniform, # specify the function to sample points scalars={'solution': 0}) # adds a scalar plot to the VTK file
if len(Lista2) > 0: fileName = fileName2 else: fileName = fileName1 nombre = fileNameInput.split("*")[0] try: meshName = sys.argv[2] except: meshName = "geometry" meshName = "./" + meshName + ".dat" # read in discretization info and potentially geometry nrb = PetIGA().read(meshName) #for infile in glob.glob("results/poisson2d*.dat"): for infile in glob.glob(fileName): # read in solution vector as a numpy array try: sol = PetIGA().read_vec(infile, nrb) except: print('Mismatch in vector lengths, wrong mesh?, file=' + sys.argv[1]) sys.exit() outfile = infile[:-4] + ".vtk" #string[:-4] cuts the last 4 characters from the string, in this case ".dat" num = numpy.round(numpy.sqrt(sol.size / 2.0), decimals=0) #print(num)
# Parameter determining level of refinement REF_LEVEL = N_LEVELS + 3 # Refinement to_insert_u = linspace(min_uKnots, max_uKnots, 2**REF_LEVEL)[1:-1] to_insert_v = linspace(min_vKnots, max_vKnots, 2**REF_LEVEL)[1:-1] srf.refine(0, to_insert_u) srf.refine(1, to_insert_v) plt.plot(srf) plt_fig.savefig('savings/refined_surface.png') # Output in PetIGA format if (mpirank == 0): PetIGA().write("out.dat", srf) MPI.barrier(worldcomm) # Creating a control mesh from the NURBS splineMesh = NURBSControlMesh(srf, useRect=True) # Create a spline generator for a spline with a single scalar field on the # given control mesh, where the scalar field is the same as the one used # to determine the mapping $\mathbf{F}:\widehat{\Omega}\to\Omega$. splineGenerator = EqualOrderSpline(1, splineMesh) # Set Dirichlet Boundary conditions (left temperature at 0 and right temperature at 1) field = 0 scalarSpline = splineGenerator.getScalarSpline(field) for parametricDirection in [0, 1]: for side in [0, 1]:
if len(Lista2) > 0: fileName = fileName2 else: fileName = fileName1 nombre = fileNameInput.split("*")[0] try: meshName = sys.argv[2] except: meshName = "geometry" meshName = "./" + meshName + ".dat" # read in discretization info and potentially geometry nrb = PetIGA().read(meshName) # write a function to sample the nrbs object uniform = lambda U: linspace(U[0], U[-1], 96) for infile in glob.glob(fileName): # read in solution vector as a numpy array try: sol = PetIGA().read_vec( infile, nrb ) #Aqui esta el secreto, con esto puedo leer 2 archivos y quiza restarlos except: print('Mismatch in vector lengths, wrong mesh?, file=' + sys.argv[1]) sys.exit()