Skip to content

Commit 596c416

Browse files
committed
vtk show method and some cleaning with pylint (#57)
* vtk show method and some cleaning with pylint * show iges test
1 parent 210903c commit 596c416

File tree

6 files changed

+125
-52
lines changed

6 files changed

+125
-52
lines changed

pygem/igeshandler.py

Lines changed: 49 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
"""
22
Utilities for reading and writing different CAD files.
33
"""
4-
import numpy as np
54
import os
6-
import pygem.filehandler as fh
5+
import numpy as np
6+
from mpl_toolkits import mplot3d
7+
from matplotlib import pyplot
78
from OCC.IGESControl import (IGESControl_Reader, IGESControl_Writer)
89
from OCC.BRep import (BRep_Tool, BRep_Builder)
9-
from OCC.BRepBuilderAPI import (BRepBuilderAPI_NurbsConvert, BRepBuilderAPI_MakeWire, BRepBuilderAPI_MakeEdge, BRepBuilderAPI_MakeFace)
10+
from OCC.BRepBuilderAPI import (BRepBuilderAPI_NurbsConvert, BRepBuilderAPI_MakeWire)
11+
from OCC.BRepBuilderAPI import (BRepBuilderAPI_MakeEdge, BRepBuilderAPI_MakeFace)
1012
from OCC.GeomConvert import geomconvert_SurfaceToBSplineSurface
1113
import OCC.TopoDS
1214
from OCC.TopAbs import (TopAbs_FACE, TopAbs_EDGE)
@@ -15,9 +17,8 @@
1517
from OCC.Display.SimpleGui import init_display
1618
from OCC.ShapeFix import ShapeFix_ShapeTolerance
1719
from OCC.StlAPI import StlAPI_Writer
18-
from mpl_toolkits import mplot3d
19-
from matplotlib import pyplot
2020
from stl import mesh
21+
import pygem.filehandler as fh
2122

2223

2324
class IgesHandler(fh.FileHandler):
@@ -27,7 +28,8 @@ class IgesHandler(fh.FileHandler):
2728
:cvar string infile: name of the input file to be processed.
2829
:cvar string outfile: name of the output file where to write in.
2930
:cvar string extension: extension of the input/output files. It is equal to '.iges'.
30-
:cvar list control_point_position: index of the first NURBS control point (or pole) of each face of the iges file.
31+
:cvar list control_point_position: index of the first NURBS control point (or pole)
32+
of each face of the iges file.
3133
"""
3234
def __init__(self):
3335
super(IgesHandler, self).__init__()
@@ -51,22 +53,21 @@ def parse(self, filename):
5153
self._check_extension(filename)
5254

5355
self.infile = filename
54-
55-
## read in the IGES file
56+
57+
# read in the IGES file
5658
reader = IGESControl_Reader()
5759
reader.ReadFile(self.infile)
5860
reader.TransferRoots()
5961
shape = reader.Shape()
6062

61-
## cycle on the faces to get the control points
63+
# cycle on the faces to get the control points
6264
# init some quantities
6365
n_faces = 0
6466
control_point_position = [0]
6567
faces_explorer = TopExp_Explorer(shape, TopAbs_FACE)
66-
mesh_points = np.zeros(shape=(0,3))
67-
68-
while faces_explorer.More():
68+
mesh_points = np.zeros(shape=(0, 3))
6969

70+
while faces_explorer.More():
7071
# performing some conversions to get the right format (BSplineSurface)
7172
iges_face = OCC.TopoDS.topods_Face(faces_explorer.Current())
7273
iges_nurbs_converter = BRepBuilderAPI_NurbsConvert(iges_face)
@@ -81,27 +82,28 @@ def parse(self, filename):
8182
# extract the Control Points of each face
8283
n_poles_u = occ_face.NbUPoles()
8384
n_poles_v = occ_face.NbVPoles()
84-
control_polygon_coordinates = np.zeros(shape=(n_poles_u*n_poles_v,3))
85+
control_polygon_coordinates = np.zeros(shape=(n_poles_u * n_poles_v, 3))
8586

8687
# cycle over the poles to get their coordinates
8788
i = 0
8889
for pole_u_direction in xrange(n_poles_u):
8990
for pole_v_direction in xrange(n_poles_v):
90-
control_point_coordinates = occ_face.Pole(pole_u_direction+1,pole_v_direction+1)
91-
control_polygon_coordinates[i,:] = [control_point_coordinates.X(), control_point_coordinates.Y(), control_point_coordinates.Z()]
92-
i += 1
91+
control_point_coordinates = occ_face.Pole(pole_u_direction+1, pole_v_direction+1)
92+
control_polygon_coordinates[i, :] = [control_point_coordinates.X(), \
93+
control_point_coordinates.Y(), control_point_coordinates.Z()]
94+
i += 1
9395

9496
# pushing the control points coordinates to the mesh_points array (used for FFD)
9597
mesh_points = np.append(mesh_points, control_polygon_coordinates, axis=0)
96-
control_point_position.append(control_point_position[-1] + n_poles_u*n_poles_v)
98+
control_point_position.append(control_point_position[-1] + n_poles_u * n_poles_v)
9799

98100
n_faces += 1
99101
faces_explorer.Next()
100102

101103
self._control_point_position = control_point_position
102104

103105
return mesh_points
104-
106+
105107

106108
def write(self, mesh_points, filename):
107109
"""
@@ -117,18 +119,18 @@ def write(self, mesh_points, filename):
117119
self._check_extension(filename)
118120
self._check_infile_instantiation(self.infile)
119121

120-
self.outfile = filename
122+
self.outfile = filename
121123

122-
## init the ouput file writer
124+
# init the ouput file writer
123125
writer = IGESControl_Writer()
124126

125-
## read in the IGES file
127+
# read in the IGES file
126128
reader = IGESControl_Reader()
127129
reader.ReadFile(self.infile)
128130
reader.TransferRoots()
129131
shape_read = reader.Shape()
130132

131-
## cycle on the faces to update the control points position
133+
# cycle on the faces to update the control points position
132134
# init some quantities
133135
faces_explorer = TopExp_Explorer(shape_read, TopAbs_FACE)
134136
n_faces = 0
@@ -137,9 +139,8 @@ def write(self, mesh_points, filename):
137139
compound_builder = BRep_Builder()
138140
compound = OCC.TopoDS.TopoDS_Compound()
139141
compound_builder.MakeCompound(compound)
140-
142+
141143
while faces_explorer.More():
142-
143144
# similar to the parser method
144145
iges_face = OCC.TopoDS.topods_Face(faces_explorer.Current())
145146
iges_nurbs_converter = BRepBuilderAPI_NurbsConvert(iges_face)
@@ -156,18 +157,19 @@ def write(self, mesh_points, filename):
156157
i = 0
157158
for pole_u_direction in xrange(n_poles_u):
158159
for pole_v_direction in xrange(n_poles_v):
159-
control_point_coordinates = mesh_points[i+control_point_position[n_faces],:]
160-
point_xyz = gp_XYZ(control_point_coordinates[0], control_point_coordinates[1], control_point_coordinates[2])
160+
control_point_coordinates = mesh_points[i+control_point_position[n_faces], :]
161+
point_xyz = gp_XYZ(control_point_coordinates[0], control_point_coordinates[1], \
162+
control_point_coordinates[2])
161163
gp_point = gp_Pnt(point_xyz)
162-
occ_face.SetPole(pole_u_direction+1,pole_v_direction+1,gp_point)
164+
occ_face.SetPole(pole_u_direction+1, pole_v_direction+1, gp_point)
163165
i += 1
164166

165-
## construct the deformed wire for the trimmed surfaces
167+
# construct the deformed wire for the trimmed surfaces
166168
wire_maker = BRepBuilderAPI_MakeWire()
167169
tol = ShapeFix_ShapeTolerance()
168170
brep = BRepBuilderAPI_MakeFace(occ_face.GetHandle(), 1e-4).Face()
169171
brep_face = BRep_Tool.Surface(brep)
170-
172+
171173
# cycle on the edges
172174
edge_explorer = TopExp_Explorer(nurbs_face, TopAbs_EDGE)
173175
while edge_explorer.More():
@@ -181,10 +183,10 @@ def write(self, mesh_points, filename):
181183
wire_maker.Add(edge_phis_coordinates)
182184
edge_explorer.Next()
183185

184-
#grouping the edges in a wire
186+
# grouping the edges in a wire
185187
wire = wire_maker.Wire()
186188

187-
## trimming the surfaces
189+
# trimming the surfaces
188190
brep_surf = BRepBuilderAPI_MakeFace(occ_face.GetHandle(), wire).Shape()
189191
compound_builder.Add(compound, brep_surf)
190192
n_faces += 1
@@ -193,8 +195,8 @@ def write(self, mesh_points, filename):
193195
writer.AddShape(compound)
194196

195197
writer.Write(self.outfile)
196-
197-
198+
199+
198200
def plot(self, plot_file=None, save_fig=False):
199201
"""
200202
Method to plot an iges file. If `plot_file` is not given it plots `self.infile`.
@@ -212,55 +214,54 @@ def plot(self, plot_file=None, save_fig=False):
212214
reader = IGESControl_Reader()
213215
reader.ReadFile(plot_file)
214216
reader.TransferRoots()
215-
shape = reader.Shape()
216-
217+
shape = reader.Shape()
218+
217219
stl_writer = StlAPI_Writer()
218220
# Do not switch SetASCIIMode() from False to True.
219221
stl_writer.SetASCIIMode(False)
220-
stl_writer.Write(shape,'aux_figure.stl')
221-
222+
stl_writer.Write(shape, 'aux_figure.stl')
223+
222224
# Create a new plot
223225
figure = pyplot.figure()
224226
axes = mplot3d.Axes3D(figure)
225227

226228
# Load the STL files and add the vectors to the plot
227229
stl_mesh = mesh.Mesh.from_file('aux_figure.stl')
230+
os.remove('aux_figure.stl')
228231
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(stl_mesh.vectors))
229232

230233
# Auto scale to the mesh size
231234
scale = stl_mesh.points.flatten(-1)
232235
axes.auto_scale_xyz(scale, scale, scale)
233-
236+
234237
# Show the plot to the screen
235238
if not save_fig:
236239
pyplot.show()
237240
else:
238241
figure.savefig(plot_file.split('.')[0] + '.png')
239-
240-
os.remove('aux_figure.stl')
241-
242-
242+
243+
243244
def show(self, show_file=None):
244245
"""
245246
Method to show an iges file. If `show_file` is not given it plots `self.infile`.
246247
247-
:param string show_file: the iges filename you want to plot.
248+
:param string show_file: the iges filename you want to show.
248249
"""
249250
if show_file is None:
250251
show_file = self.infile
251252
else:
252253
self._check_filename_type(show_file)
253254

254-
## read in the IGES file
255+
# read in the IGES file
255256
reader = IGESControl_Reader()
256257
reader.ReadFile(show_file)
257258
reader.TransferRoots()
258-
shape = reader.Shape()
259-
260-
display, start_display, add_menu, add_function_to_menu = init_display()
259+
shape = reader.Shape()
260+
261+
display, start_display, __, __ = init_display()
261262
display.FitAll()
262263
display.DisplayShape(shape, update=True)
263-
264+
264265
# Show the plot to the screen
265266
start_display()
266267

pygem/stlhandler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def write(self, mesh_points, filename, write_bin=False):
7373
for i in range(0, n_triplets):
7474
for j in range(0, 3):
7575
data['vectors'][i][j] = mesh_points[3*i + j]
76-
76+
7777
if not write_bin:
7878
stl_mesh.save(self.outfile, mode=1, update_normals=True)
7979
else:

pygem/vtkhandler.py

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,9 +99,9 @@ def write(self, mesh_points, filename):
9999

100100
def plot(self, plot_file=None, save_fig=False):
101101
"""
102-
Method to plot an stl file. If `plot_file` is not given it plots `self.infile`.
102+
Method to plot a vtk file. If `plot_file` is not given it plots `self.infile`.
103103
104-
:param string plot_file: the stl filename you want to plot.
104+
:param string plot_file: the vtk filename you want to plot.
105105
:param bool save_fig: a flag to save the figure in png or not. If True the
106106
plot is not shown.
107107
"""
@@ -147,3 +147,50 @@ def plot(self, plot_file=None, save_fig=False):
147147
figure.savefig(plot_file.split('.')[0] + '.png')
148148

149149

150+
def show(self, show_file=None):
151+
"""
152+
Method to show a vtk file. If `show_file` is not given it shows `self.infile`.
153+
154+
:param string show_file: the vtk filename you want to show.
155+
"""
156+
if show_file is None:
157+
show_file = self.infile
158+
else:
159+
self._check_filename_type(show_file)
160+
161+
# Read the source file.
162+
reader = vtk.vtkUnstructuredGridReader()
163+
reader.SetFileName(show_file)
164+
reader.Update() # Needed because of GetScalarRange
165+
output = reader.GetOutput()
166+
scalar_range = output.GetScalarRange()
167+
168+
# Create the mapper that corresponds the objects of the vtk file
169+
# into graphics elements
170+
mapper = vtk.vtkDataSetMapper()
171+
if vtk.VTK_MAJOR_VERSION <= 5:
172+
mapper.SetInput(output)
173+
else:
174+
mapper.SetInputData(output)
175+
mapper.SetScalarRange(scalar_range)
176+
177+
# Create the Actor
178+
actor = vtk.vtkActor()
179+
actor.SetMapper(mapper)
180+
181+
# Create the Renderer
182+
renderer = vtk.vtkRenderer()
183+
renderer.AddActor(actor)
184+
# Set background color (white is 1, 1, 1)
185+
renderer.SetBackground(20, 20, 20)
186+
187+
# Create the RendererWindow
188+
renderer_window = vtk.vtkRenderWindow()
189+
renderer_window.AddRenderer(renderer)
190+
191+
# Create the RendererWindowInteractor and display the vtk_file
192+
interactor = vtk.vtkRenderWindowInteractor()
193+
interactor.SetRenderWindow(renderer_window)
194+
interactor.Initialize()
195+
interactor.Start()
196+

tests/test_igeshandler.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,8 @@ def test_iges_plot_failing_outfile_type(self):
153153
with self.assertRaises(TypeError):
154154
iges_handler.plot(plot_file=3)
155155

156+
157+
def test_iges_show_failing_outfile_type(self):
158+
iges_handler = ih.IgesHandler()
159+
with self.assertRaises(TypeError):
160+
iges_handler.show(show_file=1.1)

tests/test_stlhandler.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,13 @@ def test_stl_plot_save_fig_bin(self):
215215
os.remove('tests/test_datasets/test_sphere_bin.png')
216216

217217

218+
def test_stl_plot_save_fig_plot_file(self):
219+
stl_handler = sh.StlHandler()
220+
stl_handler.plot(plot_file='tests/test_datasets/test_sphere.stl', save_fig=True)
221+
self.assertTrue(os.path.isfile('tests/test_datasets/test_sphere.png'))
222+
os.remove('tests/test_datasets/test_sphere.png')
223+
224+
218225
def test_stl_plot_failing_outfile_type(self):
219226
stl_handler = sh.StlHandler()
220227
with self.assertRaises(TypeError):

tests/test_vtkhandler.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,10 +141,23 @@ def test_vtk_plot_failing_outfile_type(self):
141141
vtk_handler.plot(plot_file=1.1)
142142

143143

144-
def test_vtk_plot_save_fig(self):
144+
def test_vtk_plot_save_fig_infile(self):
145145
vtk_handler = vh.VtkHandler()
146146
mesh_points = vtk_handler.parse('tests/test_datasets/test_red_blood_cell.vtk')
147147
vtk_handler.plot(save_fig=True)
148148
self.assertTrue(os.path.isfile('tests/test_datasets/test_red_blood_cell.png'))
149149
os.remove('tests/test_datasets/test_red_blood_cell.png')
150150

151+
152+
def test_vtk_plot_save_fig_plot_file(self):
153+
vtk_handler = vh.VtkHandler()
154+
vtk_handler.plot(plot_file='tests/test_datasets/test_red_blood_cell.vtk', save_fig=True)
155+
self.assertTrue(os.path.isfile('tests/test_datasets/test_red_blood_cell.png'))
156+
os.remove('tests/test_datasets/test_red_blood_cell.png')
157+
158+
159+
def test_vtk_show_failing_outfile_type(self):
160+
vtk_handler = vh.VtkHandler()
161+
with self.assertRaises(TypeError):
162+
vtk_handler.show(show_file=1.1)
163+

0 commit comments

Comments
 (0)