lavavu-osmesa 1.9.9__cp313-cp313-manylinux_2_28_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. lavavu/LavaVuPython.py +561 -0
  2. lavavu/_LavaVuPython.cpython-313-x86_64-linux-gnu.so +0 -0
  3. lavavu/__init__.py +15 -0
  4. lavavu/__main__.py +12 -0
  5. lavavu/amalgamate.py +15 -0
  6. lavavu/aserver.py +359 -0
  7. lavavu/control.py +1731 -0
  8. lavavu/convert.py +888 -0
  9. lavavu/dict.json +2528 -0
  10. lavavu/font.bin +0 -0
  11. lavavu/html/LavaVu-amalgamated.css +282 -0
  12. lavavu/html/OK-min.js +99 -0
  13. lavavu/html/baseviewer.js +307 -0
  14. lavavu/html/control.css +104 -0
  15. lavavu/html/control.js +340 -0
  16. lavavu/html/dat-gui-light-theme.css +68 -0
  17. lavavu/html/dat.gui.min.js +2 -0
  18. lavavu/html/draw.js +2259 -0
  19. lavavu/html/drawbox.js +1039 -0
  20. lavavu/html/emscripten-template.js +184 -0
  21. lavavu/html/emscripten.css +92 -0
  22. lavavu/html/favicon.ico +0 -0
  23. lavavu/html/gl-matrix-min.js +47 -0
  24. lavavu/html/gui.css +25 -0
  25. lavavu/html/menu.js +615 -0
  26. lavavu/html/server.js +226 -0
  27. lavavu/html/stats.min.js +5 -0
  28. lavavu/html/styles.css +58 -0
  29. lavavu/html/webview-template.html +43 -0
  30. lavavu/html/webview.html +43 -0
  31. lavavu/lavavu.py +6200 -0
  32. lavavu/osmesa/LavaVuPython.py +561 -0
  33. lavavu/osmesa/_LavaVuPython.cpython-313-x86_64-linux-gnu.so +0 -0
  34. lavavu/osmesa/__init__.py +0 -0
  35. lavavu/points.py +191 -0
  36. lavavu/server.py +343 -0
  37. lavavu/shaders/default.frag +14 -0
  38. lavavu/shaders/default.vert +17 -0
  39. lavavu/shaders/fontShader.frag +20 -0
  40. lavavu/shaders/fontShader.vert +18 -0
  41. lavavu/shaders/lineShader.frag +39 -0
  42. lavavu/shaders/lineShader.vert +26 -0
  43. lavavu/shaders/pointShader.frag +127 -0
  44. lavavu/shaders/pointShader.vert +53 -0
  45. lavavu/shaders/triShader.frag +153 -0
  46. lavavu/shaders/triShader.vert +49 -0
  47. lavavu/shaders/volumeShader.frag +400 -0
  48. lavavu/shaders/volumeShader.vert +5 -0
  49. lavavu/tracers.py +207 -0
  50. lavavu/vutils.py +211 -0
  51. lavavu_osmesa-1.9.9.dist-info/METADATA +323 -0
  52. lavavu_osmesa-1.9.9.dist-info/RECORD +65 -0
  53. lavavu_osmesa-1.9.9.dist-info/WHEEL +5 -0
  54. lavavu_osmesa-1.9.9.dist-info/entry_points.txt +2 -0
  55. lavavu_osmesa-1.9.9.dist-info/licenses/LICENSE.md +179 -0
  56. lavavu_osmesa-1.9.9.dist-info/top_level.txt +1 -0
  57. lavavu_osmesa.libs/libLLVM-17-51492e70.so +0 -0
  58. lavavu_osmesa.libs/libOSMesa-f6a8f160.so.8.0.0 +0 -0
  59. lavavu_osmesa.libs/libdrm-b0291a67.so.2.4.0 +0 -0
  60. lavavu_osmesa.libs/libffi-3a37023a.so.6.0.2 +0 -0
  61. lavavu_osmesa.libs/libglapi-520b284c.so.0.0.0 +0 -0
  62. lavavu_osmesa.libs/libpcre2-8-516f4c9d.so.0.7.1 +0 -0
  63. lavavu_osmesa.libs/libselinux-d0805dcb.so.1 +0 -0
  64. lavavu_osmesa.libs/libtinfo-3a2cb85b.so.6.1 +0 -0
  65. lavavu_osmesa.libs/libzstd-76b78bac.so.1.4.4 +0 -0
