-
Notifications
You must be signed in to change notification settings - Fork 2
/
plot2d.py
396 lines (333 loc) · 13.8 KB
/
plot2d.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# plot2d.py
"""
Contains routines to two-dimensional plots.
"""
from blendaviz.generic import GenericPlot
def mesh(x, y, z=None, c=None, alpha=None, vmax=None, vmin=None, color_map=None,
time=None):
"""
Plot a 2d surface with optional color.
Signature:
mesh(x, y, z=None, c=None, alpha=None, vmax=None, vmin=None, color_map=None,
time=None)
Parameters
----------
x, y, z: x, y and z coordinates of the points on the surface of shape (nu, nv)
or of shape (nu, nv, nt) for time dependent arrays.
If z == None then z = 0.
c: Values to be used for the colors.
Can be a character or string for constant color, e.g. 'red'
or array of shape (nu, nv) for time independent colors
or array of shape (nu, nv, nt) for time dependent colors.
alpha: Alpha values defining the opacity.
Single float or 2d array of shape (nu, nv).
vmin, vmax: Minimum and maximum values for the colormap.
If not specified, determine from the input arrays.
Can be float or array of length nt.
color_map: Color map for the values stored in the array 'c'.
These are the same as in matplotlib.
time: Float array with the time information of the data.
Has length nt.
Returns
-------
2d Surface object with the mesh plot.
Examples
--------
>>> import numpy as np
>>> import blendaviz as blt
>>> x0 = np.linspace(-3, 3, 20)
>>> y0 = np.linspace(-3, 3, 20)
>>> x, y = np.meshgrid(x0, y0, indexing='ij')
>>> z = np.ones_like(x)*np.linspace(0, 2, 20)
>>> alpha = 0.5
>>> z = (1 - x**2-y**2)*np.exp(-(x**2+y**2)/5)
>>> m = blt.mesh(x, y, z, c='r', alpha=alpha)
>>> m.c = z
>>> m.plot()
>>> m.z = None
>>> m.plot()
"""
import inspect
# Assign parameters to the Mesh objects.
surface_return = Surface()
argument_dict = inspect.getargvalues(inspect.currentframe()).locals
for argument in argument_dict:
setattr(surface_return, argument, argument_dict[argument])
surface_return.plot()
return surface_return
class Surface(GenericPlot):
"""
Surface class including the vertices, surfaces, parameters and plotting function.
"""
def __init__(self):
"""
Fill members with default values.
"""
import bpy
import blendaviz as blt
super().__init__()
# Define the members that can be seen by the user.
self.x = 0
self.y = 0
self.z = None
self.c = None
self.alpha = None
self.vmin = None
self.vmax = None
self.time_index = 0
self.color_map = None
self.mesh_data = None
self.mesh_object = None
self.mesh_material = None
self.mesh_texture = None
self.deletable_object = None
# Define the locally used time-independent data and parameters.
self._x = 0
self._y = 0
self._z = None
self._c = None
self._vmin = None
self._vmax = None
# Set the handler function for frame changes (time).
bpy.app.handlers.frame_change_pre.append(self.time_handler)
# Add the plot to the stack.
blt.plot_stack.append(self)
def plot(self):
"""
Plot the 2d mesh.
"""
import bpy
import numpy as np
from matplotlib import cm
# Check if there is any time array.
if not self.time is None:
if not isinstance(self.time, np.ndarray):
print("Error: time is not a valid array.")
return -1
if self.time.ndim != 1:
print("Error: time array must be 1d.")
return -1
# Determine the time index.
self.time_index = np.argmin(abs(bpy.context.scene.frame_float - self.time))
else:
self.time = np.array([0])
self.time_index = 0
# Check the validity of the input arrays.
if not isinstance(self.x, np.ndarray) or not isinstance(self.y, np.ndarray):
print("Error: x OR y array invalid.")
return -1
if not isinstance(self.z, np.ndarray) and not isinstance(self.c, np.ndarray):
print("Error: either z or c or both must be arrays.")
return -1
if isinstance(self.z, np.ndarray):
if not self.z.shape[:2] == self.x.shape[:2]:
print("Error: z array shape invalid.")
return -1
else:
self.z = np.zeros_like(self.x)
if isinstance(self.c, np.ndarray):
if not self.c.shape[:2] == self.x.shape[:2]:
print("Error: c array shape invalid.")
return -1
if not self.alpha:
self.alpha = 1
if isinstance(self.alpha, np.ndarray):
if self.alpha.shape != (1, ):
if not self.alpha.shape[:2] == self.x.shape[:2]:
print("Error: alpha array shape invalid.")
return -1
else:
self.alpha = np.array([self.alpha])
# Point the local variables to the correct arrays.
if self.x.ndim == 3:
self._x = self.x[:, :, self.time_index]
else:
self._x = self.x
if self.y.ndim == 3:
self._y = self.y[:, :, self.time_index]
else:
self._y = self.y
if not isinstance(self.z, np.ndarray):
self._z = np.zeros_like(self._x)
else:
if self.z.ndim == 3:
self._z = self.z[:, :, self.time_index]
else:
self._z = self.z
if not (self.x.shape == self.y.shape == self.z.shape):
print("Error: x, y, z array shapes invalid.")
return -1
if isinstance(self.vmin, np.ndarray):
self._vmin = self.vmin[self.time_index]
else:
self._vmin = self.vmin
if isinstance(self.vmax, np.ndarray):
self._vmax = self.vmax[self.time_index]
else:
self._vmax = self.vmax
# Set the array to be used for the color map.
if not isinstance(self.c, np.ndarray):
if self.c is None:
self._c = self._z
else:
self._c = self.c
else:
if self.c.ndim == 3:
self._c = self.c[:, :, self.time_index]
else:
self._c = self.c
# Delete existing meshes.
if not self.mesh_object is None:
for obj in bpy.context.view_layer.objects:
obj.select_set(False)
if self.object_reference_valid(self.mesh_object):
self.mesh_object.select_set(state=True)
bpy.data.objects.remove(self.mesh_object, do_unlink=True)
self.mesh_object = None
# Delete existing materials.
if not self.mesh_material is None:
bpy.data.materials.remove(self.mesh_material)
# Create the vertices from the data.
vertices = []
for idx in range(self._x.shape[0]*self._x.shape[1]):
vertices.append((self._x[:, :].flatten()[idx],
self._y[:, :].flatten()[idx],
self._z[:, :].flatten()[idx]))
# Create the faces from the data.
faces = []
count = 0
for idx in range((self._x.shape[0]-1)*(self._x.shape[1])):
if count < self._x.shape[1]-1:
faces.append((idx, idx+1, (idx+self._x.shape[1])+1, (idx+self._x.shape[1])))
count += 1
else:
count = 0
# Create mesh and object.
self.mesh_data = bpy.data.meshes.new("DataMesh")
self.mesh_object = bpy.data.objects.new("ObjMesh", self.mesh_data)
# Create mesh from the given data.
self.mesh_data.from_pydata(vertices, [], faces)
self.mesh_data.update(calc_edges=True)
# Assign a material to the surface.
self.mesh_material = bpy.data.materials.new('MaterialMesh')
self.mesh_data.materials.append(self.mesh_material)
# Create the texture.
if isinstance(self._c, np.ndarray):
mesh_image = bpy.data.images.new('ImageMesh', self._c.shape[0], self._c.shape[1])
pixels = np.array(mesh_image.pixels)
# Determine the minimum and maximum value for the color map.
vmin = self._vmin
vmax = self._vmax
if self._vmin is None:
vmin = np.min(self._c)
if self._vmax is None:
vmax = np.max(self._c)
# Assign the RGBa values to the pixels.
if self.color_map is None:
self.color_map = cm.viridis
pixels[0::4] = self.color_map((self._c.flatten() - vmin)/(vmax - vmin))[:, 0]
pixels[1::4] = self.color_map((self._c.flatten() - vmin)/(vmax - vmin))[:, 1]
pixels[2::4] = self.color_map((self._c.flatten() - vmin)/(vmax - vmin))[:, 2]
pixels[3::4] = self.alpha.flatten()
mesh_image.pixels[:] = np.swapaxes(pixels.reshape([self._x.shape[0],
self._x.shape[1], 4]), 0, 1).flatten()[:]
# Assign the texture to the material.
self.mesh_material.use_nodes = True
self.mesh_texture = self.mesh_material.node_tree.nodes.new('ShaderNodeTexImage')
self.mesh_texture.image = mesh_image
links = self.mesh_material.node_tree.links
links.new(self.mesh_texture.outputs[0],
self.mesh_material.node_tree.nodes.get("Principled BSDF").inputs[0])
# Link the mesh object with the scene.
bpy.context.scene.collection.objects.link(self.mesh_object)
# UV mapping for the new texture.
bpy.context.view_layer.objects.active = self.mesh_object
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.uv.unwrap(method='ANGLE_BASED', margin=0)
bpy.ops.object.mode_set(mode='OBJECT')
# UV mapping of the material on the mesh.
polygon_idx = 0
for polygon in self.mesh_object.data.polygons:
for idx in polygon.loop_indices:
x_idx = polygon_idx // (self._x.shape[1] - 1)
y_idx = polygon_idx % (self._x.shape[1] - 1)
if (idx-4*polygon_idx) == 1 or (idx-4*polygon_idx) == 2:
y_idx += 1
if (idx-4*polygon_idx) == 2 or (idx-4*polygon_idx) == 3:
x_idx += 1
uv_new = np.array([(float(x_idx)+0.5)/self._x.shape[0],
(float(y_idx)+0.5)/self._x.shape[1]])
self.mesh_object.data.uv_layers[0].data[idx].uv[0] = uv_new[0]
self.mesh_object.data.uv_layers[0].data[idx].uv[1] = uv_new[1]
polygon_idx += 1
else:
# Transform color string into rgba.
from blendaviz import colors
self.mesh_material.diffuse_color = colors.string_to_rgba(self._c)
# Link the mesh object with the scene.
bpy.context.scene.collection.objects.link(self.mesh_object)
#bpy.context.scene.collection.objects.link(self.mesh_object)
# Render surface as smooth.
self.mesh_object.select_set(True)
if bpy.ops.object.mode_set.poll():
bpy.ops.object.shade_smooth()
self.mesh_object.select_set(False)
# Make the mesh the deletable object.
self.deletable_object = self.mesh_object
#self.update_globals()
return 0
def time_handler(self, scene, depsgraph):
"""
Function to be called whenever any Blender animation functions are used.
Updates the plot according to the function specified.
"""
if not self.time is None:
self.plot()
else:
pass
def update_globals(self):
"""
Update the extrema and lights.
"""
import blendaviz as blt
if blt.house_keeping.x_min is None:
blt.house_keeping.x_min = self.x.min()
elif self.x.min() < blt.house_keeping.x_min:
blt.house_keeping.x_min = self.x.min()
if blt.house_keeping.x_max is None:
blt.house_keeping.x_max = self.x.max()
elif self.x.max() > blt.house_keeping.x_max:
blt.house_keeping.x_max = self.x.max()
if blt.house_keeping.y_min is None:
blt.house_keeping.y_min = self.y.min()
elif self.y.min() < blt.house_keeping.y_min:
blt.house_keeping.y_min = self.y.min()
if blt.house_keeping.y_max is None:
blt.house_keeping.y_max = self.y.max()
elif self.y.max() > blt.house_keeping.y_max:
blt.house_keeping.y_max = self.y.max()
if not self.z is None:
if blt.house_keeping.z_min is None:
blt.house_keeping.z_min = self.z.min()
elif self.z.min() < blt.house_keeping.z_min:
blt.house_keeping.z_min = self.z.min()
if blt.house_keeping.z_max is None:
blt.house_keeping.z_max = self.z.max()
elif self.z.max() > blt.house_keeping.z_max:
blt.house_keeping.z_max = self.z.max()
else:
if blt.house_keeping.z_min is None:
blt.house_keeping.z_min = 0
elif blt.house_keeping.z_min > 0:
blt.house_keeping.z_min = 0
if blt.house_keeping.z_max is None:
blt.house_keeping.z_max = 0
elif blt.house_keeping.z_max < 0:
blt.house_keeping.z_max = 0
if blt.house_keeping.box is None:
blt.house_keeping.box = blt.bounding_box()
else:
blt.house_keeping.box.get_extrema()
blt.house_keeping.box.plot()
# Add some light.
blt.adjust_lights()