def test_balls(self): ball_r1 = pymesh.generate_icosphere(1.0, [0.0, 0.0, 0.0], 4); ball_r2 = pymesh.generate_icosphere(2.0, [1.0, 0.0, 0.0], 4); ball_r3 = pymesh.generate_icosphere(3.0, [0.0, 1.0, 0.0], 4); ball_r1.add_attribute("vertex_gaussian_curvature"); ball_r2.add_attribute("vertex_gaussian_curvature"); ball_r3.add_attribute("vertex_gaussian_curvature"); ball_r1.add_attribute("vertex_mean_curvature"); ball_r2.add_attribute("vertex_mean_curvature"); ball_r3.add_attribute("vertex_mean_curvature"); gaussian_r1 = ball_r1.get_attribute("vertex_gaussian_curvature"); gaussian_r2 = ball_r2.get_attribute("vertex_gaussian_curvature"); gaussian_r3 = ball_r3.get_attribute("vertex_gaussian_curvature"); mean_r1 = ball_r1.get_attribute("vertex_mean_curvature"); mean_r2 = ball_r2.get_attribute("vertex_mean_curvature"); mean_r3 = ball_r3.get_attribute("vertex_mean_curvature"); self.assertAlmostEqual(1.0, np.amin(gaussian_r1), 2); self.assertAlmostEqual(1.0/4.0, np.amin(gaussian_r2), 2); self.assertAlmostEqual(1.0/9.0, np.amin(gaussian_r3), 2); self.assertAlmostEqual(1.0, np.amin(mean_r1), 2); self.assertAlmostEqual(1.0/2.0, np.amin(mean_r2), 2); self.assertAlmostEqual(1.0/3.0, np.amin(mean_r3), 2);
def test_balls(self): ball_r1 = pymesh.generate_icosphere(1.0, [0.0, 0.0, 0.0], 4) ball_r2 = pymesh.generate_icosphere(2.0, [1.0, 0.0, 0.0], 4) ball_r3 = pymesh.generate_icosphere(3.0, [0.0, 1.0, 0.0], 4) ball_r1.add_attribute("vertex_gaussian_curvature") ball_r2.add_attribute("vertex_gaussian_curvature") ball_r3.add_attribute("vertex_gaussian_curvature") ball_r1.add_attribute("vertex_mean_curvature") ball_r2.add_attribute("vertex_mean_curvature") ball_r3.add_attribute("vertex_mean_curvature") gaussian_r1 = ball_r1.get_attribute("vertex_gaussian_curvature") gaussian_r2 = ball_r2.get_attribute("vertex_gaussian_curvature") gaussian_r3 = ball_r3.get_attribute("vertex_gaussian_curvature") mean_r1 = ball_r1.get_attribute("vertex_mean_curvature") mean_r2 = ball_r2.get_attribute("vertex_mean_curvature") mean_r3 = ball_r3.get_attribute("vertex_mean_curvature") self.assertAlmostEqual(1.0, np.amin(gaussian_r1), 2) self.assertAlmostEqual(1.0/4.0, np.amin(gaussian_r2), 2) self.assertAlmostEqual(1.0/9.0, np.amin(gaussian_r3), 2) self.assertAlmostEqual(1.0, np.amin(mean_r1), 2) self.assertAlmostEqual(1.0/2.0, np.amin(mean_r2), 2) self.assertAlmostEqual(1.0/3.0, np.amin(mean_r3), 2)
def check_for_self_intersections(opts, mesh, points, points_int): si_points = set() count = 0 for i in range(len(points)): for j in range(len(points)): if i == j: continue pt0 = points[i] pt1 = points[(i + 1) % len(points)] pt2 = points[j] pt3 = points[(j + 1) % len(points)] if closed_segment_intersect(pt0, pt1, pt2, pt3): if i < j: si_points.add("%d-%d" % (i, j)) else: si_points.add("%d-%d" % (j, i)) si_points = list(si_points) dots = [] for pt in si_points: p0, p1 = pt.split('-') p_xyz = mesh.vertices[int(p0)] dots.append(pymesh.generate_icosphere(1, p_xyz)) if opts['debug']: dots.append(mesh) mesh = pymesh.merge_meshes(dots) save_mesh("si", mesh) return len(si_points)
def test_map_vertex_attributes_sphere_box(self): """ Map vertex attribute from sphere to box. """ mesh1 = pymesh.generate_icosphere(2.0, [0.0, 0.0, 0.0], 2) mesh2 = pymesh.generate_box_mesh(np.ones(3) - 2, np.ones(3), 10) Z = np.array([0, 0, 1]) theta = np.arctan2( np.dot(mesh1.vertices, Z), numpy.linalg.norm(np.cross(mesh1.vertices, Z), axis=1)) mesh1.add_attribute("theta") mesh1.set_attribute("theta", theta) pymesh.map_vertex_attribute(mesh1, mesh2, "theta") self.assertTrue(mesh2.has_attribute("theta")) ground_truth = np.arctan2( np.dot(mesh2.vertices, Z), numpy.linalg.norm(np.cross(mesh2.vertices, Z), axis=1)) theta2 = mesh2.get_vertex_attribute("theta").ravel() residual = numpy.linalg.norm(ground_truth - theta2)**2 / mesh2.num_vertices self.assertLess(residual, 1e-2)
def test_map_vertex_attributes_sphere(self): """ Map vertex attribute between two spheres. """ mesh1 = pymesh.generate_icosphere(2.0, [0.0, 0.0, 0.0], 2) mesh2 = pymesh.generate_icosphere(2.0, [0.0, 0.0, 0.0], 3) mesh1.add_attribute("x") mesh1.set_attribute("x", mesh1.vertices[:, 0]) pymesh.map_vertex_attribute(mesh1, mesh2, "x") self.assertTrue(mesh2.has_attribute("x")) x = mesh2.get_vertex_attribute("x").ravel() ground_truth = mesh2.vertices[:, 0] residual = numpy.linalg.norm(ground_truth - x)**2 / mesh2.num_vertices self.assertLess(residual, 1e-2)
def test_cut_sphere(self): mesh = generate_icosphere(1.0, np.zeros(3)) self.assertEqual(2, mesh.euler_characteristic) mesh = cut_to_disk(mesh) num_bd_loops = mesh.num_boundary_loops self.assertEqual(0, num_bd_loops) self.assertEqual(2 - num_bd_loops, mesh.euler_characteristic)
def test_map_corner_attribute_sphere(self): mesh1 = pymesh.generate_icosphere(2.0, [0.0, 0.0, 0.0], 2) mesh2 = pymesh.generate_icosphere(2.1, [0.0, 0.0, 0.0], 2) value = np.arange(mesh1.num_faces * mesh1.vertex_per_face) mesh1.add_attribute("test", dtype=np.int32) mesh1.set_attribute("test", value) pymesh.map_corner_attribute(mesh1, mesh2, "test") self.assertTrue(mesh2.has_attribute("test")) mapped_value = mesh2.get_attribute("test") diff = value - mapped_value largest_error = np.amax(np.absolute(diff)) self.assertLess(largest_error, 1e-12)
def test_radial_function(self): mesh = pymesh.generate_icosphere(1.0, [1.0, 1.0, 1.0], 2) tetgen = pymesh.tetgen() tetgen.points = mesh.vertices tetgen.triangles = mesh.faces tetgen.max_tet_volume = 0.001 tetgen.verbosity = 0 tetgen.run() mesh = tetgen.mesh self.assertLess(0, mesh.num_voxels) # Test solver to reproduce linear coordinate functions. solver = pymesh.HarmonicSolver.create(mesh) bd_indices = np.unique(mesh.faces.ravel()) target_solution = 1.0 / numpy.linalg.norm(mesh.vertices, axis=1) bd_values = target_solution[bd_indices] solver.boundary_indices = bd_indices solver.boundary_values = bd_values solver.order = 1 solver.pre_process() solver.solve() sol = solver.solution.ravel() #mesh.add_attribute("target_solution"); #mesh.set_attribute("target_solution", target_solution); #mesh.add_attribute("solution"); #mesh.set_attribute("solution", sol); #pymesh.save_mesh("tmp.msh", mesh, *mesh.attribute_names); self.assertEqual(mesh.num_vertices, len(sol)) self.assert_array_almost_equal(target_solution, sol, 2)
def test_linear_function(self): mesh = pymesh.generate_icosphere(1.0, np.zeros(3), 2) tetgen = pymesh.tetgen() tetgen.points = mesh.vertices tetgen.triangles = mesh.faces tetgen.max_tet_volume = 0.1 tetgen.verbosity = 0 tetgen.run() mesh = tetgen.mesh self.assertLess(0, mesh.num_voxels) # Test solver to reproduce linear coordinate functions. solver = pymesh.HarmonicSolver.create(mesh) bd_indices = np.unique(mesh.faces.ravel()) bd_values = mesh.vertices[bd_indices, 0] solver.boundary_indices = bd_indices solver.boundary_values = bd_values solver.pre_process() solver.solve() sol = solver.solution.ravel() self.assertEqual(mesh.num_vertices, len(sol)) self.assert_array_almost_equal(mesh.vertices[:, 0], sol, 12)
def test_simple(self): mesh = pymesh.generate_icosphere(1.0, np.zeros(3), 2) data = pymesh.compress(mesh) mesh2 = pymesh.decompress(data) self.assertEqual(mesh.num_vertices, mesh2.num_vertices) self.assertEqual(mesh.num_faces, mesh2.num_faces) self.assert_array_almost_equal(mesh.bbox, mesh2.bbox)
def get_regular_points(self, npoints=None, device='cuda'): if not self.npoints == npoints: self.mesh = pymesh.generate_icosphere(1, [0, 0, 0], 4) self.vertex = torch.from_numpy(self.mesh.vertices).to(device).float() self.num_vertex = self.vertex.size(0) self.vertex = self.vertex.transpose(0, 1).contiguous().unsqueeze(0) self.npoints = npoints return Variable(self.vertex.to(device))
def test_map_face_attribute_sphere(self): mesh1 = pymesh.generate_icosphere(2.0, [0.0, 0.0, 0.0], 2) mesh2 = pymesh.generate_icosphere(2.1, [0.0, 0.0, 0.0], 2) mesh1.add_attribute("face_centroid") centroids1 = mesh1.get_face_attribute("face_centroid") mesh2.add_attribute("face_centroid") centroids2 = mesh2.get_face_attribute("face_centroid") value = np.argmax(np.absolute(centroids1), axis=1) mesh1.add_attribute("value", dtype=np.int32) mesh1.set_attribute("value", value) pymesh.map_face_attribute(mesh1, mesh2, "value") self.assertTrue(mesh2.has_attribute("value")) mapped_value = mesh2.get_face_attribute("value").ravel() self.assert_array_equal(value, mapped_value)
def sphere(radius=0.1, center=[0, 0, 0], refinement_order=1, color=QColor("blue"), effect_f=CustomEffects.material, matrix=np.eye(4, dtype='f4'), name="sphere"): sph = pymesh.generate_icosphere(radius, center, refinement_order) return from_mesh(sph, color, effect_f, 1, matrix, name)
def test_tiny_mesh(self): """ Edge collapse performed on a tiny icosphere. """ mesh = generate_icosphere(1e-6, [0.0, 0.0, 0.0]); mesh, info = collapse_short_edges(mesh, 0.1); self.assertTrue("face_sources" in mesh.attribute_names); self.assertEqual(0, mesh.num_vertices); self.assertEqual(0, mesh.num_faces); self.assertEqual(0, mesh.num_voxels);
def add_sphere(self, params: np.ndarray, translation: np.ndarray, rotation: np.ndarray): sphere = pymesh.generate_icosphere( params[0], np.array([0, 0, 0], dtype=np.float32), refinement_order=self.sphere_complexity, ) sphere = transform_mesh(sphere, translation, rotation) self.per_layer_combinations[0].append( CSGEntry(sphere, OpType.NONE, used=False))
def test_tiny_mesh(self): """ Edge collapse performed on a tiny icosphere. """ mesh = generate_icosphere(1e-6, [0.0, 0.0, 0.0]) mesh, info = collapse_short_edges(mesh, 0.1) self.assertTrue("face_sources" in mesh.attribute_names) self.assertEqual(0, mesh.num_vertices) self.assertEqual(0, mesh.num_faces) self.assertEqual(0, mesh.num_voxels)
def get_regular_points(self, npoints=None, device="gpu0"): """ Get regular points on a Sphere Return Tensor of Size [x, 3] """ if not self.npoints == npoints: self.mesh = pymesh.generate_icosphere(1, [0, 0, 0], 4) # 2562 vertices self.vertex = torch.from_numpy(self.mesh.vertices).to(device).float() self.num_vertex = self.vertex.size(0) self.vertex = self.vertex.transpose(0,1).contiguous().unsqueeze(0) self.npoints = npoints return Variable(self.vertex.to(device))
def gen_geometry(print_code=True): sphere = pymesh.generate_icosphere(radius=1.0, center=[0, 0, 0]) n_vertices = sphere.num_faces * 3 vertices = np.full((n_vertices, 3), np.nan) for i_face in range(sphere.num_faces): face_vert = sphere.vertices[sphere.faces[i_face, :], :] i_vert = range(i_face * 3, i_face * 3 + 3) assert np.all(np.isnan(vertices[i_vert, :])) vertices[i_vert, :] = face_vert faces = np.arange(n_vertices).reshape((sphere.num_faces, 3)) mesh = pymesh.form_mesh(vertices=vertices, faces=faces) mesh.add_attribute("vertex_normal") normals = mesh.get_attribute("vertex_normal") if print_code: to_print = "points = np.array(\n [\n" for point in vertices.flat: to_print += " " * 4 * 2 + f"{point:+.08f},\n" to_print += " " * 4 + ']\n).astype("float32")\n' to_print += "\n" to_print += "normals = np.array(\n [\n" for point in normals.flat: to_print += " " * 4 * 2 + f"{point:+.08f},\n" to_print += " " * 4 + ']\n).astype("float32")\n' to_print += "\n" print(to_print) return (vertices, normals, mesh)
def test_attributes(self): mesh = pymesh.generate_icosphere(1.0, np.zeros(3), 2) mesh.add_attribute("vertex_index") mesh.add_attribute("vertex_normal") mesh.add_attribute("face_index") mesh.add_attribute("face_normal") data = pymesh.compress(mesh) mesh2 = pymesh.decompress(data) self.assertEqual(mesh.num_vertices, mesh2.num_vertices) self.assertEqual(mesh.num_faces, mesh2.num_faces) self.assert_array_almost_equal(mesh.bbox, mesh2.bbox) self.assertTrue(mesh2.has_attribute("vertex_index")) self.assertTrue(mesh2.has_attribute("vertex_normal")) #self.assertTrue(mesh2.has_attribute("face_index")); #self.assertTrue(mesh2.has_attribute("face_normal")); vertex_index_map = mesh2.get_attribute("vertex_index").ravel().astype( int) out_vertices = mesh2.vertices in_vertices = mesh.vertices[vertex_index_map] self.assert_array_equal(in_vertices, out_vertices)
def forward(): m = pm.generate_icosphere(1, [0, 0, 0]) pts, faces = m.vertices, m.faces uvs = mesh.gen_fake_uv(faces.shape[0]) pts = np.expand_dims(pts, 0).astype('float32') faces = np.expand_dims(faces, 0).astype('int32') uvs = np.expand_dims(uvs, 0).astype('float32') tex = ndimage.imread(os.path.join(misc.DATA_DIR, 'mesh', 'chessboard.jpg')) tex = np.expand_dims(tex, axis=0).astype('float32') / 255.0 tex[:, 0, 0, :] = 0 with tf.Session() as session: mv = camera.look_at(eye=tf.constant([2, 4, 4], dtype='float32'), center=tf.constant([0, 0, 0], dtype='float32'), up=tf.constant([0, 0, 1], dtype='float32')) mv = tf.expand_dims(mv, axis=0) H = 1600 W = 1600 proj = camera.perspective(focal=2000, H=H, W=W) proj = tf.expand_dims(proj, axis=0) n = 3 rendered, uvgrid, z, fids, bc = session.run( nr.render(pts=tf.tile(pts, [n, 1, 1]), faces=tf.tile(faces, [n, 1, 1]), uvs=tf.tile(uvs, [n, 1, 1, 1]), tex=tf.tile(tex, [n, 1, 1, 1]), modelview=tf.tile(mv, [n, 1, 1]), proj=tf.tile(proj, [n, 1, 1]), H=H, W=W)) print('rendering done') print(np.min(fids)) plt.figure() plt.imshow(rendered[-1, :, :, :]) plt.show()
num_segments=32) pipe2 = pymesh.generate_cylinder(p0=vertices[1, :], p1=vertices[2, :], r0=0.19, r1=0.19, num_segments=32) pipe2_outer = pymesh.generate_cylinder(p0=vertices[1, :], p1=vertices[2, :], r0=0.2, r1=0.2, num_segments=32) joint_sphere = pymesh.generate_icosphere(0.195, vertices[1, :], refinement_order=2) joint_sphere_outer = pymesh.generate_icosphere(0.205, vertices[1, :], refinement_order=2) inner_tree = pymesh.CSGTree( {"union": [{ "mesh": pipe1 }, { "mesh": joint_sphere }, { "mesh": pipe2 }]})
def main(): args = parse_args(); mesh = pymesh.load_mesh(args.input_mesh); num_tets = mesh.num_voxels; assert(mesh.dim == 3); assert(mesh.vertex_per_voxel == 4); assert(num_tets > 0); mesh = fit_into_unit_sphere(mesh); mesh.add_attribute("voxel_centroid"); assembler = pymesh.Assembler(mesh); if args.charge_distribution == "sphere": ball = pymesh.generate_icosphere(1.25 + 1e-3, np.zeros(3), 0); charges = ball.vertices; elif args.charge_distribution == "center": charges = np.zeros(3); else: raise NotImplementedError("Unsupported charge distribution ({})."\ .format(args.charge_distribution)); if args.output_kernels: kernels = pymesh.merge_meshes([ pymesh.generate_icosphere(0.05, v, 2) for v in charges ]); pymesh.save_mesh("kernel.msh", kernels); f = test_function(charges); g = test_function_grad(charges); v_pts = mesh.vertices; q_pts = get_quadrature_pts(mesh); c_pts = mesh.get_voxel_attribute("voxel_centroid"); v_values = f(v_pts); q_values = f(q_pts); c_values = f(c_pts); q_grad = g(q_pts); c_grad = g(c_pts); c_grad_norm = numpy.linalg.norm(c_grad, axis=1); q_grad_norm = numpy.linalg.norm(q_grad, axis=1); #for v,val in zip(v_pts, v_values): # print(v, val); assert(len(v_values) == len(v_pts)); assert(len(q_values) == len(q_pts)); assert(len(c_values) == len(c_pts)); assert(len(q_grad) == len(q_pts)); assert(len(c_grad) == len(c_pts)); bd_indices = np.unique(mesh.faces.ravel()).astype(int); bd_values = v_values[bd_indices]; solver = pymesh.HarmonicSolver.create(mesh); solver.order = 1; solver.boundary_indices = bd_indices; solver.boundary_values = bd_values; solver.pre_process(); solver.solve(); sol_values = solver.solution.ravel(); G = assembler.assemble("gradient"); sol_grad = (G * sol_values).reshape((-1,3), order="C"); sol_q_values, sol_q_grad = \ interpolate_at_quadrature_pts(mesh, sol_values, sol_grad); sol_c_values, sol_c_grad = \ interpolate_at_centroids(mesh, sol_values, sol_grad); v_err = sol_values - v_values; c_err = sol_c_values - c_values; q_err = sol_q_values - q_values; v_rel_err = np.divide(v_err, v_values); c_rel_err = np.divide(c_err, c_values); q_rel_err = np.divide(q_err, q_values); c_grad_err = sol_c_grad - c_grad; q_grad_err = sol_q_grad - q_grad; c_grad_err_norm = numpy.linalg.norm(c_grad_err, axis=1); q_grad_err_norm = numpy.linalg.norm(q_grad_err, axis=1); c_grad_rel_err_norm = np.divide(c_grad_err_norm, c_grad_norm); q_grad_rel_err_norm = np.divide(q_grad_err_norm, q_grad_norm); print("num_tets: {}".format(num_tets)); print("==Ground Truth=="); print("max solution at nodes: {}".format(np.amax(np.absolute(v_values)))); print("max solution at centroids: {}".format(np.amax(np.absolute(c_values)))); print("max solution at quadrature pts: {}".format(np.amax(np.absolute(q_values)))); print("max grad solution at centroids: {}".format(np.amax(c_grad_norm))); print("max grad solution at quadrature pts: {}".format(np.amax(q_grad_norm))); print("L2 solution at nodes: {}".format(numpy.linalg.norm(v_values))); print("L2 solution at centroids: {}".format(numpy.linalg.norm(c_values))); print("L2 solution at quadrature pts: {}".format(numpy.linalg.norm(q_values))); print("L2 grad solution at centroids: {}".format(numpy.linalg.norm(c_grad_norm))); print("L2 grad solution at quadrature pts: {}".format(numpy.linalg.norm(q_grad_norm))); print("sqrt ave at nodes: {}".format(math.sqrt(np.mean(np.square(v_values))))); print("sqrt ave at centroids: {}".format(math.sqrt(np.mean(np.square(c_values))))); print("sqrt ave at quadrature pts: {}".format(math.sqrt(np.mean(np.square(q_values))))); print("sqrt ave grad solution at centroids: {}".format(math.sqrt(np.mean(np.square(c_grad_norm))))); print("sqrt ave grad solution at quadrature pts: {}".format(math.sqrt(np.mean(np.square(q_grad_norm))))); print("==Absolute errors=="); print("max error at nodes: {}".format(np.amax(np.absolute(v_err)))); print("max error at centroids: {}".format(np.amax(np.absolute(c_err)))); print("max error at quadrature pts: {}".format(np.amax(np.absolute(q_err)))); print("max grad error at centroids: {}".format(np.amax(c_grad_err_norm))); print("max grad error at quadrature pts: {}".format(np.amax(q_grad_err_norm))); print("average error at nodes: {}".format(np.mean(np.absolute(v_err)))); print("average error at centroids: {}".format(np.mean(np.absolute(c_err)))); print("average error at quadrature pts: {}".format(np.mean(np.absolute(q_err)))); print("average grad error at centroids: {}".format(np.mean(c_grad_err_norm))); print("average grad error at quadrature pts: {}".format(np.mean(q_grad_err_norm))); print("L2 error at nodes: {}".format(numpy.linalg.norm(v_err))); print("L2 error at centroids: {}".format(numpy.linalg.norm(c_err))); print("L2 error at quadrature pts: {}".format(numpy.linalg.norm(q_err))); print("L2 grad error at centroids: {}".format(numpy.linalg.norm(c_grad_err_norm))); print("L2 grad error at quadrature pts: {}".format(numpy.linalg.norm(q_grad_err_norm))); print("==Relative errors=="); print("max rel error at nodes: {}".format(np.amax(np.absolute(v_rel_err)))); print("max rel error at centroids: {}".format(np.amax(np.absolute(c_rel_err)))); print("max rel error at quadrature pts: {}".format(np.amax(np.absolute(q_rel_err)))); print("max grad rel error at centroids: {}".format(np.amax(c_grad_rel_err_norm))); print("max grad rel error at quadrature pts: {}".format(np.amax(q_grad_rel_err_norm))); mesh.add_attribute("target_solution"); mesh.set_attribute("target_solution", v_values); mesh.add_attribute("solution"); mesh.set_attribute("solution", sol_values); mesh.add_attribute("v_error"); mesh.set_attribute("v_error", v_err); mesh.add_attribute("v_rel_error"); mesh.set_attribute("v_rel_error", v_rel_err); mesh.add_attribute("c_error"); mesh.set_attribute("c_error", c_err); mesh.add_attribute("c_rel_error"); mesh.set_attribute("c_rel_error", c_rel_err); mesh.add_attribute("q_error"); mesh.set_attribute("q_error", np.amax(np.absolute(q_err.reshape((-1,4), order="C")), axis=1)); mesh.add_attribute("q_rel_error"); mesh.set_attribute("q_rel_error", np.amax(np.absolute(q_rel_err.reshape((-1,4), order="C")), axis=1)); mesh.add_attribute("c_grad_error"); mesh.set_attribute("c_grad_error", c_grad_err_norm); mesh.add_attribute("c_grad_rel_error"); mesh.set_attribute("c_grad_rel_error", c_grad_rel_err_norm); mesh.add_attribute("q_grad_error"); mesh.set_attribute("q_grad_error", np.amax(q_grad_err_norm.reshape((-1,4), order="C"), axis=1)); mesh.add_attribute("q_grad_rel_error"); mesh.set_attribute("q_grad_rel_error", np.amax(q_grad_rel_err_norm.reshape((-1,4), order="C"), axis=1)); mesh.add_attribute("solution_grad"); mesh.set_attribute("solution_grad", sol_c_grad); mesh.add_attribute("target_grad"); mesh.set_attribute("target_grad", c_grad); pymesh.save_mesh(args.output_mesh, mesh, *mesh.attribute_names);
def main(): args = parse_args(); mesh = generate_icosphere(args.radius, center = args.center, refinement_order = args.refinement); save_mesh(args.output_mesh, mesh);
parser = argparse.ArgumentParser( description='Generate an image of constraints') parser.add_argument('inp', metavar='inp', type=str, help='Path to input shape') parser.add_argument('out', metavar='out', type=str, help='Name of the output') args = parser.parse_args() # by default in [0,0,0] with radius 1 constraint = pymesh.generate_icosphere(1, [0, 0, 0], 4) # 2562 vertices # Sphere with R=0.2 in (-0.05, 0.05, 0) vertices_1 = constraint.vertices * 0.11 + np.array([0, 0.05, 0]) # Sphere with R=0.1 in (0.3, 0, 0) vertices_2 = constraint.vertices * 0.088 + np.array([-0.4, 0, 0]) all_verts = np.concatenate((vertices_1, vertices_2), 0) all_faces = np.concatenate( (constraint.faces, constraint.faces + constraint.vertices.shape[0]), 0) image_constraints = visualize_constraint(all_verts, all_faces) image_filename = os.path.join("./constraint.png") imageio.imwrite(image_filename, image_constraints.astype(np.uint8)) car = trimesh.load(args.inp)
def make(Cosntellation): Clines_f = map(lambda s: s[:-1].split(), Clines) #read constellation lines information line_arr = pd.DataFrame(list(Clines_f)) line_arr = np.array(line_arr[ line_arr.loc[:, 0] == Cosntellation].iloc[0].dropna()[2:]).astype(int) #print(line_arr) dat = Table.read('hip.fit', format='fits') df = dat.to_pandas().set_index('HIP') # i llove pandas :) df = df.loc[np.unique(line_arr)] #print(df) RA_center = (np.max(df['_RA_icrs']) + np.min(df['_RA_icrs'])) / 2. #constellation center if np.max(df['_RA_icrs']) - np.min(df['_RA_icrs']) > 180: RA_center = (np.max(df['_RA_icrs']) - 360 + np.min(df['_RA_icrs'])) / 2. if RA_center < 0: RA_center += 360 DE_center = (np.max(df['_DE_icrs']) + np.min(df['_DE_icrs'])) / 2. #print(RA_center,DE_center) loc = EarthLocation(lat=DE_center * u.deg, lon=0 * u.deg) #convert coordinates fake_time = Time( '2019-09-21T00:01:40.2', format='isot', scale='utc', location=loc) + TimeDelta(RA_center / 360 * 86164, format='sec') fakeFrame = AltAz(obstime=fake_time, location=loc) cords = SkyCoord( list(df['_RA_icrs']) * u.deg, list(df['_DE_icrs']) * u.deg).transform_to(fakeFrame) df['phi'] = np.radians(cords.az.deg) + np.pi / 2 df['z'] = 90 - cords.alt.deg # df['phi'] = np.radians(df['_RA_icrs']) # df['z'] = 90 - df['_DE_icrs'] df['rho'] = df['z'] df['x'] = df['rho'] * np.cos(df['phi']) df['y'] = df['rho'] * np.sin(df['phi']) scale = np.max([df['x'], df['y']]) - np.min([df['x'], df['y']]) scale = 45 df['x'] *= 230 / scale #calculate scale df['y'] *= 230 / scale # import matplotlib.pyplot as plt # plt.plot(df['x'],df['y'],'o') # plt.show() print('coverted' + Cosntellation) star_list = [] for hip, star in df.iterrows(): #make stars r = 8 * 1.3**(-star['Vmag']) if r > 15: r = 15 sphere = pymesh.generate_icosphere(r, (star['x'], star['y'], 0), refinement_order=2) sphere = pymesh.form_mesh(sphere.vertices * np.array((1, 1, 0.75)), sphere.faces) star_list.append(sphere) mesh = pymesh.merge_meshes(star_list) print('stars' + Cosntellation) # print(df) cil_list = [] for i in range(0, len(line_arr), 2): #make lines cilinder = pymesh.generate_cylinder( (df.loc[line_arr[i], 'x'], df.loc[line_arr[i], 'y'], 0), (df.loc[line_arr[i + 1], 'x'], df.loc[line_arr[i + 1], 'y'], 0), 1.4, 1.4) cilinder = pymesh.form_mesh(cilinder.vertices * np.array((1, 1, 0.5)), cilinder.faces) cil_list.append(cilinder) cil_mesh = pymesh.merge_meshes(cil_list) print('lines' + Cosntellation) mesh = pymesh.boolean(mesh, cil_mesh, operation='union') DOWN = pymesh.meshutils.generate_box_mesh((-400, -400, -400), (400, 400, 0)) mesh = pymesh.boolean(mesh, DOWN, 'difference') pymesh.meshio.save_mesh('./' + Cosntellation + '.stl', mesh) print('completed' + Cosntellation)
obliquity = j * dobliq tau_BY_x, tau_BY_y, tau_BY_z, tau_l = compute_BY( body, obliquity, nphi, nphi_Sun, incl, phi0, phi_prec) o_arr[j] = obliquity * 180 / np.pi tau_l_arr[i, j] = tau_l print(i) return p_arr, o_arr, tau_l_arr # In[ ]: # In[12]: # create a sphere of radius 1 center = np.array([0, 0, 0]) sphere = pymesh.generate_icosphere(1., center, refinement_order=2) sphere.add_attribute("face_area") sphere.add_attribute("face_normal") sphere.add_attribute("face_centroid") print(volume_mesh(sphere)) nf_mesh(sphere) # create a perturbed ellipsoid using the above sphere devrand = 0.025 # perturbation size # fiducial model aratio1 = 0.5 # axis ratios c/a aratio2 = 0.7 # b/a random.seed(1) # fix sequence psphere1 = sphere_perturb(sphere, devrand, 1, 1) #perturbed sphere body1 = body_stretch(psphere1, aratio1, aratio2) # stretch #print(volume_mesh(body1)) #check volume
def main(): args = parse_args() mesh = generate_icosphere(args.radius, center=args.center, refinement_order=args.refinement) save_mesh(args.output_mesh, mesh)
meshname = arg if gotGid: meshname = meshname + str(gid) return meshname, gid, refinement if __name__ == "__main__": meshname, gid, refinement = args(sys.argv[1:]) gamma = gamma * np.pi / 180 ell = 2.0 * np.sin(0.5 * gamma) beta = np.sqrt(np.log(sigma**2 + 1.0)) # Autocorrelation if (cflg == 1): a_l = power_lcoef(l, nu) if (cflg == 2): a_l = mgaussian_lcoef(l, ell) seed(gid) std = coef_std(a_l, beta, l) # Generate a sample Gaussian sphere with id gid, then move to discretization and output sphere = pymesh.generate_icosphere(1.0, [0., 0., 0.], 3) a_lm, b_lm = sample_gaussian_sphere_coef(std, l) new_vertices = deform(sphere, a_lm, b_lm, beta) gsphere = pymesh.form_mesh(new_vertices, sphere.elements) tetramesh = draw_mesh(meshname, gsphere, refinement) # pymesh.save_mesh(meshname+".mesh",tetramesh)
def one_pipe_making(pointlist, diameter, thickness=0.1, extra_safe_percent=0.05, joint_amplification=0.01, segments=32): # lists to store geometries inner_geometries = [] outer_geometries = [] number_of_points = pointlist.shape[0] # radius for inner and outer geometries outer_radius = diameter / 2 inner_radius = outer_radius - thickness # a little bit bigger for joints outer_radius_sphere = outer_radius + outer_radius * joint_amplification inner_radius_sphere = inner_radius + inner_radius * joint_amplification for i, point in enumerate(pointlist): print(i, point) # calculating the joint spheres: # first and last points does not have any joint if (i > 0) and (i < (number_of_points - 1)): joint_sphere = pymesh.generate_icosphere(inner_radius_sphere, point, refinement_order=2) joint_sphere_outer = pymesh.generate_icosphere(outer_radius_sphere, point, refinement_order=2) inner_geometries.append(joint_sphere) outer_geometries.append(joint_sphere_outer) if i < (number_of_points - 1): # the outer pipe must not have the safe margin p2 = pointlist[ i + 1, :] # except for the last inner segment, it will always be this point outer_pipe = pymesh.generate_cylinder(p0=point, p1=p2, r0=outer_radius, r1=outer_radius, num_segments=segments) outer_geometries.append(outer_pipe) # we neeed to apply some safe margin, to avoid thin triangles if i == 0: # b_a is vector from B to A b_a = point - p2 point += b_a * extra_safe_percent if i == (number_of_points - 2): a_b = p2 - point p2 += a_b * extra_safe_percent inner_pipe = pymesh.generate_cylinder(p0=point, p1=p2, r0=inner_radius, r1=inner_radius, num_segments=32) inner_geometries.append(inner_pipe) # now the inner and outer trees for combinations print('joining from geometries') innerlist = [{'mesh': geometry} for geometry in inner_geometries] outerlist = [{'mesh': geometry} for geometry in outer_geometries] inner_tree = pymesh.CSGTree({"union": innerlist}) outer_tree = pymesh.CSGTree({"union": outerlist}) pipe_tree = pymesh.CSGTree({"difference": [outer_tree, inner_tree]}) ret_mesh = pipe_tree.mesh return ret_mesh