@@ -0,0 +1,400 @@
1
+ /*
2
+ * Copyright (c) 2014, Monash University. All rights reserved.
3
+ * Author: Owen Kaluza - owen.kaluza ( at ) monash.edu
4
+ *
5
+ * Licensed under the GNU Lesser General Public License
6
+ * https://www.gnu.org/licenses/lgpl.html
7
+ * (volume shader from sharevol https://github.com/OKaluza/sharevol)
8
+ */
9
+ //Included dynamically before compile in WebGL mode...
10
+ const int maxSamples = 2048;
11
+ uniform sampler3D uVolume;
12
+ out vec4 outColour;
13
+
14
+ const float depthT = 0.99; //Transmissivity threshold below which depth write applied
15
+
16
+ uniform sampler2D uTransferFunction;
17
+
18
+ uniform vec3 uBBMin;
19
+ uniform vec3 uBBMax;
20
+ uniform vec3 uResolution;
21
+
22
+ uniform bool uEnableColour;
23
+
24
+ uniform float uBrightness;
25
+ uniform float uContrast;
26
+ uniform float uSaturation;
27
+ uniform float uPower;
28
+ uniform float uBloom;
29
+
30
+ uniform mat4 uMVMatrix;
31
+ uniform mat4 uTMVMatrix;
32
+ uniform mat4 uMVPMatrix;
33
+ uniform mat4 uInvMVPMatrix;
34
+ uniform mat4 uNMatrix;
35
+ uniform vec4 uViewport;
36
+ uniform int uSamples;
37
+ uniform float uDensityFactor;
38
+ uniform float uIsoValue;
39
+ uniform vec4 uIsoColour;
40
+ uniform float uIsoSmooth;
41
+ uniform int uIsoWalls;
42
+ uniform int uFilter;
43
+ uniform vec2 uRange;
44
+ uniform vec2 uDenMinMax;
45
+
46
+ uniform float uAmbient;
47
+ uniform float uDiffuse;
48
+ uniform float uSpecular;
49
+ uniform vec3 uLightPos;
50
+ uniform bool uLighting;
51
+
52
+ vec3 bbMin;
53
+ vec3 bbMax;
54
+
55
+ #ifdef ENABLE_TRICUBIC
56
+ float interpolate_tricubic_fast(vec3 coord);
57
+ #endif
58
+
59
+ #define sample(pos) (texture(uVolume, pos).x)
60
+
61
+ float tex3D(vec3 pos)
62
+ {
63
+ float density;
64
+ //TODO: this can't be enabled outside WebGL currently
65
+ #ifdef ENABLE_TRICUBIC
66
+ if (uFilter > 0)
67
+ density = interpolate_tricubic_fast(pos);
68
+ else
69
+ #endif
70
+ density = sample(pos);
71
+
72
+ //Normalise the density over provided range
73
+ //(used for float textures only, all other formats are already [0,1])
74
+ density = (density - uRange.x) / (uRange.y - uRange.x);
75
+ //density = (density - uRange.x) * irange;
76
+ return density;
77
+ }
78
+
79
+ void lighting(in vec3 pos, in vec3 normal, inout vec3 colour)
80
+ {
81
+ vec4 vertPos = uMVMatrix * vec4(pos, 1.0);
82
+ //Light moves with camera at specified offset
83
+ vec3 lightDir = normalize(uLightPos - vertPos.xyz);
84
+ float diffuse = clamp(abs(dot(normal, lightDir)), 0.1, 1.0);
85
+ vec3 lightWeighting = vec3(uAmbient + diffuse * uDiffuse);
86
+ colour *= lightWeighting;
87
+ }
88
+
89
+ vec3 isoNormal(in vec3 pos, in vec3 shift)
90
+ {
91
+ //Detect bounding box hit (walls)
92
+ if (uIsoWalls > 0)
93
+ {
94
+ if (pos.x <= bbMin.x) return vec3(-1.0, 0.0, 0.0);
95
+ if (pos.x >= bbMax.x) return vec3(1.0, 0.0, 0.0);
96
+ if (pos.y <= bbMin.y) return vec3(0.0, -1.0, 0.0);
97
+ if (pos.y >= bbMax.y) return vec3(0.0, 1.0, 0.0);
98
+ if (pos.z <= bbMin.z) return vec3(0.0, 0.0, -1.0);
99
+ if (pos.z >= bbMax.z) return vec3(0.0, 0.0, 1.0);
100
+ }
101
+
102
+ //Calculate normal
103
+ //by central difference gradient
104
+ //(slower, faster way would be to precompute a gradient texture)
105
+ vec3 pos1 = vec3(tex3D(vec3(pos.x+shift.x, pos.y, pos.z)),
106
+ tex3D(vec3(pos.x, pos.y+shift.y, pos.z)),
107
+ tex3D(vec3(pos.x, pos.y, pos.z+shift.z)));
108
+ vec3 pos2 = vec3(tex3D(vec3(pos.x-shift.x, pos.y, pos.z)),
109
+ tex3D(vec3(pos.x, pos.y-shift.y, pos.z)),
110
+ tex3D(vec3(pos.x, pos.y, pos.z-shift.z)));
111
+ return normalize(pos1 - pos2);
112
+ }
113
+
114
+ vec2 rayIntersectBox(vec3 rayDirection, vec3 rayOrigin)
115
+ {
116
+ //Intersect ray with bounding box
117
+ vec3 rayInvDirection = 1.0 / rayDirection;
118
+ vec3 bbMinDiff = (bbMin - rayOrigin) * rayInvDirection;
119
+ vec3 bbMaxDiff = (bbMax - rayOrigin) * rayInvDirection;
120
+ vec3 imax = max(bbMaxDiff, bbMinDiff);
121
+ vec3 imin = min(bbMaxDiff, bbMinDiff);
122
+ float back = min(imax.x, min(imax.y, imax.z));
123
+ float front = max(max(imin.x, 0.0), max(imin.y, imin.z));
124
+ return vec2(back, front);
125
+ }
126
+
127
+ void main()
128
+ {
129
+ if (any(greaterThan(uBBMin, uBBMax)))
130
+ {
131
+ bbMin = vec3(0.0);
132
+ bbMax = vec3(1.0);
133
+ }
134
+ else
135
+ {
136
+ bbMin = clamp(uBBMin, vec3(0.0), vec3(1.0));
137
+ bbMax = clamp(uBBMax, vec3(0.0), vec3(1.0));
138
+ }
139
+
140
+ //Compute eye space coord from window space to get the ray direction
141
+ //ObjectSpace *[MV] = EyeSpace *[P] = Clip /w = Normalised device coords ->VP-> Window
142
+ //Window ->[VP^]-> NDC ->[/w]-> Clip ->[P^]-> EyeSpace ->[MV^]-> ObjectSpace
143
+ vec4 ndcPos;
144
+ ndcPos.xy = ((2.0 * gl_FragCoord.xy) - (2.0 * uViewport.xy)) / (uViewport.zw) - 1.0;
145
+ //ndcPos.z = (2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) /
146
+ // (gl_DepthRange.far - gl_DepthRange.near);
147
+ ndcPos.z = 2.0 * gl_FragCoord.z - 1.0;
148
+ ndcPos.w = 1.0;
149
+ vec4 clipPos = ndcPos / gl_FragCoord.w;
150
+ //vec4 eyeSpacePos = uInvPMatrix * clipPos;
151
+ vec3 rayDirection = normalize((uInvMVPMatrix * clipPos).xyz);
152
+
153
+ //Ray origin from the camera position
154
+ vec4 camPos = -vec4(uMVMatrix[3]); //4th column of modelview
155
+ vec3 rayOrigin = (uTMVMatrix * camPos).xyz;
156
+
157
+ //Calc step
158
+ float stepSize = 1.732 / float(uSamples); //diagonal of [0,1] normalised coord cube = sqrt(3)
159
+
160
+ //Intersect ray with bounding box
161
+ vec2 intersection = rayIntersectBox(rayDirection, rayOrigin);
162
+ //Subtract small increment to avoid errors on front boundary
163
+ intersection.y -= 0.000001;
164
+ //Discard points outside the box (no intersection)
165
+ if (intersection.x <= intersection.y) discard;
166
+
167
+ vec3 rayStart = rayOrigin + rayDirection * intersection.y;
168
+ vec3 rayStop = rayOrigin + rayDirection * intersection.x;
169
+
170
+ vec3 step = normalize(rayStop-rayStart) * stepSize;
171
+ vec3 pos = rayStart;
172
+
173
+ float T = 1.0;
174
+ vec3 colour = vec3(0.0);
175
+ bool inside = false;
176
+ vec3 shift = uIsoSmooth / uResolution;
177
+ //Number of samples to take along this ray before we pass out back of volume...
178
+ float travel = distance(rayStop, rayStart) / stepSize;
179
+ int samples = int(ceil(travel));
180
+ float irange = uRange.y - uRange.x;
181
+ if (irange <= 0.0) irange = 1.0;
182
+ irange = 1.0 / irange;
183
+
184
+ //Map colour over valid density range only
185
+ float dRange = uDenMinMax[1] - uDenMinMax[0];
186
+
187
+ //Raymarch, front to back
188
+ vec3 depthHit = rayStart;
189
+ for (int i=0; i < maxSamples; ++i)
190
+ {
191
+ //Render samples until we pass out back of cube or fully opaque
192
+ if (i == samples || T < 0.01) break;
193
+ {
194
+ //Get density
195
+ float density = tex3D(pos);
196
+
197
+ //Set the depth point to where transmissivity drops below threshold
198
+ if (T > depthT)
199
+ depthHit = pos;
200
+
201
+ #define ISOSURFACE
202
+ #ifdef ISOSURFACE
203
+ //Passed through isosurface?
204
+ if (uIsoColour.a > 0.0 && ((!inside && density >= uIsoValue) || (inside && density < uIsoValue)))
205
+ {
206
+ inside = !inside;
207
+ //Find closer to exact position by iteration
208
+ //http://sizecoding.blogspot.com.au/2008/08/isosurfaces-in-glsl.html
209
+ float exact;
210
+ float a = intersection.y + (float(i)*stepSize);
211
+ float b = a - stepSize;
212
+ for (int j = 0; j < 5; j++)
213
+ {
214
+ exact = (b + a) * 0.5;
215
+ pos = rayDirection * exact + rayOrigin;
216
+ density = tex3D(pos);
217
+ if (density - uIsoValue < 0.0)
218
+ b = exact;
219
+ else
220
+ a = exact;
221
+ }
222
+
223
+ //Skip edges unless flagged to draw
224
+ if (uIsoWalls > 0 || all(greaterThanEqual(pos, bbMin)) && all(lessThanEqual(pos, bbMax)))
225
+ {
226
+ vec4 value = vec4(uIsoColour.rgb, 1.0);
227
+ vec3 light = vec3(1.0, 1.0, 1.0);
228
+ if (uLighting)
229
+ {
230
+ vec3 normal = normalize((uNMatrix * vec4(isoNormal(pos, shift), 1.0)).xyz);
231
+ light = value.rgb;
232
+ lighting(pos, normal, light);
233
+ }
234
+
235
+ //Front-to-back blend equation
236
+ colour += T * uIsoColour.a * light;
237
+ //Render normals
238
+ //colour += T * abs(isoNormal(pos, shift, density));
239
+ T *= (1.0 - uIsoColour.a);
240
+ }
241
+ }
242
+ #endif
243
+
244
+ if (uDensityFactor > 0.0)
245
+ {
246
+ density = clamp(density, 0.0, 1.0);
247
+ if (density < uDenMinMax[0] || density > uDenMinMax[1])
248
+ {
249
+ //Skip to next sample...
250
+ pos += step;
251
+ continue;
252
+ }
253
+
254
+ //Scale to density range - fits colourmap to only the displayed data range
255
+ density = density / dRange;
256
+
257
+ density = pow(density, uPower); //Apply power
258
+
259
+ vec4 value;
260
+ if (uEnableColour)
261
+ {
262
+ value = texture(uTransferFunction, vec2(density, 0.5));
263
+ //Premultiply alpha
264
+ value.rgb *= value.a;
265
+ //Apply bloom power, makes the blending more additive
266
+ value.a = pow(value.a, 1.0 + 3.0*uBloom);
267
+ }
268
+ else
269
+ value = vec4(density);
270
+
271
+ value *= uDensityFactor * stepSize;
272
+
273
+ //Blending is front to back
274
+ //Color
275
+ colour += T * value.rgb;
276
+ //Alpha
277
+ T *= 1.0 - value.a;
278
+ }
279
+ }
280
+
281
+ //Next sample...
282
+ pos += step;
283
+ }
284
+
285
+ //Apply brightness, saturation & contrast
286
+ colour += uBrightness;
287
+ const vec3 LumCoeff = vec3(0.2125, 0.7154, 0.0721);
288
+ vec3 AvgLumin = vec3(0.5, 0.5, 0.5);
289
+ vec3 intensity = vec3(dot(colour, LumCoeff));
290
+ colour = mix(intensity, colour, uSaturation);
291
+ colour = mix(AvgLumin, colour, uContrast);
292
+
293
+ //TODO: alpha threshold uniform?
294
+ //if (T > depthT) discard;
295
+ outColour = vec4(colour, 1.0 - T);
296
+
297
+ #ifndef NO_DEPTH_WRITE
298
+ // Write the depth (!Not supported in WebGL without extension)
299
+ float depth = 1.0; //Default to far limit
300
+ if (T < depthT)
301
+ {
302
+ //ObjectSpace *[MV] = EyeSpace *[P] = Clip /w = Normalised device coords ->VP-> Window
303
+ vec4 clip_space_pos = vec4(depthHit, 1.0);
304
+ clip_space_pos = uMVPMatrix * clip_space_pos;
305
+ //Get in normalised device coords [-1,1]
306
+ float ndc_depth = clip_space_pos.z / clip_space_pos.w;
307
+ //Convert to depth range, default [0,1] but may have been modified
308
+ if (ndc_depth >= -1.0 && ndc_depth <= 1.0)
309
+ depth = 0.5 * ndc_depth + 0.5;
310
+ else
311
+ depth = 0.0;
312
+
313
+ //depth = 0.5 * (((gl_DepthRange.far - gl_DepthRange.near) * ndc_depth) +
314
+ // gl_DepthRange.near + gl_DepthRange.far);
315
+ }
316
+
317
+ gl_FragDepth = depth;
318
+ #endif
319
+ }
320
+
321
+ #ifdef ENABLE_TRICUBIC
322
+ float interpolate_tricubic_fast(vec3 coord)
323
+ {
324
+ /* License applicable to this function:
325
+ Copyright (c) 2008-2013, Danny Ruijters. All rights reserved.
326
+
327
+ Redistribution and use in source and binary forms, with or without
328
+ modification, are permitted provided that the following conditions are met:
329
+ * Redistributions of source code must retain the above copyright
330
+ notice, this list of conditions and the following disclaimer.
331
+ * Redistributions in binary form must reproduce the above copyright
332
+ notice, this list of conditions and the following disclaimer in the
333
+ documentation and/or other materials provided with the distribution.
334
+ * Neither the name of the copyright holders nor the names of its
335
+ contributors may be used to endorse or promote products derived from
336
+ this software without specific prior written permission.
337
+
338
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
339
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
340
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
341
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
342
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
343
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
344
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
345
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
346
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
347
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
348
+ POSSIBILITY OF SUCH DAMAGE.
349
+
350
+ The views and conclusions contained in the software and documentation are
351
+ those of the authors and should not be interpreted as representing official
352
+ policies, either expressed or implied.
353
+
354
+ When using this code in a scientific project, please cite one or all of the
355
+ following papers:
356
+ * Daniel Ruijters and Philippe Thevenaz,
357
+ GPU Prefilter for Accurate Cubic B-Spline Interpolation,
358
+ The Computer Journal, vol. 55, no. 1, pp. 15-20, January 2012.
359
+ * Daniel Ruijters, Bart M. ter Haar Romeny, and Paul Suetens,
360
+ Efficient GPU-Based Texture Interpolation using Uniform B-Splines,
361
+ Journal of Graphics Tools, vol. 13, no. 4, pp. 61-69, 2008.
362
+ */
363
+ // shift the coordinate from [0,1] to [-0.5, nrOfVoxels-0.5]
364
+ vec3 nrOfVoxels = uResolution;
365
+ vec3 coord_grid = coord * nrOfVoxels - 0.5;
366
+ vec3 index = floor(coord_grid);
367
+ vec3 fraction = coord_grid - index;
368
+ vec3 one_frac = 1.0 - fraction;
369
+
370
+ vec3 w0 = 1.0/6.0 * one_frac*one_frac*one_frac;
371
+ vec3 w1 = 2.0/3.0 - 0.5 * fraction*fraction*(2.0-fraction);
372
+ vec3 w2 = 2.0/3.0 - 0.5 * one_frac*one_frac*(2.0-one_frac);
373
+ vec3 w3 = 1.0/6.0 * fraction*fraction*fraction;
374
+
375
+ vec3 g0 = w0 + w1;
376
+ vec3 g1 = w2 + w3;
377
+ vec3 mult = 1.0 / nrOfVoxels;
378
+ vec3 h0 = mult * ((w1 / g0) - 0.5 + index); //h0 = w1/g0 - 1, move from [-0.5, nrOfVoxels-0.5] to [0,1]
379
+ vec3 h1 = mult * ((w3 / g1) + 1.5 + index); //h1 = w3/g1 + 1, move from [-0.5, nrOfVoxels-0.5] to [0,1]
380
+
381
+ // fetch the eight linear interpolations
382
+ // weighting and fetching is interleaved for performance and stability reasons
383
+ float tex000 = sample(h0);
384
+ float tex100 = sample(vec3(h1.x, h0.y, h0.z));
385
+ tex000 = mix(tex100, tex000, g0.x); //weigh along the x-direction
386
+ float tex010 = sample(vec3(h0.x, h1.y, h0.z));
387
+ float tex110 = sample(vec3(h1.x, h1.y, h0.z));
388
+ tex010 = mix(tex110, tex010, g0.x); //weigh along the x-direction
389
+ tex000 = mix(tex010, tex000, g0.y); //weigh along the y-direction
390
+ float tex001 = sample(vec3(h0.x, h0.y, h1.z));
391
+ float tex101 = sample(vec3(h1.x, h0.y, h1.z));
392
+ tex001 = mix(tex101, tex001, g0.x); //weigh along the x-direction
393
+ float tex011 = sample(vec3(h0.x, h1.y, h1.z));
394
+ float tex111 = sample(h1);
395
+ tex011 = mix(tex111, tex011, g0.x); //weigh along the x-direction
396
+ tex001 = mix(tex011, tex001, g0.y); //weigh along the y-direction
397
+
398
+ return mix(tex001, tex000, g0.z); //weigh along the z-direction
399
+ }
400
+ #endif
@@ -0,0 +1,5 @@
1
+ in vec4 aVertexPosition;
2
+ void main(void)
3
+ {
4
+ gl_Position = aVertexPosition;
5
+ }
lavavu/tracers.py ADDED
@@ -0,0 +1,207 @@
1
+ """
2
+ Tracer particles in a vector field
3
+
4
+ - Requires scipy.interpolate
5
+ """
6
+ import numpy
7
+ import os
8
+ import sys
9
+ import random
10
+ from scipy.interpolate import RegularGridInterpolator
11
+
12
+ def random_particles(count, lowerbound=[0,0,0], upperbound=[1,1,1], dims=3):
13
+ """
14
+ Return an array of *count* 3d vertices of random particle positions
15
+ Minimum and maximum values defined by lowerbound and upperbound
16
+ """
17
+ p = [None] * dims
18
+ for c in range(dims):
19
+ if lowerbound[c] == upperbound[c]:
20
+ p[c] = numpy.zeros(shape=(count)) + lowerbound[c]
21
+ else:
22
+ p[c] = numpy.random.uniform(low=lowerbound[c], high=upperbound[c], size=count)
23
+
24
+ return numpy.stack(p).T
25
+
26
+ class Tracers():
27
+ def __init__(self, grid, count=1000, lowerbound=None, upperbound=None, limit=None, age=4, respawn_chance=0.2, speed_multiply=1.0, height=0.0, label='', viewer=None):
28
+ """
29
+ Seed random particles into a vector field and trace their positions
30
+
31
+ Parameters
32
+ ----------
33
+ grid : list of coord arrays for each dimension as expected by RegularGridInterpolator,
34
+ or a numpy array of 2d or 3d vertices, which will be converted before being sent to the interpolator
35
+ Object returned from first call, pass None on first pass
36
+ count : int
37
+ Number of particles to seed and track
38
+ lowerbound : optional minimum vertex point defining particle bounding box,
39
+ if not provided will be taken from grid lower corner
40
+ upperbound : optional maximum vertex point defining particle bounding box,
41
+ if not provided will be taken from grid upper corner
42
+ limit : float
43
+ Distance limit over which tracers are not connected,
44
+ For example if using a periodic boundary, setting limit to
45
+ half the bounding box size will prevent tracer lines being
46
+ connected when passing through the boundary
47
+ age : int
48
+ Minimum particle age in steps after which particle can be deleted and respawned, defaults to 4
49
+ respawn : float
50
+ Probability of respawning, after age reached, default 0.2 ==> 1 in 5 chance of deletion
51
+ speed_multiply : float
52
+ Speed multiplier, scaling factor for the velocity taken from the vector values
53
+ height : float
54
+ A fixed height value, all positions will be given this height as their Z component
55
+ label : str
56
+ Name label prefix for the visualisation objects when plotting
57
+ viewer : lavavu.Viewer
58
+ Viewer object for plotting functions
59
+ """
60
+ if len(grid) == 2:
61
+ self.gridx = grid[0]
62
+ self.gridy = grid[1]
63
+ self.gridz = numpy.array((height, height))
64
+ self.dims = 2
65
+ elif len(grid) == 3:
66
+ self.gridx = grid[0]
67
+ self.gridy = grid[1]
68
+ self.gridz = grid[2]
69
+ self.dims = 3
70
+ elif isinstance(grid, numpy.ndarray) and grid.shape[1] == 3:
71
+ self.gridx = grid[::,0]
72
+ self.gridy = grid[::,1]
73
+ self.gridz = grid[::,2]
74
+ self.dims = 3
75
+ elif isinstance(grid, numpy.ndarray) and grid.shape[1] == 2:
76
+ self.gridx = grid[::,0]
77
+ self.gridy = grid[::,1]
78
+ self.gridz = numpy.array((height, height))
79
+ self.dims = 2
80
+ else:
81
+ raise(ValueError('Grid needs to be array of 2d/3d vertices, or arrays of vertex coords (x, y, [z])'))
82
+
83
+ self.count = count
84
+ if lowerbound is None:
85
+ lowerbound = (self.gridx[0], self.gridy[0], self.gridz[0])
86
+ if upperbound is None:
87
+ upperbound = (self.gridx[-1], self.gridy[-1], self.gridz[-1])
88
+ self.positions = random_particles(self.count, lowerbound, upperbound, self.dims)
89
+ self.old_pos = numpy.zeros_like(self.positions)
90
+ self.lowerbound = lowerbound
91
+ self.upperbound = upperbound
92
+ self.velocities = None
93
+ self.steps = [0]*count
94
+ self.speed = numpy.zeros(shape=(count))
95
+ self.ages = numpy.zeros(shape=(count))
96
+ self.interp = None
97
+ if limit is None:
98
+ limit = 0.1 * (abs(self.gridx[-1] - self.gridx[0]) + abs(self.gridy[-1] - self.gridy[0]))
99
+ self.limit = limit
100
+ self.age = age
101
+ self.respawn_chance = respawn_chance
102
+ self.speed_multiply = speed_multiply
103
+ self.height = height
104
+
105
+ self.label = label
106
+ self.lv = viewer
107
+ self.points = None
108
+ self.arrows = None
109
+ self.tracers = None
110
+
111
+
112
+ def respawn(self, r):
113
+ #Dead or out of bounds particle, start at new position
114
+ #Loop until new position further from current position than limit
115
+ old_pos = self.positions[r]
116
+ pos = numpy.array([0.] * self.dims)
117
+ for i in range(10):
118
+ pos = random_particles(1, self.lowerbound, self.upperbound, self.dims)
119
+ dist = numpy.linalg.norm(old_pos - pos)
120
+ if dist > self.limit*1.01:
121
+ break
122
+
123
+ self.ages[r] = 0
124
+ self.positions[r] = pos
125
+
126
+ def update(self, vectors=None):
127
+ #Interpolate velocity at all positions,
128
+ #If vectors not passed, will use previous values
129
+ if vectors is not None:
130
+ if self.dims == 2:
131
+ self.interp = RegularGridInterpolator((self.gridx, self.gridy), vectors, bounds_error=False, fill_value=0.0)
132
+ else:
133
+ self.interp = RegularGridInterpolator((self.gridx, self.gridy, self.gridz), vectors, bounds_error=False, fill_value=0.0)
134
+
135
+ if self.interp is None:
136
+ raise(ValueError("No velocity grid, must pass vectors for first call of update()"))
137
+
138
+ self.velocities = self.interp(self.positions)
139
+ self.old_pos = numpy.copy(self.positions)
140
+
141
+ for r in range(len(self.velocities)):
142
+ #Lookup velocity at this index, multiply by position to get delta and add
143
+ self.speed[r] = numpy.linalg.norm(self.velocities[r])
144
+ if numpy.isnan(self.speed[r]): self.speed[r] = 0.0
145
+ if self.speed[r] == 0.0: #numpy.any(numpy.isinf(self.old_pos[r])) or numpy.any(numpy.isinf(self.positions[r])):
146
+ self.respawn(r)
147
+ else:
148
+ self.positions[r] = self.positions[r] + self.speed_multiply * self.velocities[r]
149
+ self.ages[r] += 1
150
+
151
+ #Bounds checks
152
+ #Chance of killing particle when over age, default 1 in 5 (0.2)
153
+ if (any(self.positions[r] < self.lowerbound[0:self.dims]) or any(self.positions[r] > self.upperbound[0:self.dims])
154
+ or (self.ages[r] > self.age and numpy.random.uniform() <= self.respawn_chance)):
155
+ #if r < 20: print("Kill", r, self.speed[r], numpy.isnan(self.speed[r])) # [0] == numpy.nan)
156
+ #self.positions[r] = numpy.array([numpy.inf] * self.dims)
157
+ #self.positions[r] = numpy.array([numpy.nan] * self.dims)
158
+ self.respawn(r)
159
+ self.velocities[r] = numpy.array([0.0] * self.dims)
160
+ self.speed[r] = 0.0
161
+
162
+ if self.lv:
163
+ positions = self.get_positions()
164
+ if positions.shape[1] == 2 and self.height != 0:
165
+ #Convert to 3d and set z coord to height
166
+ shape = list(positions.shape)
167
+ shape[-1] = 3
168
+ positions = numpy.zeros(shape)
169
+ positions[::,0:2] = self.positions
170
+ positions[::,2] = numpy.array([self.height] * shape[0])
171
+ if self.points:
172
+ self.points.vertices(positions)
173
+ if len(self.points["colourmap"]):
174
+ self.points.values(self.speed)
175
+ if self.arrows:
176
+ self.arrows.vectors(self.velocities)
177
+ self.arrows.vertices(positions)
178
+ if len(self.arrows["colourmap"]):
179
+ self.arrows.values(self.speed)
180
+
181
+ if self.tracers:
182
+ self.tracers.vertices(positions)
183
+ if len(self.tracers["colourmap"]):
184
+ self.tracers.values(self.speed)
185
+
186
+ def get_positions(self):
187
+ """
188
+ This funcion can be overridden if positions need to be transformed
189
+ in any way before plotting, eg: plotting on spherical earth model
190
+ """
191
+ return self.positions
192
+
193
+ def prefix(self):
194
+ return self.label + '_' if len(self.label) else ''
195
+
196
+ def plot_points(self, **kwargs):
197
+ if self.lv is not None and self.points is None:
198
+ self.points = self.lv.points(self.prefix() + 'tracer_points', **kwargs)
199
+
200
+ def plot_arrows(self, **kwargs):
201
+ if self.lv is not None and self.arrows is None:
202
+ self.arrows = self.lv.vectors(self.prefix() + 'tracer_arrows', **kwargs)
203
+
204
+ def plot_tracers(self, **kwargs):
205
+ if self.lv is not None and self.tracers is None:
206
+ self.tracers = self.lv.tracers(self.prefix() + 'tracers', dims=self.count, limit=self.limit, **kwargs)
207
+