-
Notifications
You must be signed in to change notification settings - Fork 258
/
utils.py
2938 lines (2500 loc) · 92 KB
/
utils.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import time
import numpy as np
from vtkmodules.util.numpy_support import numpy_to_vtk, vtk_to_numpy
from vtkmodules.util.numpy_support import numpy_to_vtkIdTypeArray
import vedo.vtkclasses as vtki
import vedo
__docformat__ = "google"
__doc__ = "Utilities submodule."
__all__ = [
"OperationNode",
"ProgressBar",
"progressbar",
"Minimizer",
"geometry",
"is_sequence",
"lin_interpolate",
"vector",
"mag",
"mag2",
"versor",
"precision",
"round_to_digit",
"point_in_triangle",
"point_line_distance",
"closest",
"grep",
"make_bands",
"pack_spheres",
"humansort",
"print_histogram",
"print_inheritance_tree",
"camera_from_quaternion",
"camera_from_neuroglancer",
"camera_from_dict",
"camera_to_dict",
"oriented_camera",
"vedo2trimesh",
"trimesh2vedo",
"vedo2meshlab",
"meshlab2vedo",
"vedo2open3d",
"open3d2vedo",
"vtk2numpy",
"numpy2vtk",
"get_uv",
"andrews_curves",
]
###########################################################################
array_types = {}
array_types[vtki.VTK_UNSIGNED_CHAR] = ("UNSIGNED_CHAR", "np.uint8")
array_types[vtki.VTK_UNSIGNED_SHORT]= ("UNSIGNED_SHORT", "np.uint16")
array_types[vtki.VTK_UNSIGNED_INT] = ("UNSIGNED_INT", "np.uint32")
array_types[vtki.VTK_UNSIGNED_LONG_LONG] = ("UNSIGNED_LONG_LONG", "np.uint64")
array_types[vtki.VTK_CHAR] = ("CHAR", "np.int8")
array_types[vtki.VTK_SHORT] = ("SHORT", "np.int16")
array_types[vtki.VTK_INT] = ("INT", "np.int32")
array_types[vtki.VTK_LONG] = ("LONG", "") # ??
array_types[vtki.VTK_LONG_LONG] = ("LONG_LONG", "np.int64")
array_types[vtki.VTK_FLOAT] = ("FLOAT", "np.float32")
array_types[vtki.VTK_DOUBLE] = ("DOUBLE", "np.float64")
array_types[vtki.VTK_SIGNED_CHAR] = ("SIGNED_CHAR", "np.int8")
array_types[vtki.VTK_ID_TYPE] = ("ID", "np.int64")
###########################################################################
class OperationNode:
"""
Keep track of the operations which led to a final state.
"""
# https://www.graphviz.org/doc/info/shapes.html#html
# Mesh #e9c46a
# Follower #d9ed92
# Volume, UnstructuredGrid #4cc9f0
# TetMesh #9e2a2b
# File #8a817c
# Image #f28482
# Assembly #f08080
def __init__(
self, operation, parents=(), comment="", shape="none", c="#e9c46a", style="filled"
):
"""
Keep track of the operations which led to a final object.
This allows to show the `pipeline` tree for any `vedo` object with e.g.:
```python
from vedo import *
sp = Sphere()
sp.clean().subdivide()
sp.pipeline.show()
```
Arguments:
operation : (str, class)
descriptor label, if a class is passed then grab its name
parents : (list)
list of the parent classes the object comes from
comment : (str)
a second-line text description
shape : (str)
shape of the frame, check out [this link.](https://graphviz.org/doc/info/shapes.html)
c : (hex)
hex color
style : (str)
comma-separated list of styles
Example:
```python
from vedo.utils import OperationNode
op_node1 = OperationNode("Operation1", c="lightblue")
op_node2 = OperationNode("Operation2")
op_node3 = OperationNode("Operation3", shape='diamond')
op_node4 = OperationNode("Operation4")
op_node5 = OperationNode("Operation5")
op_node6 = OperationNode("Result", c="lightgreen")
op_node3.add_parent(op_node1)
op_node4.add_parent(op_node1)
op_node3.add_parent(op_node2)
op_node5.add_parent(op_node2)
op_node6.add_parent(op_node3)
op_node6.add_parent(op_node5)
op_node6.add_parent(op_node1)
op_node6.show(orientation="TB")
```
![](https://vedo.embl.es/images/feats/operation_node.png)
"""
if not vedo.settings.enable_pipeline:
return
if isinstance(operation, str):
self.operation = operation
else:
self.operation = operation.__class__.__name__
self.operation_plain = str(self.operation)
pp = [] # filter out invalid stuff
for p in parents:
if hasattr(p, "pipeline"):
pp.append(p.pipeline)
self.parents = pp
if comment:
self.operation = f"<{self.operation}<BR/><SUB><I>{comment}</I></SUB>>"
self.dot = None
self.time = time.time()
self.shape = shape
self.style = style
self.color = c
self.counts = 0
def add_parent(self, parent):
self.parents.append(parent)
def _build_tree(self, dot):
dot.node(
str(id(self)),
label=self.operation,
shape=self.shape,
color=self.color,
style=self.style,
)
for parent in self.parents:
if parent:
t = f"{self.time - parent.time: .1f}s"
dot.edge(str(id(parent)), str(id(self)), label=t)
parent._build_tree(dot)
def __repr__(self):
try:
from treelib import Tree
except ImportError:
vedo.logger.error(
"To use this functionality please install treelib:"
"\n pip install treelib"
)
return ""
def _build_tree(parent):
for par in parent.parents:
if par:
op = par.operation_plain
tree.create_node(
op, op + str(par.time), parent=parent.operation_plain + str(parent.time)
)
_build_tree(par)
try:
tree = Tree()
tree.create_node(self.operation_plain, self.operation_plain + str(self.time))
_build_tree(self)
out = tree.show(stdout=False)
except:
out = f"Sorry treelib failed to build the tree for '{self.operation_plain}()'."
return out
def print(self):
"""Print the tree of operations."""
print(self.__str__())
def show(self, orientation="LR", popup=True):
"""Show the graphviz output for the pipeline of this object"""
if not vedo.settings.enable_pipeline:
return
try:
from graphviz import Digraph
except ImportError:
vedo.logger.error("please install graphviz with command\n pip install graphviz")
return
# visualize the entire tree
dot = Digraph(
node_attr={"fontcolor": "#201010", "fontname": "Helvetica", "fontsize": "12"},
edge_attr={"fontname": "Helvetica", "fontsize": "6", "arrowsize": "0.4"},
)
dot.attr(rankdir=orientation)
self.counts = 0
self._build_tree(dot)
self.dot = dot
home_dir = os.path.expanduser("~")
gpath = os.path.join(
home_dir, vedo.settings.cache_directory, "vedo", "pipeline_graphviz")
dot.render(gpath, view=popup)
###########################################################################
class ProgressBar:
"""
Class to print a progress bar.
"""
def __init__(
self,
start,
stop,
step=1,
c=None,
bold=True,
italic=False,
title="",
eta=True,
delay=-1,
width=25,
char="\U00002501",
char_back="\U00002500",
):
"""
Class to print a progress bar with optional text message.
Check out also function `progressbar()`.
Arguments:
start : (int)
starting value
stop : (int)
stopping value
step : (int)
step value
c : (str)
color in hex format
title : (str)
title text
eta : (bool)
estimate time of arrival
delay : (float)
minimum time before printing anything,
if negative use the default value
as set in `vedo.settings.progressbar_delay`
width : (int)
width of the progress bar
char : (str)
character to use for the progress bar
char_back : (str)
character to use for the background of the progress bar
Example:
```python
import time
from vedo import ProgressBar
pb = ProgressBar(0,40, c='r')
for i in pb.range():
time.sleep(0.1)
pb.print()
```
![](https://user-images.githubusercontent.com/32848391/51858823-ed1f4880-2335-11e9-8788-2d102ace2578.png)
"""
self.char = char
self.char_back = char_back
self.title = title + " "
if title:
self.title = " " + self.title
if delay < 0:
delay = vedo.settings.progressbar_delay
self.start = start
self.stop = stop
self.step = step
self.color = c
self.bold = bold
self.italic = italic
self.width = width
self.pbar = ""
self.percent = 0.0
self.percent_int = 0
self.eta = eta
self.delay = delay
self.t0 = time.time()
self._remaining = 1e10
self._update(0)
self._counts = 0
self._oldbar = ""
self._lentxt = 0
self._range = np.arange(start, stop, step)
def print(self, txt="", c=None):
"""Print the progress bar with an optional message."""
if not c:
c = self.color
self._update(self._counts + self.step)
if self.delay:
if time.time() - self.t0 < self.delay:
return
if self.pbar != self._oldbar:
self._oldbar = self.pbar
if self.eta and self._counts > 1:
tdenom = time.time() - self.t0
if tdenom:
vel = self._counts / tdenom
self._remaining = (self.stop - self._counts) / vel
else:
vel = 1
self._remaining = 0.0
if self._remaining > 60:
mins = int(self._remaining / 60)
secs = self._remaining - 60 * mins
mins = f"{mins}m"
secs = f"{int(secs + 0.5)}s "
else:
mins = ""
secs = f"{int(self._remaining + 0.5)}s "
vel = round(vel, 1)
eta = f"eta: {mins}{secs}({vel} it/s) "
if self._remaining < 0.5:
dt = time.time() - self.t0
if dt > 60:
mins = int(dt / 60)
secs = dt - 60 * mins
mins = f"{mins}m"
secs = f"{int(secs + 0.5)}s "
else:
mins = ""
secs = f"{int(dt + 0.5)}s "
eta = f"elapsed: {mins}{secs}({vel} it/s) "
txt = ""
else:
eta = ""
eraser = " " * self._lentxt + "\b" * self._lentxt
s = f"{self.pbar} {eraser}{eta}{txt}\r"
vedo.printc(s, c=c, bold=self.bold, italic=self.italic, end="")
if self.percent > 99.999:
print("")
self._lentxt = len(txt)
def range(self):
"""Return the range iterator."""
return self._range
def _update(self, counts):
if counts < self.start:
counts = self.start
elif counts > self.stop:
counts = self.stop
self._counts = counts
self.percent = (self._counts - self.start) * 100.0
delta = self.stop - self.start
if delta:
self.percent /= delta
else:
self.percent = 0.0
self.percent_int = int(round(self.percent))
af = self.width - 2
nh = int(round(self.percent_int / 100 * af))
pbar_background = "\x1b[2m" + self.char_back * (af - nh)
self.pbar = f"{self.title}{self.char * (nh-1)}{pbar_background}"
if self.percent < 100.0:
ps = f" {self.percent_int}%"
else:
ps = ""
self.pbar += ps
#####################################
def progressbar(
iterable,
c=None, bold=True, italic=False, title="",
eta=True, width=25, delay=-1,
):
"""
Function to print a progress bar with optional text message.
Use delay to set a minimum time before printing anything.
If delay is negative, then use the default value
as set in `vedo.settings.progressbar_delay`.
Arguments:
start : (int)
starting value
stop : (int)
stopping value
step : (int)
step value
c : (str)
color in hex format
title : (str)
title text
eta : (bool)
estimate time of arrival
delay : (float)
minimum time before printing anything,
if negative use the default value
set in `vedo.settings.progressbar_delay`
width : (int)
width of the progress bar
char : (str)
character to use for the progress bar
char_back : (str)
character to use for the background of the progress bar
Example:
```python
import time
for i in progressbar(range(100), c='r'):
time.sleep(0.1)
```
![](https://user-images.githubusercontent.com/32848391/51858823-ed1f4880-2335-11e9-8788-2d102ace2578.png)
"""
try:
if is_number(iterable):
total = int(iterable)
iterable = range(total)
else:
total = len(iterable)
except TypeError:
iterable = list(iterable)
total = len(iterable)
pb = ProgressBar(
0, total, c=c, bold=bold, italic=italic, title=title,
eta=eta, delay=delay, width=width,
)
for item in iterable:
pb.print()
yield item
###########################################################
class Minimizer:
"""
A function minimizer that uses the Nelder-Mead method.
The algorithm constructs an n-dimensional simplex in parameter
space (i.e. a tetrahedron if the number or parameters is 3)
and moves the vertices around parameter space until
a local minimum is found. The amoeba method is robust,
reasonably efficient, but is not guaranteed to find
the global minimum if several local minima exist.
Arguments:
function : (callable)
the function to minimize
max_iterations : (int)
the maximum number of iterations
contraction_ratio : (float)
The contraction ratio.
The default value of 0.5 gives fast convergence,
but larger values such as 0.6 or 0.7 provide greater stability.
expansion_ratio : (float)
The expansion ratio.
The default value is 2.0, which provides rapid expansion.
Values between 1.1 and 2.0 are valid.
tol : (float)
the tolerance for convergence
Example:
- [nelder-mead.py](https://github.com/marcomusy/vedo/blob/master/examples/others/nelder-mead.py)
"""
def __init__(
self,
function=None,
max_iterations=10000,
contraction_ratio=0.5,
expansion_ratio=2.0,
tol=1e-5,
):
self.function = function
self.tolerance = tol
self.contraction_ratio = contraction_ratio
self.expansion_ratio = expansion_ratio
self.max_iterations = max_iterations
self.minimizer = vtki.new("AmoebaMinimizer")
self.minimizer.SetFunction(self._vtkfunc)
self.results = {}
self.parameters_path = []
self.function_path = []
def _vtkfunc(self):
n = self.minimizer.GetNumberOfParameters()
ain = [self.minimizer.GetParameterValue(i) for i in range(n)]
r = self.function(ain)
self.minimizer.SetFunctionValue(r)
self.parameters_path.append(ain)
self.function_path.append(r)
return r
def eval(self, parameters=()):
"""
Evaluate the function at the current or given parameters.
"""
if len(parameters) == 0:
return self.minimizer.EvaluateFunction()
self.set_parameters(parameters)
return self.function(parameters)
def set_parameter(self, name, value, scale=1.0):
"""
Set the parameter value.
The initial amount by which the parameter
will be modified during the search for the minimum.
"""
self.minimizer.SetParameterValue(name, value)
self.minimizer.SetParameterScale(name, scale)
def set_parameters(self, parameters):
"""
Set the parameters names and values from a dictionary.
"""
for name, value in parameters.items():
if len(value) == 2:
self.set_parameter(name, value[0], value[1])
else:
self.set_parameter(name, value)
def minimize(self):
"""
Minimize the input function.
Returns:
dict :
the minimization results
init_parameters : (dict)
the initial parameters
parameters : (dict)
the final parameters
min_value : (float)
the minimum value
iterations : (int)
the number of iterations
max_iterations : (int)
the maximum number of iterations
tolerance : (float)
the tolerance for convergence
convergence_flag : (int)
zero if the tolerance stopping
criterion has been met.
parameters_path : (np.array)
the path of the minimization
algorithm in parameter space
function_path : (np.array)
the path of the minimization
algorithm in function space
hessian : (np.array)
the Hessian matrix of the
function at the minimum
parameter_errors : (np.array)
the errors on the parameters
"""
n = self.minimizer.GetNumberOfParameters()
out = [(
self.minimizer.GetParameterName(i),
(self.minimizer.GetParameterValue(i),
self.minimizer.GetParameterScale(i))
) for i in range(n)]
self.results["init_parameters"] = dict(out)
self.minimizer.SetTolerance(self.tolerance)
self.minimizer.SetContractionRatio(self.contraction_ratio)
self.minimizer.SetExpansionRatio(self.expansion_ratio)
self.minimizer.SetMaxIterations(self.max_iterations)
self.minimizer.Minimize()
self.results["convergence_flag"] = not bool(self.minimizer.Iterate())
out = [(
self.minimizer.GetParameterName(i),
self.minimizer.GetParameterValue(i),
) for i in range(n)]
self.results["parameters"] = dict(out)
self.results["min_value"] = self.minimizer.GetFunctionValue()
self.results["iterations"] = self.minimizer.GetIterations()
self.results["max_iterations"] = self.minimizer.GetMaxIterations()
self.results["tolerance"] = self.minimizer.GetTolerance()
self.results["expansion_ratio"] = self.expansion_ratio
self.results["contraction_ratio"] = self.contraction_ratio
self.results["parameters_path"] = np.array(self.parameters_path)
self.results["function_path"] = np.array(self.function_path)
self.results["hessian"] = np.zeros((n,n))
self.results["parameter_errors"] = np.zeros(n)
return self.results
def compute_hessian(self, epsilon=0):
"""
Compute the Hessian matrix of `function` at the
minimum numerically.
Arguments:
epsilon : (float)
Step size used for numerical approximation.
Returns:
array: Hessian matrix of `function` at minimum.
"""
if not epsilon:
epsilon = self.tolerance * 10
n = self.minimizer.GetNumberOfParameters()
x0 = [self.minimizer.GetParameterValue(i) for i in range(n)]
hessian = np.zeros((n, n))
for i in vedo.progressbar(n, title="Computing Hessian", delay=2):
for j in range(n):
xijp = np.copy(x0)
xijp[i] += epsilon
xijp[j] += epsilon
xijm = np.copy(x0)
xijm[i] += epsilon
xijm[j] -= epsilon
xjip = np.copy(x0)
xjip[i] -= epsilon
xjip[j] += epsilon
xjim = np.copy(x0)
xjim[i] -= epsilon
xjim[j] -= epsilon
# Second derivative approximation
fijp = self.function(xijp)
fijm = self.function(xijm)
fjip = self.function(xjip)
fjim = self.function(xjim)
hessian[i, j] = (fijp - fijm - fjip + fjim) / (2 * epsilon**2)
self.results["hessian"] = hessian
try:
ihess = np.linalg.inv(hessian)
self.results["parameter_errors"] = np.sqrt(np.diag(ihess))
except:
vedo.logger.warning("Cannot compute hessian for parameter errors")
self.results["parameter_errors"] = np.zeros(n)
return hessian
def __str__(self) -> str:
out = vedo.printc(
f"vedo.utils.Minimizer at ({hex(id(self))})".ljust(75),
bold=True, invert=True, return_string=True,
)
out += "Function name".ljust(20) + self.function.__name__ + "()\n"
out += "-------- parameters initial value -----------\n"
out += "Name".ljust(20) + "Value".ljust(20) + "Scale\n"
for name, value in self.results["init_parameters"].items():
out += name.ljust(20) + str(value[0]).ljust(20) + str(value[1]) + "\n"
out += "-------- parameters final value --------------\n"
for name, value in self.results["parameters"].items():
out += name.ljust(20) + f"{value:.6f}"
ierr = list(self.results["parameters"]).index(name)
err = self.results["parameter_errors"][ierr]
if err:
out += f" ± {err:.4f}"
out += "\n"
out += "Value at minimum".ljust(20)+ f'{self.results["min_value"]}\n'
out += "Iterations".ljust(20) + f'{self.results["iterations"]}\n'
out += "Max iterations".ljust(20) + f'{self.results["max_iterations"]}\n'
out += "Convergence flag".ljust(20)+ f'{self.results["convergence_flag"]}\n'
out += "Tolerance".ljust(20) + f'{self.results["tolerance"]}\n'
try:
arr = np.array2string(
self.compute_hessian(),
separator=', ', precision=6, suppress_small=True,
)
out += "Hessian Matrix:\n" + arr
except:
out += "Hessian Matrix: (not available)"
return out
###########################################################
def andrews_curves(M, res=100):
"""
Computes the [Andrews curves](https://en.wikipedia.org/wiki/Andrews_plot)
for the provided data.
The input array is an array of shape (n,m) where n is the number of
features and m is the number of observations.
Arguments:
M : (ndarray)
the data matrix (or data vector).
res : (int)
the resolution (n. of points) of the output curve.
Example:
- [andrews_cluster.py](https://github.com/marcomusy/vedo/blob/master/examples/pyplot/andrews_cluster.py)
![](https://vedo.embl.es/images/pyplot/andrews_cluster.png)
"""
# Credits:
# https://gist.github.com/ryuzakyl/12c221ff0e54d8b1ac171c69ea552c0a
M = np.asarray(M)
m = int(res + 0.5)
# getting data vectors
X = np.reshape(M, (1, -1)) if len(M.shape) == 1 else M.copy()
_rows, n = X.shape
# andrews curve dimension (n. theta angles)
t = np.linspace(-np.pi, np.pi, m)
# m: range of values for angle theta
# n: amount of components of the Fourier expansion
A = np.empty((m, n))
# setting first column of A
A[:, 0] = [1/np.sqrt(2)] * m
# filling columns of A
for i in range(1, n):
# computing the scaling coefficient for angle theta
c = np.ceil(i / 2)
# computing i-th column of matrix A
col = np.sin(c * t) if i % 2 == 1 else np.cos(c * t)
# setting column in matrix A
A[:, i] = col[:]
# computing Andrews curves for provided data
andrew_curves = np.dot(A, X.T).T
# returning the Andrews Curves (raveling if needed)
return np.ravel(andrew_curves) if andrew_curves.shape[0] == 1 else andrew_curves
###########################################################
def numpy2vtk(arr, dtype=None, deep=True, name=""):
"""
Convert a numpy array into a `vtkDataArray`.
Use `dtype='id'` for `vtkIdTypeArray` objects.
"""
# https://github.com/Kitware/VTK/blob/master/Wrapping/Python/vtkmodules/util/numpy_support.py
if arr is None:
return None
arr = np.ascontiguousarray(arr)
if dtype == "id":
varr = numpy_to_vtkIdTypeArray(arr.astype(np.int64), deep=deep)
elif dtype:
varr = numpy_to_vtk(arr.astype(dtype), deep=deep)
else:
# let numpy_to_vtk() decide what is best type based on arr type
if arr.dtype == np.bool_:
arr = arr.astype(np.uint8)
varr = numpy_to_vtk(arr, deep=deep)
if name:
varr.SetName(name)
return varr
def vtk2numpy(varr):
"""Convert a `vtkDataArray`, `vtkIdList` or `vtTransform` into a numpy array."""
if varr is None:
return np.array([])
if isinstance(varr, vtki.vtkIdList):
return np.array([varr.GetId(i) for i in range(varr.GetNumberOfIds())])
elif isinstance(varr, vtki.vtkBitArray):
carr = vtki.vtkCharArray()
carr.DeepCopy(varr)
varr = carr
elif isinstance(varr, vtki.vtkHomogeneousTransform):
try:
varr = varr.GetMatrix()
except AttributeError:
pass
n = 4
M = [[varr.GetElement(i, j) for j in range(n)] for i in range(n)]
return np.array(M)
return vtk_to_numpy(varr)
def make3d(pts):
"""
Make an array which might be 2D to 3D.
Array can also be in the form `[allx, ally, allz]`.
"""
if pts is None:
return np.array([])
pts = np.asarray(pts)
if pts.dtype == "object":
raise ValueError("Cannot form a valid numpy array, input may be non-homogenous")
if pts.size == 0: # empty list
return pts
if pts.ndim == 1:
if pts.shape[0] == 2:
return np.hstack([pts, [0]]).astype(pts.dtype)
elif pts.shape[0] == 3:
return pts
else:
raise ValueError
if pts.shape[1] == 3:
return pts
# if 2 <= pts.shape[0] <= 3 and pts.shape[1] > 3:
# pts = pts.T
if pts.shape[1] == 2:
return np.c_[pts, np.zeros(pts.shape[0], dtype=pts.dtype)]
if pts.shape[1] != 3:
raise ValueError(f"input shape is not supported: {pts.shape}")
return pts
def geometry(obj, extent=None):
"""
Apply the `vtkGeometryFilter` to the input object.
This is a general-purpose filter to extract geometry (and associated data)
from any type of dataset.
This filter also may be used to convert any type of data to polygonal type.
The conversion process may be less than satisfactory for some 3D datasets.
For example, this filter will extract the outer surface of a volume
or structured grid dataset.
Returns a `vedo.Mesh` object.
Set `extent` as the `[xmin,xmax, ymin,ymax, zmin,zmax]` bounding box to clip data.
"""
gf = vtki.new("GeometryFilter")
gf.SetInputData(obj)
if extent is not None:
gf.SetExtent(extent)
gf.Update()
return vedo.Mesh(gf.GetOutput())
def buildPolyData(vertices, faces=None, lines=None, strips=None, index_offset=0, tetras=False):
"""
Build a `vtkPolyData` object from a list of vertices
where faces represents the connectivity of the polygonal mesh.
Lines and triangle strips can also be specified.
E.g. :
- `vertices=[[x1,y1,z1],[x2,y2,z2], ...]`
- `faces=[[0,1,2], [1,2,3], ...]`
- `lines=[[0,1], [1,2,3,4], ...]`
- `strips=[[0,1,2,3,4,5], [2,3,9,7,4], ...]`
A flat list of faces can be passed as `faces=[3, 0,1,2, 4, 1,2,3,4, ...]`.
For lines use `lines=[2, 0,1, 4, 1,2,3,4, ...]`.
Use `index_offset=1` if face numbering starts from 1 instead of 0.
If `tetras=True`, interpret 4-point faces as tetrahedrons instead of surface quads.
"""
if is_sequence(faces) and len(faces) == 0:
faces=None
if is_sequence(lines) and len(lines) == 0:
lines=None
if is_sequence(strips) and len(strips) == 0:
strips=None
poly = vtki.vtkPolyData()
if len(vertices) == 0:
return poly
vertices = make3d(vertices)
source_points = vtki.vtkPoints()
source_points.SetData(numpy2vtk(vertices, dtype=np.float32))
poly.SetPoints(source_points)
if lines is not None:
# Create a cell array to store the lines in and add the lines to it
linesarr = vtki.vtkCellArray()
if is_sequence(lines[0]): # assume format [(id0,id1),..]
for iline in lines:
for i in range(0, len(iline) - 1):
i1, i2 = iline[i], iline[i + 1]
if i1 != i2:
vline = vtki.vtkLine()
vline.GetPointIds().SetId(0, i1)
vline.GetPointIds().SetId(1, i2)
linesarr.InsertNextCell(vline)
else: # assume format [id0,id1,...]
# print("buildPolyData: assuming lines format [id0,id1,...]", lines)
# TODO CORRECT THIS CASE, MUST BE [2, id0,id1,...]
for i in range(0, len(lines) - 1):
vline = vtki.vtkLine()
vline.GetPointIds().SetId(0, lines[i])
vline.GetPointIds().SetId(1, lines[i + 1])
linesarr.InsertNextCell(vline)
poly.SetLines(linesarr)
if faces is not None:
source_polygons = vtki.vtkCellArray()
if isinstance(faces, np.ndarray) or not is_ragged(faces):
##### all faces are composed of equal nr of vtxs, FAST
faces = np.asarray(faces)
ast = np.int32
if vtki.vtkIdTypeArray().GetDataTypeSize() != 4:
ast = np.int64
if faces.ndim > 1:
nf, nc = faces.shape
hs = np.hstack((np.zeros(nf)[:, None] + nc, faces))
else:
nf = faces.shape[0]
hs = faces
arr = numpy_to_vtkIdTypeArray(hs.astype(ast).ravel(), deep=True)
source_polygons.SetCells(nf, arr)
else:
############################# manually add faces, SLOW
for f in faces:
n = len(f)
if n == 3:
ele = vtki.vtkTriangle()
pids = ele.GetPointIds()
for i in range(3):
pids.SetId(i, f[i] - index_offset)
source_polygons.InsertNextCell(ele)
elif n == 4 and tetras:
ele0 = vtki.vtkTriangle()
ele1 = vtki.vtkTriangle()
ele2 = vtki.vtkTriangle()
ele3 = vtki.vtkTriangle()
if index_offset:
for i in [0, 1, 2, 3]:
f[i] -= index_offset
f0, f1, f2, f3 = f
pid0 = ele0.GetPointIds()
pid1 = ele1.GetPointIds()
pid2 = ele2.GetPointIds()
pid3 = ele3.GetPointIds()
pid0.SetId(0, f0)
pid0.SetId(1, f1)
pid0.SetId(2, f2)
pid1.SetId(0, f0)
pid1.SetId(1, f1)
pid1.SetId(2, f3)
pid2.SetId(0, f1)
pid2.SetId(1, f2)