Skip to content

vedo.utils

utils

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.

Parameters:

Name Type Description Default
function callable

the function to minimize

None
max_iterations int

the maximum number of iterations

10000
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.

0.5
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.

2.0
tol float

the tolerance for convergence

1e-05

Examples:

Source code in vedo/utils.py
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
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.

    Args:
        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

    Examples:
        - [nelder-mead.py](https://github.com/marcomusy/vedo/blob/master/examples/extras/nelder-mead.py)
    """

    def __init__(
        self,
        function=None,
        max_iterations=10000,
        contraction_ratio=0.5,
        expansion_ratio=2.0,
        tol=1e-5,
    ) -> None:
        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)

    def eval(self, parameters=()) -> float:
        """
        Evaluate the function at the current or given parameters.
        """
        if len(parameters) == 0:
            return self.minimizer.EvaluateFunction()
        self.set_parameters(parameters)
        return self.function(list(parameters.values()))

    def set_parameter(self, name, value, scale=1.0) -> None:
        """
        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) -> None:
        """
        Set the parameters names and values from a dictionary.
        """
        for name, value in parameters.items():
            if is_sequence(value) and len(value) == 2:
                self.set_parameter(name, value[0], value[1])
            else:
                self.set_parameter(name, value)

    def minimize(self) -> dict:
        """
        Minimize the input function.

        A dictionary with the minimization results
        including the initial parameters, final parameters,
        minimum value, number of iterations, maximum iterations,
        tolerance, convergence flag, parameters path,
        function path, Hessian matrix, and parameter errors.

        Args:
            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
        """
        self.parameters_path = []
        self.function_path = []

        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"] = (
            self.minimizer.GetIterations() < self.minimizer.GetMaxIterations()
        )

        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

    @property
    def x(self):
        """Return the final parameters."""
        return self.results["parameters"]

    @property
    def fun(self):
        """Return the final score value."""
        return self.results["min_value"]

    def compute_hessian(self, epsilon=0) -> np.ndarray:
        """
        Compute the Hessian matrix of `function` at the
        minimum numerically.

        Args:
            epsilon (float):
                Step size used for numerical approximation.

        Returns:
            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 = compute_hessian(self.function, x0, epsilon=epsilon)

        self.results["hessian"] = hessian
        try:
            ihess = np.linalg.inv(hessian)
            cov = ihess / 2
            self.results["parameter_errors"] = np.sqrt(np.diag(cov))
        except (np.linalg.LinAlgError, ValueError):
            vedo.logger.warning("Cannot compute hessian for parameter errors")
            self.results["parameter_errors"] = np.zeros(n)
        return hessian

    def __str__(self) -> str:
        return summary_string(self, self._summary_rows())

    def __repr__(self) -> str:
        return self.__str__()

    def __rich__(self):
        return summary_panel(self, self._summary_rows())

    def _summary_rows(self) -> list[tuple[str, str]]:
        rows = [("Function name", self.function.__name__ + "()")]
        init_lines = ["Name".ljust(20) + "Value".ljust(20) + "Scale"]
        for name, value in self.results["init_parameters"].items():
            init_lines.append(name.ljust(20) + str(value[0]).ljust(20) + str(value[1]))
        rows.append(("initial params", "\n".join(init_lines)))

        final_lines = []
        errors = self.results["parameter_errors"]
        for ierr, (name, value) in enumerate(self.results["parameters"].items()):
            line = name.ljust(20) + f"{value:.6f}"
            err = errors[ierr]
            if err:
                line += f" ± {err:.4f}"
            final_lines.append(line)
        rows.append(("final params", "\n".join(final_lines)))
        rows.append(("Value at minimum", f"{self.results['min_value']}"))
        rows.append(("Iterations", f"{self.results['iterations']}"))
        rows.append(("Max iterations", f"{self.results['max_iterations']}"))
        rows.append(("Convergence flag", f"{self.results['convergence_flag']}"))
        rows.append(("Tolerance", f"{self.results['tolerance']}"))
        hessian = self.results.get("hessian")
        if hessian is not None and np.any(hessian):
            try:
                arr = np.array2string(
                    hessian,
                    separator=", ",
                    precision=6,
                    suppress_small=True,
                )
                rows.append(("Hessian Matrix", arr))
            except Exception:
                rows.append(("Hessian Matrix", "(not available)"))
        else:
            rows.append(("Hessian Matrix", "(not computed)"))
        return rows

fun property

Return the final score value.

x property

Return the final parameters.

compute_hessian(epsilon=0)

Compute the Hessian matrix of function at the minimum numerically.

Parameters:

Name Type Description Default
epsilon float

Step size used for numerical approximation.

0

Returns:

Type Description
ndarray

Hessian matrix of function at minimum.

Source code in vedo/utils.py
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
def compute_hessian(self, epsilon=0) -> np.ndarray:
    """
    Compute the Hessian matrix of `function` at the
    minimum numerically.

    Args:
        epsilon (float):
            Step size used for numerical approximation.

    Returns:
        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 = compute_hessian(self.function, x0, epsilon=epsilon)

    self.results["hessian"] = hessian
    try:
        ihess = np.linalg.inv(hessian)
        cov = ihess / 2
        self.results["parameter_errors"] = np.sqrt(np.diag(cov))
    except (np.linalg.LinAlgError, ValueError):
        vedo.logger.warning("Cannot compute hessian for parameter errors")
        self.results["parameter_errors"] = np.zeros(n)
    return hessian

eval(parameters=())

Evaluate the function at the current or given parameters.

Source code in vedo/utils.py
609
610
611
612
613
614
615
616
def eval(self, parameters=()) -> float:
    """
    Evaluate the function at the current or given parameters.
    """
    if len(parameters) == 0:
        return self.minimizer.EvaluateFunction()
    self.set_parameters(parameters)
    return self.function(list(parameters.values()))

minimize()

Minimize the input function.

A dictionary with the minimization results including the initial parameters, final parameters, minimum value, number of iterations, maximum iterations, tolerance, convergence flag, parameters path, function path, Hessian matrix, and parameter errors.

Parameters:

Name Type Description Default
init_parameters dict

the initial parameters

required
parameters dict

the final parameters

required
min_value float

the minimum value

required
iterations int

the number of iterations

required
max_iterations int

the maximum number of iterations

required
tolerance float

the tolerance for convergence

required
convergence_flag int

zero if the tolerance stopping criterion has been met.

required
parameters_path array

the path of the minimization algorithm in parameter space

required
function_path array

the path of the minimization algorithm in function space

required
hessian array

the Hessian matrix of the function at the minimum

required
parameter_errors array

the errors on the parameters

required
Source code in vedo/utils.py
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
def minimize(self) -> dict:
    """
    Minimize the input function.

    A dictionary with the minimization results
    including the initial parameters, final parameters,
    minimum value, number of iterations, maximum iterations,
    tolerance, convergence flag, parameters path,
    function path, Hessian matrix, and parameter errors.

    Args:
        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
    """
    self.parameters_path = []
    self.function_path = []

    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"] = (
        self.minimizer.GetIterations() < self.minimizer.GetMaxIterations()
    )

    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

set_parameter(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.

Source code in vedo/utils.py
618
619
620
621
622
623
624
625
def set_parameter(self, name, value, scale=1.0) -> None:
    """
    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)

set_parameters(parameters)

Set the parameters names and values from a dictionary.

Source code in vedo/utils.py
627
628
629
630
631
632
633
634
635
def set_parameters(self, parameters) -> None:
    """
    Set the parameters names and values from a dictionary.
    """
    for name, value in parameters.items():
        if is_sequence(value) and len(value) == 2:
            self.set_parameter(name, value[0], value[1])
        else:
            self.set_parameter(name, value)

OperationNode

Keep track of the operations which led to a final state.

Source code in vedo/utils.py
 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
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",
    ) -> None:
        """
        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()
        ```

        Args:
            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

        Examples:
            ```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)
        """
        self._enabled = vedo.settings.enable_pipeline
        if not self._enabled:
            self.parents = []
            self.operation = ""
            self.operation_plain = ""
            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

    def add_parent(self, parent) -> None:
        """Add a parent to the list."""
        self.parents.append(parent)

    def _node_id(self):
        return self.operation_plain + str(self.time)

    def _build_tree(self, dot, visited=None):
        if visited is None:
            visited = set()
        nid = self._node_id()
        if nid in visited:
            return
        visited.add(nid)
        dot.node(
            nid,
            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(parent._node_id(), nid, label=t)
                parent._build_tree(dot, visited)

    def __repr__(self):
        if not self._enabled:
            return ""
        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, visited):
            if id(parent) in visited:
                return
            visited.add(id(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, visited)

        try:
            tree = Tree()
            tree.create_node(
                self.operation_plain, self.operation_plain + str(self.time)
            )
            _build_tree(self, set())
            out = tree.show(stdout=False)
        except Exception as e:
            out = f"Sorry treelib failed to build the tree for '{self.operation_plain}()': {e}."
        return out

    def __str__(self):
        return self.__repr__()

    def print(self) -> None:
        """Print the tree of operations."""
        print(self.__repr__())

    def show(self, orientation="LR", popup=True) -> None:
        """Show the graphviz output for the pipeline of this object"""
        if not self._enabled:
            return

        try:
            from graphviz import Digraph
        except ImportError:
            vedo.logger.error(
                "please install graphviz with command\n  pip install graphviz"
            )
            vedo.logger.error("  sudo apt-get install graphviz -y")
            return

        dot = Digraph(
            node_attr={
                "fontcolor": "#201010",
                "fontname": "Helvetica",
                "fontsize": "12",
            },
            edge_attr={"fontname": "Helvetica", "fontsize": "6", "arrowsize": "0.4"},
        )
        dot.attr(rankdir=orientation)

        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)

add_parent(parent)

Add a parent to the list.

Source code in vedo/utils.py
162
163
164
def add_parent(self, parent) -> None:
    """Add a parent to the list."""
    self.parents.append(parent)

print()

Print the tree of operations.

Source code in vedo/utils.py
229
230
231
def print(self) -> None:
    """Print the tree of operations."""
    print(self.__repr__())

show(orientation='LR', popup=True)

Show the graphviz output for the pipeline of this object

Source code in vedo/utils.py
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
def show(self, orientation="LR", popup=True) -> None:
    """Show the graphviz output for the pipeline of this object"""
    if not self._enabled:
        return

    try:
        from graphviz import Digraph
    except ImportError:
        vedo.logger.error(
            "please install graphviz with command\n  pip install graphviz"
        )
        vedo.logger.error("  sudo apt-get install graphviz -y")
        return

    dot = Digraph(
        node_attr={
            "fontcolor": "#201010",
            "fontname": "Helvetica",
            "fontsize": "12",
        },
        edge_attr={"fontname": "Helvetica", "fontsize": "6", "arrowsize": "0.4"},
    )
    dot.attr(rankdir=orientation)

    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)

ProgressBar

Class to print a progress bar.

Source code in vedo/utils.py
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
class ProgressBar:
    """
    Class to print a progress bar.
    """

    def __init__(
        self,
        start: int,
        stop: int,
        step: int = 1,
        c: str | None = None,
        bold: bool = True,
        italic: bool = False,
        title: str = "",
        eta: bool = True,
        delay: float = -1,
        width: int | None = 25,
        char: str = "\U00002501",
        char_back: str = "\U00002500",
    ) -> None:
        """
        Class to print a progress bar with optional text message.

        Check out also function `progressbar()`.

        Args:
            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; None adapts to terminal width
            char (str):
                character to use for the progress bar
            char_back (str):
                character to use for the background of the progress bar

        Examples:
            ```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 else ""

        if delay < 0:
            delay = vedo.settings.progressbar_delay

        self.start = start
        self.stop = stop
        self.step = step if step != 0 else 1
        if self.stop < self.start and self.step > 0:
            self.step = -self.step

        self.color = c
        self.bold = bold
        self.italic = italic
        self._fixed_width = width
        self.width = self._compute_width()
        self.pbar = ""
        self.percent = 0.0
        self.percent_int = 0
        self.eta = eta
        self.delay = float(delay)

        self._t0 = time.perf_counter()
        self._last_print = ""
        self._finished = False
        self._cursor_hidden = False
        self._ema_rate: float | None = None

        self._counts = start
        self._prev_counts = start

        self._update(self._counts)
        self._range = np.arange(start, stop, self.step)

    def print(self, txt: str = "", c: str | None = None) -> None:
        """Print the progress bar with an optional message."""
        if self._finished:
            return

        self._update(self._counts + self.step)

        if self.delay and (time.perf_counter() - self._t0) < self.delay:
            return

        if self.pbar != self._last_print:
            self._last_print = self.pbar
            if not self._cursor_hidden:
                print("\x1b[?25l", end="", flush=True)
                self._cursor_hidden = True

            eta_str = self._format_eta() if (self.eta and self._counts != self.start) else ""
            s = self._fit_line(eta_str, txt)
            vedo.printc(s, c=c or self.color, bold=self.bold, italic=self.italic, end="\x1b[K\r")

            if self.percent >= 99.999:
                self.finish()

    def range(self) -> np.ndarray:
        """Return the range iterator."""
        return self._range

    def finish(self) -> None:
        """Force a final newline."""
        if not self._finished:
            if self._cursor_hidden:
                print("\x1b[?25h", end="", flush=True)
                self._cursor_hidden = False
            print("")
            self._finished = True

    def __del__(self):
        if getattr(self, "_cursor_hidden", False):
            print("\x1b[?25h\n", end="", flush=True)

    def __iter__(self):
        self._iter_value = self.start
        return self

    def __next__(self):
        v = self._iter_value
        if (self.step > 0 and v >= self.stop) or (self.step < 0 and v <= self.stop):
            raise StopIteration
        self._iter_value += self.step
        return v

    def _fit_line(self, eta_str: str, txt: str) -> str:
        try:
            cols = shutil.get_terminal_size().columns
        except Exception:
            cols = 80
        pbar_vis = len(_ANSI_RE.sub("", self.pbar))
        avail = cols - pbar_vis - 2  # -1 space separator, -1 for double-space before txt
        if avail <= 0:
            return f"{self.percent_int}%" if pbar_vis > cols else self.pbar
        suffix = f"{eta_str}  {txt}".rstrip() if txt else eta_str
        if len(suffix) <= avail:
            return f"{self.pbar} {suffix}"
        if len(eta_str) <= avail:
            return f"{self.pbar} {eta_str}"
        if avail >= 2:
            return f"{self.pbar} {eta_str[:avail - 1]}…"
        return self.pbar

    def _compute_width(self) -> int:
        if self._fixed_width is not None:
            return max(8, int(self._fixed_width))
        try:
            cols = shutil.get_terminal_size().columns
        except Exception:
            cols = 80
        return max(8, cols - max(30, len(self.title) + 12))

    def _update(self, counts: int) -> None:
        lo, hi = min(self.start, self.stop), max(self.start, self.stop)
        self._prev_counts = self._counts
        self._counts = max(lo, min(hi, counts))

        if self._fixed_width is None:
            self.width = self._compute_width()

        total = self.stop - self.start or 1
        self.percent = max(0.0, min(100.0, 100.0 * (self._counts - self.start) / total))
        self.percent_int = int(round(self.percent))

        af = max(2, self.width - 2)
        nh = max(0, min(af, int(round(self.percent / 100.0 * af))))
        bg = "\x1b[2m" + self.char_back * (af - nh) + "\x1b[22m"
        ps = "" if self.percent >= 100.0 else f" {self.percent_int}%"
        self.pbar = f"{self.title}{self.char * nh}{bg}{ps}"

        delta = abs(self._counts - self._prev_counts)
        if delta > 0:
            dt = max(1e-9, time.perf_counter() - self._t0)
            inst = abs(self._counts - self.start) / dt
            self._ema_rate = inst if self._ema_rate is None else 0.2 * inst + 0.8 * self._ema_rate

    def _format_eta(self) -> str:
        rate = max(self._ema_rate or 0.0, 1e-12)
        remaining = max(0.0, abs(self.stop - self._counts) / rate)

        def _fmt(s: float) -> str:
            if s >= 60:
                m = int(s // 60)
                return f"{m}m{int(round(s - 60*m))}s "
            return f"{int(round(s))}s "

        if remaining < 0.5:
            return f"elapsed: {_fmt(time.perf_counter() - self._t0)}({round(rate,1)} it/s)"
        return f"eta: {_fmt(remaining)}({round(rate,1)} it/s)"

finish()

Force a final newline.

Source code in vedo/utils.py
392
393
394
395
396
397
398
399
def finish(self) -> None:
    """Force a final newline."""
    if not self._finished:
        if self._cursor_hidden:
            print("\x1b[?25h", end="", flush=True)
            self._cursor_hidden = False
        print("")
        self._finished = True

print(txt='', c=None)

Print the progress bar with an optional message.

Source code in vedo/utils.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
def print(self, txt: str = "", c: str | None = None) -> None:
    """Print the progress bar with an optional message."""
    if self._finished:
        return

    self._update(self._counts + self.step)

    if self.delay and (time.perf_counter() - self._t0) < self.delay:
        return

    if self.pbar != self._last_print:
        self._last_print = self.pbar
        if not self._cursor_hidden:
            print("\x1b[?25l", end="", flush=True)
            self._cursor_hidden = True

        eta_str = self._format_eta() if (self.eta and self._counts != self.start) else ""
        s = self._fit_line(eta_str, txt)
        vedo.printc(s, c=c or self.color, bold=self.bold, italic=self.italic, end="\x1b[K\r")

        if self.percent >= 99.999:
            self.finish()

range()

Return the range iterator.

Source code in vedo/utils.py
388
389
390
def range(self) -> np.ndarray:
    """Return the range iterator."""
    return self._range

andrews_curves(M, res=100)

Computes the Andrews curves 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.

Parameters:

Name Type Description Default
M ndarray

the data matrix (or data vector).

required
res int

the resolution (n. of points) of the output curve.

100

Examples:

Source code in vedo/utils.py
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
def andrews_curves(M, res=100) -> np.ndarray:
    """
    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.

    Args:
        M (ndarray):
            the data matrix (or data vector).
        res (int):
            the resolution (n. of points) of the output curve.

    Examples:
        - [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

buildPolyData(vertices, faces=None, lines=None, strips=None, index_offset=0)

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.

Source code in vedo/utils.py
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
def buildPolyData(
    vertices, faces=None, lines=None, strips=None, index_offset=0
) -> vtki.vtkPolyData:
    """
    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 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()
    if vedo.settings.force_single_precision_points:
        source_points.SetData(numpy2vtk(vertices, dtype=np.float32))
    else:
        source_points.SetData(numpy2vtk(vertices))
    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:
            # VTK-style connectivity stream format:
            # [n0, p0, p1, ..., n1, q0, q1, ...]
            # For n==2 we insert a line segment, for n>2 a polyline.
            i = 0
            nvals = len(lines)
            while i < nvals:
                npts = int(lines[i])
                if npts < 2:
                    raise ValueError(
                        "buildPolyData(lines): each cell must have at least 2 points"
                    )
                end = i + 1 + npts
                if end > nvals:
                    raise ValueError(
                        "buildPolyData(lines): malformed connectivity stream, "
                        f"expected {npts} ids after position {i}"
                    )
                ids = [int(pid) for pid in lines[i + 1 : end]]
                if npts == 2:
                    vline = vtki.vtkLine()
                    vline.GetPointIds().SetId(0, ids[0])
                    vline.GetPointIds().SetId(1, ids[1])
                    linesarr.InsertNextCell(vline)
                else:
                    pline = vtki.vtkPolyLine()
                    pline.GetPointIds().SetNumberOfIds(npts)
                    for k, pid in enumerate(ids):
                        pline.GetPointIds().SetId(k, pid)
                    linesarr.InsertNextCell(pline)
                i = end
        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)
            if vtki.vtkIdTypeArray().GetDataTypeSize() != 4:
                ast = np.int64
            else:
                ast = np.int32

            if faces.ndim > 1:
                nf, nc = faces.shape
                hs = np.hstack((np.zeros(nf)[:, None] + nc, faces - index_offset))
            else:
                nf = faces.shape[0]
                hs = faces.copy()
                # Flat packed format: [n0, p0, p1, ..., n1, q0, q1, ...]
                # Apply index_offset only to point-id entries.
                i = 0
                while i < len(hs):
                    nids = int(hs[i])
                    start = i + 1
                    end = start + nids
                    hs[start:end] -= index_offset
                    i = end
            arr = numpy_to_vtkIdTypeArray(hs.astype(ast).ravel(), deep=True)
            # VTK >= 9.6 deprecates vtkCellArray.SetCells(n, legacy_arr).
            # Prefer ImportLegacyFormat when available and keep fallback for older VTK.
            if hasattr(source_polygons, "ImportLegacyFormat"):
                source_polygons.ImportLegacyFormat(arr)
            else:
                source_polygons.SetCells(nf, arr)

        else:
            ############################# manually add faces, SLOW
            for f in faces:
                n = len(f)

                if n == 3:
                    tri = vtki.vtkTriangle()
                    pids = tri.GetPointIds()
                    for i in range(3):
                        pids.SetId(i, f[i] - index_offset)
                    source_polygons.InsertNextCell(tri)

                else:
                    ele = vtki.vtkPolygon()
                    pids = ele.GetPointIds()
                    pids.SetNumberOfIds(n)
                    for i in range(n):
                        pids.SetId(i, f[i] - index_offset)
                    source_polygons.InsertNextCell(ele)

        poly.SetPolys(source_polygons)

    if strips is not None:
        tscells = vtki.vtkCellArray()
        for strip in strips:
            # create a triangle strip
            # https://vtk.org/doc/nightly/html/classvtkTriangleStrip.html
            n = len(strip)
            tstrip = vtki.vtkTriangleStrip()
            tstrip_ids = tstrip.GetPointIds()
            tstrip_ids.SetNumberOfIds(n)
            for i in range(n):
                tstrip_ids.SetId(i, strip[i] - index_offset)
            tscells.InsertNextCell(tstrip)
        poly.SetStrips(tscells)

    if faces is None and lines is None and strips is None:
        source_vertices = vtki.vtkCellArray()
        for i in range(len(vertices)):
            source_vertices.InsertNextCell(1)
            source_vertices.InsertCellPoint(i)
        poly.SetVerts(source_vertices)

    # print("buildPolyData \n",
    #     poly.GetNumberOfPoints(),
    #     poly.GetNumberOfCells(), # grand total
    #     poly.GetNumberOfLines(),
    #     poly.GetNumberOfPolys(),
    #     poly.GetNumberOfStrips(),
    #     poly.GetNumberOfVerts(),
    # )
    return poly

camera_from_dict(camera, modify_inplace=None)

Generate a vtkCamera object from a python dictionary.

Parameters of the camera are
  • position or pos (3-tuple)
  • focal_point (3-tuple)
  • viewup (3-tuple)
  • distance (float)
  • clipping_range (2-tuple)
  • parallel_scale (float)
  • thickness (float)
  • view_angle (float)
  • roll (float)

Exaplanation of the parameters can be found in the vtkCamera documentation.

Parameters:

Name Type Description Default
camera dict

a python dictionary containing camera parameters.

required
modify_inplace vtkCamera

an existing vtkCamera object to modify in place.

None

Returns:

Type Description
vtkCamera

vtki.vtkCamera, a vtk camera setup that matches this state.

Source code in vedo/utils.py
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
def camera_from_dict(camera, modify_inplace=None) -> vtki.vtkCamera:
    """
    Generate a `vtkCamera` object from a python dictionary.

    Parameters of the camera are:
        - `position` or `pos` (3-tuple)
        - `focal_point` (3-tuple)
        - `viewup` (3-tuple)
        - `distance` (float)
        - `clipping_range` (2-tuple)
        - `parallel_scale` (float)
        - `thickness` (float)
        - `view_angle` (float)
        - `roll` (float)

    Exaplanation of the parameters can be found in the
    [vtkCamera documentation](https://vtk.org/doc/nightly/html/classvtkCamera.html).

    Args:
        camera (dict):
            a python dictionary containing camera parameters.
        modify_inplace (vtkCamera):
            an existing `vtkCamera` object to modify in place.

    Returns:
        `vtki.vtkCamera`, a vtk camera setup that matches this state.
    """
    if modify_inplace is not None:
        vcam = modify_inplace
    else:
        vcam = vtki.vtkCamera()

    camera = dict(camera)  # make a copy so input is not emptied by pop()

    cm_pos = camera.pop("position", camera.pop("pos", None))
    cm_focal_point = camera.pop("focal_point", camera.pop("focalPoint", None))
    cm_viewup = camera.pop("viewup", None)
    cm_distance = camera.pop("distance", None)
    cm_clipping_range = camera.pop("clipping_range", camera.pop("clippingRange", None))
    cm_parallel_scale = camera.pop("parallel_scale", camera.pop("parallelScale", None))
    cm_thickness = camera.pop("thickness", None)
    cm_view_angle = camera.pop("view_angle", camera.pop("viewAngle", None))
    cm_roll = camera.pop("roll", None)

    if len(camera.keys()) > 0:
        vedo.logger.warning(
            f"in camera_from_dict, key(s) not recognized: {camera.keys()}"
        )
    if cm_pos is not None:
        vcam.SetPosition(cm_pos)
    if cm_focal_point is not None:
        vcam.SetFocalPoint(cm_focal_point)
    if cm_viewup is not None:
        vcam.SetViewUp(cm_viewup)
    if cm_distance is not None:
        vcam.SetDistance(cm_distance)
    if cm_clipping_range is not None:
        vcam.SetClippingRange(cm_clipping_range)
    if cm_parallel_scale is not None:
        vcam.SetParallelScale(cm_parallel_scale)
    if cm_thickness is not None:
        vcam.SetThickness(cm_thickness)
    if cm_view_angle is not None:
        vcam.SetViewAngle(cm_view_angle)
    if cm_roll is not None:
        vcam.SetRoll(cm_roll)
    return vcam

camera_from_neuroglancer(state, zoom)

Define a vtkCamera from a neuroglancer state dictionary.

Parameters:

Name Type Description Default
state dict

an neuroglancer state dictionary.

required
zoom float

how much to multiply zoom by to get camera backoff distance

required

Returns:

Type Description
vtkCamera

vtki.vtkCamera, a vtk camera setup that matches this state.

Source code in vedo/utils.py
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
def camera_from_neuroglancer(state, zoom) -> vtki.vtkCamera:
    """
    Define a `vtkCamera` from a neuroglancer state dictionary.

    Args:
        state (dict):
            an neuroglancer state dictionary.
        zoom (float):
            how much to multiply zoom by to get camera backoff distance

    Returns:
        `vtki.vtkCamera`, a vtk camera setup that matches this state.
    """
    orient = state.get("perspectiveOrientation", [0.0, 0.0, 0.0, 1.0])
    pzoom = state.get("perspectiveZoom", 10.0)
    position = state["navigation"]["pose"]["position"]
    pos_nm = np.array(position["voxelCoordinates"]) * position["voxelSize"]
    return camera_from_quaternion(pos_nm, orient, pzoom * zoom, ngl_correct=True)

camera_from_quaternion(pos, quaternion, distance=10000, ngl_correct=True)

Define a vtkCamera with a particular orientation.

Parameters:

Name Type Description Default
pos (array, list, tuple)

an iterator of length 3 containing the focus point of the camera

required
quaternion (array, list, tuple)

a len(4) quaternion (x,y,z,w) describing the rotation of the camera such as returned by neuroglancer x,y,z,w all in [0,1] range

required
distance float

the desired distance from pos to the camera (default = 10000 nm)

10000

Returns:

Type Description
vtkCamera

vtki.vtkCamera, a vtk camera setup according to these rules.

Source code in vedo/utils.py
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
def camera_from_quaternion(
    pos, quaternion, distance=10000, ngl_correct=True
) -> vtki.vtkCamera:
    """
    Define a `vtkCamera` with a particular orientation.

    Args:
        pos (np.array, list, tuple):
            an iterator of length 3 containing the focus point of the camera
        quaternion (np.array, list, tuple):
            a len(4) quaternion `(x,y,z,w)` describing the rotation of the camera
            such as returned by neuroglancer `x,y,z,w` all in `[0,1]` range
        distance (float):
            the desired distance from pos to the camera (default = 10000 nm)

    Returns:
        `vtki.vtkCamera`, a vtk camera setup according to these rules.
    """
    camera = vtki.vtkCamera()
    quat = vedo.Quaternion.from_xyzw(quaternion)
    M = quat.matrix3x3.astype(np.float32)
    focus = np.asarray(pos, dtype=float)
    # the default camera orientation is y up
    up = [0, 1, 0]
    # calculate default camera position is backed off in positive z
    backoff = [0, 0, distance]

    # set the camera rototation by applying the rotation matrix
    camera.SetViewUp(*np.dot(M, up))
    # set the camera position by applying the rotation matrix
    camera.SetPosition(*np.dot(M, backoff))
    if ngl_correct:
        # neuroglancer has positive y going down
        # so apply these azimuth and roll corrections
        # to fix orientatins
        camera.Azimuth(-180)
        camera.Roll(180)

    # shift the camera posiiton and focal position
    # to be centered on the desired location
    p = camera.GetPosition()
    p_new = np.array(p) + focus
    camera.SetPosition(*p_new)
    camera.SetFocalPoint(*focus)
    return camera

camera_to_dict(vtkcam)

Convert a vtkCamera object into a python dictionary.

Parameters of the camera are
  • position (3-tuple)
  • focal_point (3-tuple)
  • viewup (3-tuple)
  • distance (float)
  • clipping_range (2-tuple)
  • parallel_scale (float)
  • thickness (float)
  • view_angle (float)
  • roll (float)

Parameters:

Name Type Description Default
vtkcam vtkCamera

a vtkCamera object to convert.

required
Source code in vedo/utils.py
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
def camera_to_dict(vtkcam) -> dict:
    """
    Convert a [vtkCamera](https://vtk.org/doc/nightly/html/classvtkCamera.html)
    object into a python dictionary.

    Parameters of the camera are:
        - `position` (3-tuple)
        - `focal_point` (3-tuple)
        - `viewup` (3-tuple)
        - `distance` (float)
        - `clipping_range` (2-tuple)
        - `parallel_scale` (float)
        - `thickness` (float)
        - `view_angle` (float)
        - `roll` (float)

    Args:
        vtkcam (vtkCamera):
            a `vtkCamera` object to convert.
    """
    cam = dict()
    cam["position"] = np.array(vtkcam.GetPosition())
    cam["focal_point"] = np.array(vtkcam.GetFocalPoint())
    cam["viewup"] = np.array(vtkcam.GetViewUp())
    cam["distance"] = vtkcam.GetDistance()
    cam["clipping_range"] = np.array(vtkcam.GetClippingRange())
    cam["parallel_scale"] = vtkcam.GetParallelScale()
    cam["thickness"] = vtkcam.GetThickness()
    cam["view_angle"] = vtkcam.GetViewAngle()
    cam["roll"] = vtkcam.GetRoll()
    return cam

circle_from_3points(p1, p2, p3)

Find the center and radius of a circle given 3 points in 3D space.

Returns the center of the circle.

Examples:

from vedo.utils import mag, circle_from_3points
p1 = [0,1,1]
p2 = [3,0,1]
p3 = [1,2,0]
c = circle_from_3points(p1, p2, p3)
print(mag(c-p1), mag(c-p2), mag(c-p3))

Source code in vedo/utils.py
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
def circle_from_3points(p1, p2, p3) -> np.ndarray:
    """
    Find the center and radius of a circle given 3 points in 3D space.

    Returns the center of the circle.

    Examples:
    ```python
    from vedo.utils import mag, circle_from_3points
    p1 = [0,1,1]
    p2 = [3,0,1]
    p3 = [1,2,0]
    c = circle_from_3points(p1, p2, p3)
    print(mag(c-p1), mag(c-p2), mag(c-p3))
    ```
    """
    p1 = np.asarray(p1)
    p2 = np.asarray(p2)
    p3 = np.asarray(p3)
    v1 = p2 - p1
    v2 = p3 - p1
    v11 = np.dot(v1, v1)
    v22 = np.dot(v2, v2)
    v12 = np.dot(v1, v2)
    f = 1.0 / (2 * (v11 * v22 - v12 * v12))
    k1 = f * v22 * (v11 - v12)
    k2 = f * v11 * (v22 - v12)
    return p1 + k1 * v1 + k2 * v2

closest(point, points, n=1, return_ids=False, use_tree=False)

Returns the distances and the closest point(s) to the given set of points. Needs scipy.spatial library.

Parameters:

Name Type Description Default
n int

the nr of closest points to return

1
return_ids bool

return the ids instead of the points coordinates

False
use_tree bool

build a scipy.spatial.KDTree. An already existing one can be passed to avoid rebuilding.

False
Source code in vedo/utils.py
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
def closest(point, points, n=1, return_ids=False, use_tree=False):
    """
    Returns the distances and the closest point(s) to the given set of points.
    Needs `scipy.spatial` library.

    Args:
        n (int):
            the nr of closest points to return
        return_ids (bool):
            return the ids instead of the points coordinates
        use_tree (bool):
            build a `scipy.spatial.KDTree`.
            An already existing one can be passed to avoid rebuilding.
    """
    from scipy.spatial import distance, KDTree

    points = np.asarray(points)
    if n == 1:
        dists = distance.cdist([point], points)
        closest_idx = np.argmin(dists)
    else:
        if use_tree:
            if isinstance(use_tree, KDTree):  # reuse
                tree = use_tree
            else:
                tree = KDTree(points)
            dists, closest_idx = tree.query([point], k=n)
            closest_idx = closest_idx[0]
        else:
            dists = distance.cdist([point], points)
            closest_idx = np.argsort(dists)[0][:n]
    if return_ids:
        return dists, closest_idx
    else:
        return dists, points[closest_idx]

compute_hessian(func, params, bounds=None, epsilon=1e-05, verbose=True)

Compute the Hessian matrix of a scalar function func at params, accounting for parameter boundaries.

Parameters:

Name Type Description Default
func callable

Function returning a scalar. Takes params as input.

required
params ndarray

Parameter vector at which to compute the Hessian.

required
bounds list of tuples

Optional bounds for parameters, e.g., [(lb1, ub1), ...].

None
epsilon float

Base step size for finite differences.

1e-05
verbose bool

Whether to print progress.

True

Returns:

Type Description
ndarray

Hessian matrix of shape (n_params, n_params).

Examples:

from vedo import *
import numpy as np

# 1. Define the objective function to minimize
def cost_function(params):
    a, b = params[0], params[1]
    score = (a-5)**2 + (b-2)**2 #+a*b
    #print(a, b, score)
    return score

# 2. Fit parameters (example result)
mle_params = np.array([4.97, 1.95])  # Assume obtained via optimization

# 3. Define bounds for parameters
bounds = [(-np.inf, np.inf), (1e-6, 2.1)]

# 4. Compute Hessian
hessian = compute_hessian(cost_function, mle_params, bounds=bounds)
cov_matrix = np.linalg.inv(hessian) / 2
print("Covariance Matrix:", cov_matrix)
std = np.sqrt(np.diag(cov_matrix))
print("Standard deviations:", std)

Source code in vedo/utils.py
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
def compute_hessian(
    func, params, bounds=None, epsilon=1e-5, verbose=True
) -> np.ndarray:
    """
    Compute the Hessian matrix of a scalar function `func` at `params`,
    accounting for parameter boundaries.

    Args:
        func (callable):
            Function returning a scalar. Takes `params` as input.
        params (np.ndarray):
            Parameter vector at which to compute the Hessian.
        bounds (list of tuples):
            Optional bounds for parameters, e.g., [(lb1, ub1), ...].
        epsilon (float):
            Base step size for finite differences.
        verbose (bool):
            Whether to print progress.

    Returns:
        Hessian matrix of shape (n_params, n_params).

    Examples:
    ```python
    from vedo import *
    import numpy as np

    # 1. Define the objective function to minimize
    def cost_function(params):
        a, b = params[0], params[1]
        score = (a-5)**2 + (b-2)**2 #+a*b
        #print(a, b, score)
        return score

    # 2. Fit parameters (example result)
    mle_params = np.array([4.97, 1.95])  # Assume obtained via optimization

    # 3. Define bounds for parameters
    bounds = [(-np.inf, np.inf), (1e-6, 2.1)]

    # 4. Compute Hessian
    hessian = compute_hessian(cost_function, mle_params, bounds=bounds)
    cov_matrix = np.linalg.inv(hessian) / 2
    print("Covariance Matrix:", cov_matrix)
    std = np.sqrt(np.diag(cov_matrix))
    print("Standard deviations:", std)
    ```
    """
    n = len(params)
    hessian = np.zeros((n, n))
    f_0 = func(params)  # Central value

    # Diagonal elements (second derivatives)
    for i in range(n):
        if verbose:
            vedo.printc(f"Computing Hessian: {i + 1}/{n} for diagonal", delay=0)
        if bounds:
            lb, ub = bounds[i]
        else:
            lb, ub = -np.inf, np.inf

        # Adaptive step size to stay within bounds
        h_plus = min(epsilon, ub - params[i])  # Max allowed step upward
        h_minus = min(epsilon, params[i] - lb)  # Max allowed step downward
        h = min(h_plus, h_minus)  # Use symmetric step where possible

        # Avoid zero step size (if parameter is at a boundary)
        if h <= 0:
            h = epsilon  # Fallback to one-sided derivative

        # Compute f(x + h) and f(x - h)
        params_plus = np.copy(params)
        params_plus[i] = np.clip(params[i] + h, lb, ub)
        f_plus = func(params_plus)

        params_minus = np.copy(params)
        params_minus[i] = np.clip(params[i] - h, lb, ub)
        f_minus = func(params_minus)

        # Central difference for diagonal
        hessian[i, i] = (f_plus - 2 * f_0 + f_minus) / (h**2)

    # Off-diagonal elements (mixed partial derivatives)
    for i in range(n):
        if verbose:
            vedo.printc(f"Computing Hessian: {i + 1}/{n} for off-diagonal", delay=0)
        for j in range(i + 1, n):
            if bounds:
                lb_i, ub_i = bounds[i]
                lb_j, ub_j = bounds[j]
            else:
                lb_i, ub_i = -np.inf, np.inf
                lb_j, ub_j = -np.inf, np.inf

            # Step sizes for i and j
            h_i_plus = min(epsilon, ub_i - params[i])
            h_i_minus = min(epsilon, params[i] - lb_i)
            h_i = min(h_i_plus, h_i_minus)
            h_i = max(h_i, 1e-10)  # Prevent division by zero

            h_j_plus = min(epsilon, ub_j - params[j])
            h_j_minus = min(epsilon, params[j] - lb_j)
            h_j = min(h_j_plus, h_j_minus)
            h_j = max(h_j, 1e-10)

            # Compute four perturbed points
            params_pp = np.copy(params)
            params_pp[i] = np.clip(params[i] + h_i, lb_i, ub_i)
            params_pp[j] = np.clip(params[j] + h_j, lb_j, ub_j)
            f_pp = func(params_pp)

            params_pm = np.copy(params)
            params_pm[i] = np.clip(params[i] + h_i, lb_i, ub_i)
            params_pm[j] = np.clip(params[j] - h_j, lb_j, ub_j)
            f_pm = func(params_pm)

            params_mp = np.copy(params)
            params_mp[i] = np.clip(params[i] - h_i, lb_i, ub_i)
            params_mp[j] = np.clip(params[j] + h_j, lb_j, ub_j)
            f_mp = func(params_mp)

            params_mm = np.copy(params)
            params_mm[i] = np.clip(params[i] - h_i, lb_i, ub_i)
            params_mm[j] = np.clip(params[j] - h_j, lb_j, ub_j)
            f_mm = func(params_mm)

            # Central difference for off-diagonal
            hessian[i, j] = (f_pp - f_pm - f_mp + f_mm) / (4 * h_i * h_j)
            hessian[j, i] = hessian[i, j]  # Symmetric
    return hessian

ctf2lut(vol, logscale=False)

Internal use.

Source code in vedo/utils.py
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
def ctf2lut(vol, logscale=False):
    """Internal use."""
    # build LUT from a color transfer function for tmesh or volume

    ctf = vol.properties.GetRGBTransferFunction()
    otf = vol.properties.GetScalarOpacity()
    x0, x1 = vol.dataset.GetScalarRange()
    cols, alphas = [], []
    for x in np.linspace(x0, x1, 256):
        cols.append(ctf.GetColor(x))
        alphas.append(otf.GetValue(x))

    if logscale:
        lut = vtki.vtkLogLookupTable()
    else:
        lut = vtki.vtkLookupTable()

    lut.SetRange(x0, x1)
    lut.SetNumberOfTableValues(len(cols))
    for i, col in enumerate(cols):
        r, g, b = col
        lut.SetTableValue(i, r, g, b, alphas[i])
    lut.Build()
    return lut

flatten(list_to_flatten)

Flatten out a list.

Source code in vedo/utils.py
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
def flatten(list_to_flatten) -> list:
    """Flatten out a list."""

    def _genflatten(lst):
        for elem in lst:
            if isinstance(elem, (list, tuple)):
                for x in flatten(elem):
                    yield x
            else:
                yield elem

    return list(_genflatten(list_to_flatten))

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.

Source code in vedo/utils.py
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
def geometry(obj, extent=None) -> vedo.Mesh:
    """
    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())

get_font_path(font)

Internal use.

Source code in vedo/utils.py
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
def get_font_path(font: str) -> str:
    """Internal use."""
    if font in vedo.settings.font_parameters.keys():
        if vedo.settings.font_parameters[font]["islocal"]:
            fl = os.path.join(vedo.fonts_path, f"{font}.ttf")
        else:
            try:
                fl = vedo.file_io.download(
                    f"https://vedo.embl.es/fonts/{font}.ttf", verbose=False
                )
            except Exception:
                vedo.logger.warning(
                    f"Could not download https://vedo.embl.es/fonts/{font}.ttf"
                )
                fl = os.path.join(vedo.fonts_path, "Normografo.ttf")
    else:
        if font.startswith("https://"):
            fl = vedo.file_io.download(font, verbose=False)
        elif os.path.isfile(font):
            fl = font  # assume user is passing a valid file
        else:
            if font.endswith(".ttf"):
                vedo.logger.error(
                    f"Could not set font file {font}"
                    f"-> using default: {vedo.settings.default_font}"
                )
            else:
                vedo.settings.default_font = "Normografo"
                vedo.logger.error(
                    f"Could not set font name {font}"
                    f" -> using default: Normografo\n"
                    f"Check out https://vedo.embl.es/fonts for additional fonts\n"
                    f"Type 'vedo -r fonts' to see available fonts"
                )
            fl = get_font_path(vedo.settings.default_font)
    return fl

get_uv(p, x, v)

Obtain the texture uv-coords of a point p belonging to a face that has point coordinates (x0, x1, x2) with the corresponding uv-coordinates v=(v0, v1, v2). All p and x0,x1,x2 are 3D-vectors, while v are their 2D uv-coordinates.

Examples:

from vedo import *

pic = Image(dataurl+"coloured_cube_faces.jpg")
cb = Mesh(dataurl+"coloured_cube.obj").lighting("off").texture(pic)

cbpts = cb.points
faces = cb.cells
uv = cb.pointdata["Material"]

pt = [-0.2, 0.75, 2]
pr = cb.closest_point(pt)

idface = cb.closest_point(pt, return_cell_id=True)
idpts = faces[idface]
uv_face = uv[idpts]

uv_pr = utils.get_uv(pr, cbpts[idpts], uv_face)
print("interpolated uv =", uv_pr)

sx, sy = pic.dimensions()
i_interp_uv = uv_pr * [sy, sx]
ix, iy = i_interp_uv.astype(int)
mpic = pic.tomesh()
rgba = mpic.pointdata["RGBA"].reshape(sy, sx, 3)
print("color =", rgba[ix, iy])

show(
    [[cb, Point(pr), cb.labels("Material")],
        [pic, Point(i_interp_uv)]],
    N=2, axes=1, sharecam=False,
).close()

Source code in vedo/utils.py
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
def get_uv(p, x, v):
    """
    Obtain the texture uv-coords of a point p belonging to a face that has point
    coordinates (x0, x1, x2) with the corresponding uv-coordinates v=(v0, v1, v2).
    All p and x0,x1,x2 are 3D-vectors, while v are their 2D uv-coordinates.

    Examples:
        ```python
        from vedo import *

        pic = Image(dataurl+"coloured_cube_faces.jpg")
        cb = Mesh(dataurl+"coloured_cube.obj").lighting("off").texture(pic)

        cbpts = cb.points
        faces = cb.cells
        uv = cb.pointdata["Material"]

        pt = [-0.2, 0.75, 2]
        pr = cb.closest_point(pt)

        idface = cb.closest_point(pt, return_cell_id=True)
        idpts = faces[idface]
        uv_face = uv[idpts]

        uv_pr = utils.get_uv(pr, cbpts[idpts], uv_face)
        print("interpolated uv =", uv_pr)

        sx, sy = pic.dimensions()
        i_interp_uv = uv_pr * [sy, sx]
        ix, iy = i_interp_uv.astype(int)
        mpic = pic.tomesh()
        rgba = mpic.pointdata["RGBA"].reshape(sy, sx, 3)
        print("color =", rgba[ix, iy])

        show(
            [[cb, Point(pr), cb.labels("Material")],
                [pic, Point(i_interp_uv)]],
            N=2, axes=1, sharecam=False,
        ).close()
        ```
        ![](https://vedo.embl.es/images/feats/utils_get_uv.png)
    """
    # Vector vp=p-x0 is representable as alpha*s + beta*t,
    # where s = x1-x0 and t = x2-x0, in matrix form
    # vp = [alpha, beta] . matrix(s,t)
    # M = matrix(s,t) is 2x3 matrix, so (alpha, beta) can be found by
    # inverting any of its minor A with non-zero determinant.
    # Once found, uv-coords of p are vt0 + alpha (vt1-v0) + beta (vt2-v0)

    p = np.asarray(p)
    x0, x1, x2 = np.asarray(x)[:3]
    vt0, vt1, vt2 = np.asarray(v)[:3]

    s = x1 - x0
    t = x2 - x0
    vs = vt1 - vt0
    vt = vt2 - vt0
    vp = p - x0

    # finding a minor with independent rows
    M = np.array([s, t])
    mnr = [0, 1]
    A = M[:, mnr]
    if np.abs(np.linalg.det(A)) < 0.000001:
        mnr = [0, 2]
        A = M[:, mnr]
        if np.abs(np.linalg.det(A)) < 0.000001:
            mnr = [1, 2]
            A = M[:, mnr]
    Ainv = np.linalg.inv(A)
    alpha_beta = vp[mnr].dot(Ainv)  # [alpha, beta]
    return vt0 + alpha_beta.dot(np.array([vs, vt]))

get_vtk_name_event(name)

Return the name of a VTK event.

Frequently used events are: - KeyPress, KeyRelease: listen to keyboard events - LeftButtonPress, LeftButtonRelease: listen to mouse clicks - MiddleButtonPress, MiddleButtonRelease - RightButtonPress, RightButtonRelease - MouseMove: listen to mouse pointer changing position - MouseWheelForward, MouseWheelBackward - Enter, Leave: listen to mouse entering or leaving the window - Pick, StartPick, EndPick: listen to object picking - ResetCamera, ResetCameraClippingRange - Error, Warning, Char, Timer

Check the complete list of events here: https://vtk.org/doc/nightly/html/classvtkCommand.html

Source code in vedo/utils.py
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
def get_vtk_name_event(name: str) -> str:
    """
    Return the name of a VTK event.

    Frequently used events are:
    - KeyPress, KeyRelease: listen to keyboard events
    - LeftButtonPress, LeftButtonRelease: listen to mouse clicks
    - MiddleButtonPress, MiddleButtonRelease
    - RightButtonPress, RightButtonRelease
    - MouseMove: listen to mouse pointer changing position
    - MouseWheelForward, MouseWheelBackward
    - Enter, Leave: listen to mouse entering or leaving the window
    - Pick, StartPick, EndPick: listen to object picking
    - ResetCamera, ResetCameraClippingRange
    - Error, Warning, Char, Timer

    Check the complete list of events here:
    https://vtk.org/doc/nightly/html/classvtkCommand.html
    """
    # as vtk names are ugly and difficult to remember:
    ln = name.lower()
    if "click" in ln or "button" in ln:
        event_name = "LeftButtonPress"
        if "right" in ln:
            event_name = "RightButtonPress"
        elif "mid" in ln:
            event_name = "MiddleButtonPress"
        if "release" in ln:
            event_name = event_name.replace("Press", "Release")
    else:
        event_name = name
        if "key" in ln:
            if "release" in ln:
                event_name = "KeyRelease"
            else:
                event_name = "KeyPress"

    if ("mouse" in ln and "mov" in ln) or "over" in ln:
        event_name = "MouseMove"

    words = [
        "pick",
        "timer",
        "reset",
        "enter",
        "leave",
        "char",
        "error",
        "warning",
        "start",
        "end",
        "wheel",
        "clipping",
        "range",
        "camera",
        "render",
        "interaction",
        "modified",
    ]
    for w in words:
        if w in ln:
            event_name = event_name.replace(w, w.capitalize())

    event_name = event_name.replace("REnd ", "Rend")
    event_name = event_name.replace("the ", "")
    event_name = event_name.replace(" of ", "").replace(" ", "")

    if not event_name.endswith("Event"):
        event_name += "Event"

    if vtki.vtkCommand.GetEventIdFromString(event_name) == 0:
        vedo.logger.error(f"'{name}' is not a valid event name.")
        vedo.logger.error("Check the list of events here:")
        vedo.logger.error("https://vtk.org/doc/nightly/html/classvtkCommand.html")
        raise ValueError(f"Invalid VTK event name: {name!r}")

    return event_name

grep(filename, tag, column=None, first_occurrence_only=False)

Greps the line in a file that starts with a specific tag string inside the file.

Source code in vedo/utils.py
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
def grep(filename: str, tag: str, column=None, first_occurrence_only=False) -> list:
    """Greps the line in a file that starts with a specific `tag` string inside the file."""
    import re

    with open(str(filename), "r", encoding="UTF-8") as afile:
        content = []
        for line in afile:
            if re.search(tag, line):
                c = line.split()
                if column is not None:
                    content.append(c[column])
                else:
                    content.append(c)
                if first_occurrence_only:
                    break
    return content

grid_corners(i, nm, size, margin=0, yflip=True)

Compute the 2 corners coordinates of the i-th box in a grid of shape n*m. The top-left square is square number 1.

Parameters:

Name Type Description Default
i int

input index of the desired grid square (to be used in show(..., at=...)).

required
nm list

grid shape as (n,m).

required
size list

total size of the grid along x and y.

required
margin float

keep a small margin between boxes.

0
yflip bool

y-coordinate points downwards

True

Returns:

Type Description
ndarray

Two 2D points representing the bottom-left corner and the top-right corner

ndarray

of the i-nth box in the grid.

Examples:

from vedo.utils import grid_corners
from vedo import Text3D, Rectangle, show
objs=[]
n,m = 5,7
for i in range(1, n*m + 1):
    c1, c2 = grid_corners(i, [n,m], [1,1], 0.01)
    t = Text3D(i, (c1+c2)/2, c='k', s=0.02, justify='center').z(0.01)
    r = Rectangle(c1, c2, c=i)
    objs += [t,r]
show(objs, axes=1).close()

Source code in vedo/utils.py
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
def grid_corners(
    i: int, nm: list, size: list, margin=0, yflip=True
) -> tuple[np.ndarray, np.ndarray]:
    """
    Compute the 2 corners coordinates of the i-th box in a grid of shape n*m.
    The top-left square is square number 1.

    Args:
        i (int):
            input index of the desired grid square (to be used in `show(..., at=...)`).
        nm (list):
            grid shape as (n,m).
        size (list):
            total size of the grid along x and y.
        margin (float):
            keep a small margin between boxes.
        yflip (bool):
            y-coordinate points downwards

    Returns:
        Two 2D points representing the bottom-left corner and the top-right corner
        of the `i`-nth box in the grid.

    Examples:
        ```python
        from vedo.utils import grid_corners
        from vedo import Text3D, Rectangle, show
        objs=[]
        n,m = 5,7
        for i in range(1, n*m + 1):
            c1, c2 = grid_corners(i, [n,m], [1,1], 0.01)
            t = Text3D(i, (c1+c2)/2, c='k', s=0.02, justify='center').z(0.01)
            r = Rectangle(c1, c2, c=i)
            objs += [t,r]
        show(objs, axes=1).close()
        ```
        ![](https://vedo.embl.es/images/feats/grid_corners.png)
    """
    i -= 1
    n, m = nm
    sx, sy = size
    dx, dy = sx / n, sy / m
    nx = i % n
    ny = i // n
    if yflip:
        ny = m - 1 - ny
    c1 = (dx * nx + margin, dy * ny + margin)
    c2 = (dx * (nx + 1) - margin, dy * (ny + 1) - margin)
    return np.array(c1), np.array(c2)

humansort(alist)

Sort in place a given list the way humans expect.

E.g. ['file11', 'file1'] -> ['file1', 'file11']

.. warning:: input list is modified in-place by this function.

Source code in vedo/utils.py
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
def humansort(alist) -> list:
    """
    Sort in place a given list the way humans expect.

    E.g. `['file11', 'file1'] -> ['file1', 'file11']`

    .. warning:: input list is modified in-place by this function.
    """
    import re

    def alphanum_key(s):
        # Turn a string into a list of string and number chunks.
        # e.g. "z23a" -> ["z", 23, "a"]
        def tryint(s):
            if s.isdigit():
                return int(s)
            return s

        return [tryint(c) for c in re.split("([0-9]+)", s)]

    alist.sort(key=alphanum_key)
    return alist  # NB: input list is modified

intersection_ray_triangle(P0, P1, V0, V1, V2)

Fast intersection between a directional ray defined by P0,P1 and triangle V0, V1, V2.

Returns the intersection point or - None if triangle is degenerate, or ray is parallel to triangle plane. - False if no intersection, or ray direction points away from triangle.

Source code in vedo/utils.py
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
def intersection_ray_triangle(P0, P1, V0, V1, V2) -> bool | None | np.ndarray:
    """
    Fast intersection between a directional ray defined by `P0,P1`
    and triangle `V0, V1, V2`.

    Returns the intersection point or
    - `None` if triangle is degenerate, or ray is  parallel to triangle plane.
    - `False` if no intersection, or ray direction points away from triangle.
    """
    # Credits: http://geomalgorithms.com/a06-_intersect-2.html
    # Get triangle edge vectors and plane normal
    # todo : this is slow should check
    # https://vtk.org/doc/nightly/html/classvtkCell.html
    V0 = np.asarray(V0, dtype=float)
    P0 = np.asarray(P0, dtype=float)
    u = V1 - V0
    v = V2 - V0
    n = np.cross(u, v)
    if not np.abs(n).sum():  # triangle is degenerate
        return None  # do not deal with this case

    rd = P1 - P0  # ray direction vector
    w0 = P0 - V0
    a = -np.dot(n, w0)
    b = np.dot(n, rd)
    if not b:  # ray is  parallel to triangle plane
        return None

    # Get intersect point of ray with triangle plane
    r = a / b
    if r < 0.0:  # ray goes away from triangle
        return False  #  => no intersect

    # Gor a segment, also test if (r > 1.0) => no intersect
    I = P0 + r * rd  # intersect point of ray and plane

    # is I inside T?
    uu = np.dot(u, u)
    uv = np.dot(u, v)
    vv = np.dot(v, v)
    w = I - V0
    wu = np.dot(w, u)
    wv = np.dot(w, v)
    D = uv * uv - uu * vv

    # Get and test parametric coords
    s = (uv * wv - vv * wu) / D
    if s < 0.0 or s > 1.0:  # I is outside T
        return False
    t = (uv * wu - uu * wv) / D
    if t < 0.0 or (s + t) > 1.0:  # I is outside T
        return False
    return I  # I is in T

is_integer(n)

Check if input is an integer.

Source code in vedo/utils.py
1898
1899
1900
1901
1902
1903
1904
1905
def is_integer(n) -> bool:
    """Check if input is an integer."""
    try:
        float(n)
    except (ValueError, TypeError):
        return False
    else:
        return float(n).is_integer()

is_number(n)

Check if input is a number

Source code in vedo/utils.py
1908
1909
1910
1911
1912
1913
1914
def is_number(n) -> bool:
    """Check if input is a number"""
    try:
        float(n)
        return True
    except (ValueError, TypeError):
        return False

is_ragged(arr, deep=False)

A ragged or inhomogeneous array in Python is an array with arrays of different lengths as its elements. To check if an array is ragged, we iterate through the elements and check if their lengths are the same.

Examples:

arr = [[1, 2, 3], [[4, 5], [6], 1], [7, 8, 9]]
print(is_ragged(arr, deep=True))  # output: True

Source code in vedo/utils.py
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
def is_ragged(arr, deep=False) -> bool:
    """
    A ragged or inhomogeneous array in Python is an array
    with arrays of different lengths as its elements.
    To check if an array is ragged, we iterate through the elements
    and check if their lengths are the same.

    Examples:
    ```python
    arr = [[1, 2, 3], [[4, 5], [6], 1], [7, 8, 9]]
    print(is_ragged(arr, deep=True))  # output: True
    ```
    """
    n = len(arr)
    if n == 0:
        return False
    if is_sequence(arr[0]):
        length = len(arr[0])
        for i in range(1, n):
            if len(arr[i]) != length or (deep and is_ragged(arr[i])):
                return True
        return False
    return False

is_sequence(arg)

Check if the input is iterable.

Source code in vedo/utils.py
1339
1340
1341
1342
1343
1344
1345
def is_sequence(arg) -> bool:
    """Check if the input is iterable."""
    if hasattr(arg, "strip"):
        return False
    if hasattr(arg, "__iter__"):
        return True
    return False

lin_interpolate(x, rangeX, rangeY)

Interpolate linearly the variable x in rangeX onto the new rangeY. If x is a 3D vector the linear weight is the distance to the two 3D rangeX vectors.

E.g. if x runs in rangeX=[x0,x1] and I want it to run in rangeY=[y0,y1] then

y = lin_interpolate(x, rangeX, rangeY) will interpolate x onto rangeY.

Examples:

Source code in vedo/utils.py
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
def lin_interpolate(x, rangeX, rangeY):
    """
    Interpolate linearly the variable `x` in `rangeX` onto the new `rangeY`.
    If `x` is a 3D vector the linear weight is the distance to the two 3D `rangeX` vectors.

    E.g. if `x` runs in `rangeX=[x0,x1]` and I want it to run in `rangeY=[y0,y1]` then

    `y = lin_interpolate(x, rangeX, rangeY)` will interpolate `x` onto `rangeY`.

    Examples:
        - [lin_interpolate.py](https://github.com/marcomusy/vedo/tree/master/examples/basic/lin_interpolate.py)

            ![](https://vedo.embl.es/images/basic/linInterpolate.png)
    """
    if is_sequence(x):
        x = np.asarray(x)
        x0, x1 = np.asarray(rangeX)
        y0, y1 = np.asarray(rangeY)
        dx = x1 - x0
        dxn = np.linalg.norm(dx)
        if not dxn:
            return y0
        s = np.linalg.norm(x - x0) / dxn
        t = np.linalg.norm(x - x1) / dxn
        st = s + t
        out = y0 * (t / st) + y1 * (s / st)

    else:  # faster
        x0 = rangeX[0]
        dx = rangeX[1] - x0
        if not dx:
            return rangeY[0]
        s = (x - x0) / dx
        out = rangeY[0] * (1 - s) + rangeY[1] * s
    return out

line_line_distance(p1, p2, q1, q2)

Compute the distance of a line to a line (not the segment) defined by p1 and p2 and q1 and q2.

Returns the distance, the closest point on line 1, the closest point on line 2. Their parametric coords (-inf <= t0, t1 <= inf) are also returned.

Source code in vedo/utils.py
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
def line_line_distance(
    p1, p2, q1, q2
) -> tuple[float, np.ndarray, np.ndarray, float, float]:
    """
    Compute the distance of a line to a line (not the segment)
    defined by `p1` and `p2` and `q1` and `q2`.

    Returns the distance,
    the closest point on line 1, the closest point on line 2.
    Their parametric coords (-inf <= t0, t1 <= inf) are also returned.
    """
    closest_pt1: MutableSequence[float] = [0, 0, 0]
    closest_pt2: MutableSequence[float] = [0, 0, 0]
    t1, t2 = 0.0, 0.0
    d = vtki.vtkLine.DistanceBetweenLines(
        p1, p2, q1, q2, closest_pt1, closest_pt2, t1, t2
    )
    return np.sqrt(d), closest_pt1, closest_pt2, t1, t2

mag(v)

Get the magnitude of a vector or array of vectors.

Source code in vedo/utils.py
1882
1883
1884
1885
1886
1887
def mag(v):
    """Get the magnitude of a vector or array of vectors."""
    v = np.asarray(v)
    if v.ndim == 1:
        return np.linalg.norm(v)
    return np.linalg.norm(v, axis=1)

mag2(v)

Get the squared magnitude of a vector or array of vectors.

Source code in vedo/utils.py
1890
1891
1892
1893
1894
1895
def mag2(v) -> np.ndarray:
    """Get the squared magnitude of a vector or array of vectors."""
    v = np.asarray(v)
    if v.ndim == 1:
        return np.square(v).sum()
    return np.square(v).sum(axis=1)

make3d(pts)

Make an array which might be 2D to 3D.

Array can also be in the form [allx, ally, allz].

Source code in vedo/utils.py
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
def make3d(pts) -> np.ndarray:
    """
    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

make_bands(inputlist, n)

Group values of a list into bands of equal value, where n is the number of bands, a positive integer > 2.

Returns a binned list of the same length as the input.

Source code in vedo/utils.py
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
def make_bands(inputlist, n):
    """
    Group values of a list into bands of equal value, where
    `n` is the number of bands, a positive integer > 2.

    Returns a binned list of the same length as the input.
    """
    if n < 2:
        return inputlist
    vmin = np.min(inputlist)
    vmax = np.max(inputlist)
    bb = np.linspace(vmin, vmax, n, endpoint=0)
    dr = bb[1] - bb[0]
    bb += dr / 2
    tol = dr / 2 * 1.001
    newlist = []
    for s in inputlist:
        for b in bb:
            if abs(s - b) < tol:
                newlist.append(b)
                break
    return np.array(newlist)

make_ticks(x0, x1, n=None, labels=None, digits=None, logscale=False, useformat='')

Generate numeric labels for the [x0, x1] range.

The format specifier could be expressed in the format

:[[fill]align][sign][#][0][width][,][.precision][type]

where, the options are:

fill        =  any character
align       =  < | > | = | ^
sign        =  + | - | " "
width       =  integer
precision   =  integer
type        =  b | c | d | e | E | f | F | g | G | n | o | s | x | X | %

E.g.: useformat=":.2f"

Source code in vedo/utils.py
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
def make_ticks(
    x0: float,
    x1: float,
    n=None,
    labels=None,
    digits=None,
    logscale=False,
    useformat="",
) -> tuple[np.ndarray, list[str]]:
    """
    Generate numeric labels for the `[x0, x1]` range.

    The format specifier could be expressed in the format:
        `:[[fill]align][sign][#][0][width][,][.precision][type]`

    where, the options are:
    ```
    fill        =  any character
    align       =  < | > | = | ^
    sign        =  + | - | " "
    width       =  integer
    precision   =  integer
    type        =  b | c | d | e | E | f | F | g | G | n | o | s | x | X | %
    ```

    E.g.: useformat=":.2f"
    """
    # Copyright M. Musy, 2021, license: MIT.
    #
    # useformat eg: ":.2f", check out:
    # https://mkaz.blog/code/python-string-format-cookbook/
    # https://www.programiz.com/python-programming/methods/built-in/format

    if x1 <= x0:
        # vedo.printc("Error in make_ticks(): x0 >= x1", x0,x1, c='r')
        return np.array([0.0, 1.0]), ["", ""]

    ticks_str, ticks_float = [], []
    baseline = (1, 2, 5, 10, 20, 50)

    if logscale:
        if x0 <= 0 or x1 <= 0:
            vedo.logger.error("make_ticks: zero or negative range with log scale.")
            raise RuntimeError("make_ticks: zero or negative range with log scale.")
        if n is None:
            n = int(abs(np.log10(x1) - np.log10(x0))) + 1
        x0, x1 = np.log10([x0, x1])

    if n is None:
        n = 5

    if labels is not None:
        # user is passing custom labels

        ticks_float.append(0)
        ticks_str.append("")
        for tp, ts in labels:
            if np.isclose(tp, x1):
                continue
            ticks_str.append(str(ts))
            tickn = lin_interpolate(tp, [x0, x1], [0, 1])
            ticks_float.append(tickn)

    else:
        # ..here comes one of the shortest and most painful pieces of code:
        # automatically choose the best natural axis subdivision based on multiples of 1,2,5
        dstep = (x1 - x0) / n  # desired step size, begin of the nightmare

        basestep = pow(10, np.floor(np.log10(dstep)))
        steps = np.array([basestep * i for i in baseline])
        idx = (np.abs(steps - dstep)).argmin()
        s = steps[idx]  # chosen step size

        low_bound, up_bound = 0, 0
        if x0 < 0:
            low_bound = -pow(10, np.ceil(np.log10(-x0)))
        if x1 > 0:
            up_bound = pow(10, np.ceil(np.log10(x1)))

        if low_bound < 0:
            if up_bound < 0:
                negaxis = np.arange(low_bound, int(up_bound / s) * s)
            else:
                if -low_bound / s > 1.0e06:
                    return np.array([0.0, 1.0]), ["", ""]
                negaxis = np.arange(low_bound, 0, s)
        else:
            negaxis = np.array([])

        if up_bound > 0:
            if low_bound > 0:
                posaxis = np.arange(int(low_bound / s) * s, up_bound, s)
            else:
                if up_bound / s > 1.0e06:
                    return np.array([0.0, 1.0]), ["", ""]
                posaxis = np.arange(0, up_bound, s)
        else:
            posaxis = np.array([])

        fulaxis = np.unique(np.clip(np.concatenate([negaxis, posaxis]), x0, x1))
        # end of the nightmare

        if useformat and not logscale:
            sf = "{" + f"{useformat}" + "}"
            sas = " ".join(sf.format(x) for x in fulaxis)
        elif digits is None:
            sas = " ".join(f"{x:g}" for x in fulaxis)
        else:
            sas = precision(fulaxis, digits, vrange=(x0, x1))
            sas = (
                sas.replace("[", "").replace("]", "").replace(")", "").replace(",", "")
            )

        sas2 = []
        for tok in sas.split():
            if tok.endswith("."):
                tok = tok[:-1]
            if tok == "-0":
                tok = "0"
            if digits is not None and "e" in tok:
                tok += " "  # add space to terminate modifiers
            sas2.append(tok)

        for ts, tp in zip(sas2, fulaxis):
            if tp == x1:
                continue
            tickn = lin_interpolate(tp, [x0, x1], [0, 1])
            ticks_float.append(tickn)
            if logscale:
                val = np.power(10, tp)
                if useformat:
                    sf = "{" + f"{useformat}" + "}"
                    ticks_str.append(sf.format(val))
                else:
                    if val >= 10:
                        val = int(val + 0.5)
                    else:
                        val = round_to_digit(val, 2)
                    ticks_str.append(str(val))
            else:
                ticks_str.append(ts)

    ticks_str.append("")
    ticks_float.append(1)
    return np.array(ticks_float), ticks_str

numpy2vtk(arr, dtype=None, deep=True, name='', as_image=False, dims=None)

Convert a numpy array into a vtkDataArray or vtkImageArray.

Use dtype='id' for vtkIdTypeArray objects. Use as_image=True and specify the dimensions with the dims keyword to generate a vtkImageArray object suitable for use with the volume constructor directly.

Source code in vedo/utils.py
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
def numpy2vtk(arr, dtype=None, deep=True, name="", as_image=False, dims=None):
    """
    Convert a numpy array into a `vtkDataArray` or `vtkImageArray`.

    Use `dtype='id'` for `vtkIdTypeArray` objects.
    Use `as_image=True` and specify the dimensions with the `dims` keyword to generate
    a `vtkImageArray` object suitable for use with the volume constructor directly.
    """
    # https://github.com/Kitware/VTK/blob/master/Wrapping/Python/vtkmodules/util/numpy_support.py
    if arr is None:
        return None

    if as_image and dims is None:
        vedo.logger.error("must set dimensions (dims keyword) when requesting an image")
        raise RuntimeError()

    arr = np.ascontiguousarray(arr)

    if dtype == "id":
        if vtki.vtkIdTypeArray().GetDataTypeSize() != 4:
            ast = np.int64
        else:
            ast = np.int32
        varr = numpy_to_vtkIdTypeArray(arr.astype(ast), 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)

    if as_image:
        # Assuming this is meant to be used with a volume
        varr.SetName("input_scalars")

        img = vtki.vtkImageData()
        dims3 = tuple(int(d) for d in dims[:3])
        expected = int(np.prod(dims3))
        n_tuples = varr.GetNumberOfTuples()
        if n_tuples != expected:
            raise ValueError(
                f"numpy2vtk(as_image=True): scalar tuple count ({n_tuples}) "
                f"does not match image dimensions product ({expected})"
            )
        img.SetDimensions(*dims3)
        img.GetPointData().AddArray(varr)
        img.GetPointData().SetActiveScalars(varr.GetName())

        return img

    return varr

oriented_camera(center, up_vector, backoff_vector, backoff)

Generate a vtkCamera pointed at a specific location, oriented with a given up direction, set to a backoff.

Source code in vedo/utils.py
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
def oriented_camera(center, up_vector, backoff_vector, backoff) -> vtki.vtkCamera:
    """
    Generate a `vtkCamera` pointed at a specific location,
    oriented with a given up direction, set to a backoff.
    """
    vup = np.array(up_vector)
    vup = vup / np.linalg.norm(vup)
    pt_backoff = center - backoff * np.array(backoff_vector)
    camera = vtki.vtkCamera()
    camera.SetFocalPoint(center[0], center[1], center[2])
    camera.SetViewUp(vup[0], vup[1], vup[2])
    camera.SetPosition(pt_backoff[0], pt_backoff[1], pt_backoff[2])
    return camera

otsu_threshold(image)

Compute Otsu optimal threshold. Assumes image is a NumPy array (grayscale).

Source code in vedo/utils.py
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
def otsu_threshold(image):
    """
    Compute Otsu optimal threshold. Assumes image is a NumPy array (grayscale).
    """
    image = image.ravel()

    # Compute histogram
    min_val, max_val = image.min(), image.max()
    hist, bin_edges = np.histogram(image, bins=256, range=(min_val, max_val))
    hist = hist.astype(np.float64)
    total = hist.sum()

    # Probabilities and bin centers
    prob = hist / total
    bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2

    # Cumulative sums
    omega = np.cumsum(prob)
    mu = np.cumsum(prob * bin_centers)
    mu_total = mu[-1]

    numerator = (mu_total * omega - mu) ** 2
    denominator = omega * (1 - omega)

    with np.errstate(divide="ignore", invalid="ignore"):
        sigma_b_squared = np.divide(numerator, denominator, where=denominator > 0)

    idx = np.argmax(sigma_b_squared)
    return bin_centers[idx]

pack_spheres(bounds, radius)

Packing spheres into a bounding box. Returns a numpy array of sphere centers.

Source code in vedo/utils.py
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
def pack_spheres(bounds, radius) -> np.ndarray:
    """
    Packing spheres into a bounding box.
    Returns a numpy array of sphere centers.
    """
    h = 0.8164965 / 2
    d = 0.8660254
    a = 0.288675135

    if is_sequence(bounds):
        x0, x1, y0, y1, z0, z1 = bounds
    else:
        x0, x1, y0, y1, z0, z1 = bounds.bounds()

    x = np.arange(x0, x1, radius)
    nul = np.zeros_like(x)
    nz = int((z1 - z0) / radius / h / 2 + 1.5)
    ny = int((y1 - y0) / radius / d + 1.5)

    pts = []
    for iz in range(nz):
        z = z0 + nul + iz * h * radius
        dx, dy, dz = [radius * 0.5, radius * a, iz * h * radius]
        for iy in range(ny):
            y = y0 + nul + iy * d * radius
            if iy % 2:
                xs = x
            else:
                xs = x + radius * 0.5
            if iz % 2:
                p = np.c_[xs, y, z] + [dx, dy, dz]
            else:
                p = np.c_[xs, y, z] + [0, 0, dz]
            pts += p.tolist()
    return np.array(pts)

point_in_triangle(p, p1, p2, p3)

Return True if a point is inside (or above/below) a triangle defined by 3 points in space.

Source code in vedo/utils.py
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
def point_in_triangle(p, p1, p2, p3) -> bool | None:
    """
    Return True if a point is inside (or above/below)
    a triangle defined by 3 points in space.
    """
    p1 = np.array(p1)
    p2 = np.array(p2)
    p3 = np.array(p3)
    u = p2 - p1
    v = p3 - p1
    n = np.cross(u, v)
    w = p - p1
    ln = np.dot(n, n)
    if not ln:
        return None  # degenerate triangle
    gamma = (np.dot(np.cross(u, w), n)) / ln
    if 0 < gamma < 1:
        beta = (np.dot(np.cross(w, v), n)) / ln
        if 0 < beta < 1:
            alpha = 1 - gamma - beta
            if 0 < alpha < 1:
                return True
    return False

point_line_distance(p, p1, p2)

Compute the distance of a point to a line (not the segment) defined by p1 and p2.

Source code in vedo/utils.py
1636
1637
1638
1639
1640
1641
def point_line_distance(p, p1, p2) -> float:
    """
    Compute the distance of a point to a line (not the segment)
    defined by `p1` and `p2`.
    """
    return np.sqrt(vtki.vtkLine.DistanceToLine(p, p1, p2))

precision(x, p, vrange=None, delimiter='e')

Returns a string representation of x formatted to precision p.

Set vrange to the range in which x exists (to snap x to '0' if below precision).

Source code in vedo/utils.py
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
def precision(x, p: int, vrange=None, delimiter="e") -> str:
    """
    Returns a string representation of `x` formatted to precision `p`.

    Set `vrange` to the range in which x exists (to snap x to '0' if below precision).
    """
    # Based on the webkit javascript implementation
    # `from here <https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp>`_,
    # and implemented by `randlet <https://github.com/randlet/to-precision>`_.
    # Modified for vedo by M.Musy 2020

    if isinstance(x, str):  # do nothing
        return x

    if is_sequence(x):
        out = "("
        nn = len(x) - 1
        for i, ix in enumerate(x):
            try:
                if np.isnan(ix):
                    return "NaN"
            except Exception:
                # cannot handle list of list
                continue

            out += precision(ix, p)
            if i < nn:
                out += ", "
        return out + ")"  ############ <--

    try:
        if np.isnan(x):
            return "NaN"
    except TypeError:
        return "NaN"

    x = float(x)

    if x == 0.0 or (vrange is not None and abs(x) < vrange / pow(10, p)):
        return "0"

    out = []
    if x < 0:
        out.append("-")
        x = -x

    e = int(np.log10(x))
    # tens = np.power(10, e - p + 1)
    tens = 10 ** (e - p + 1)
    n = np.floor(x / tens)

    # if n < np.power(10, p - 1):
    if n < 10 ** (p - 1):
        e = e - 1
        # tens = np.power(10, e - p + 1)
        tens = 10 ** (e - p + 1)
        n = np.floor(x / tens)

    if abs((n + 1.0) * tens - x) <= abs(n * tens - x):
        n = n + 1

    # if n >= np.power(10, p):
    if n >= 10**p:
        n = n / 10.0
        e = e + 1

    m = "%.*g" % (p, n)
    if e < -2 or e >= p:
        out.append(m[0])
        if p > 1:
            out.append(".")
            out.extend(m[1:p])
        out.append(delimiter)
        if e > 0:
            out.append("+")
        out.append(str(e))
    elif e == (p - 1):
        out.append(m)
    elif e >= 0:
        out.append(m[: e + 1])
        if e + 1 < len(m):
            out.append(".")
            out.extend(m[e + 1 :])
    else:
        out.append("0.")
        out.extend(["0"] * -(e + 1))
        out.append(m)
    return "".join(out)

print_histogram(data, bins=10, height=10, logscale=False, minbin=0, vrange=(), horizontal=True, char='▉', c=None, bold=True, title='histogram', spacer='')

Ascii histogram printing.

Input can be a vedo.Volume or vedo.Mesh. Returns the raw data before binning (useful when passing vtk objects).

Parameters:

Name Type Description Default
bins int

number of histogram bins

10
height int

height of the histogram in character units

10
logscale bool

use logscale for frequencies

False
minbin int

ignore bins before minbin

0
vrange tuple

range of values to consider, e.g. (0, 1) or (None, 1) or (0, None). If empty, all values are considered.

()
horizontal bool

show histogram horizontally

True
char str

character to be used

'▉'
bold bool

use boldface

True
title str

histogram title

'histogram'
spacer str

horizontal spacer

''

Examples:

from vedo import print_histogram
import numpy as np
d = np.random.normal(size=1000)
data = print_histogram(d, c='b', logscale=True, title='my scalars')
data = print_histogram(d, c='o')
print(np.mean(data)) # data here is same as d

Source code in vedo/utils.py
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
def print_histogram(
    data,
    bins=10,
    height=10,
    logscale=False,
    minbin=0,
    vrange=(),
    horizontal=True,
    char="\U00002589",
    c=None,
    bold=True,
    title="histogram",
    spacer="",
) -> np.ndarray:
    """
    Ascii histogram printing.

    Input can be a `vedo.Volume` or `vedo.Mesh`.
    Returns the raw data before binning (useful when passing vtk objects).

    Args:
        bins (int):
            number of histogram bins
        height (int):
            height of the histogram in character units
        logscale (bool):
            use logscale for frequencies
        minbin (int):
            ignore bins before minbin
        vrange (tuple):
            range of values to consider, e.g. (0, 1) or (None, 1) or (0, None).
            If empty, all values are considered.
        horizontal (bool):
            show histogram horizontally
        char (str):
            character to be used
        bold (bool):
            use boldface
        title (str):
            histogram title
        spacer (str):
            horizontal spacer

    Examples:
        ```python
        from vedo import print_histogram
        import numpy as np
        d = np.random.normal(size=1000)
        data = print_histogram(d, c='b', logscale=True, title='my scalars')
        data = print_histogram(d, c='o')
        print(np.mean(data)) # data here is same as d
        ```
        ![](https://vedo.embl.es/images/feats/print_histogram.png)
    """
    # credits: http://pyinsci.blogspot.com/2009/10/ascii-histograms.html
    # adapted for vedo by M.Musy, 2019

    if not horizontal:  # better aspect ratio
        bins *= 2

    try:
        data = vtk2numpy(data.dataset.GetPointData().GetScalars())
    except AttributeError:
        # already an array
        data = np.asarray(data)

    # remove out of range values
    if len(vrange):
        if vrange[0] is None:
            data = data[data <= vrange[1]]
        elif vrange[1] is None:
            data = data[data >= vrange[0]]
        else:
            data = data[(data >= vrange[0]) & (data <= vrange[1])]

    try:
        h = np.histogram(data, bins=bins)
    except TypeError as e:
        vedo.logger.error(f"cannot compute histogram: {e}")
        return np.array([])

    if minbin:
        hi = h[0][minbin:-1]
    else:
        hi = h[0]

    if char == "\U00002589" and horizontal:
        char = "\U00002586"

    title = title.ljust(14) + ":"
    entrs = " entries=" + str(len(data))
    if logscale:
        h0 = np.log10(hi + 1)
        maxh0 = int(max(h0) * 100) / 100
        title = title + entrs + " (logscale)"
    else:
        h0 = hi
        maxh0 = max(h0)
        title = title + entrs

    def _v():
        his = ""
        if title:
            his += title + "\n"
        bars = h0 / maxh0 * height
        for l in reversed(range(1, height + 1)):
            line = ""
            if l == height:
                line = "%s " % maxh0
            else:
                line = "   |" + " " * (len(str(maxh0)) - 3)
            for c in bars:
                if c >= np.ceil(l):
                    line += char
                else:
                    line += " "
            line += "\n"
            his += line
        his += "%.2f" % h[1][0] + "." * (bins) + "%.2f" % h[1][-1] + "\n"
        return his

    def _h():
        his = ""
        if title:
            his += title + "\n"
        xl = ["%.2f" % n for n in h[1]]
        lxl = [len(l) for l in xl]
        bars = h0 / maxh0 * height
        his += spacer + " " * int(max(bars) + 2 + max(lxl)) + "%s\n" % maxh0
        for i, c in enumerate(bars):
            line = xl[i] + " " * int(max(lxl) - lxl[i]) + "| " + char * int(c) + "\n"
            his += spacer + line
        return his

    if horizontal:
        height *= 2
        vedo.printc(_h(), c=c, bold=bold)
    else:
        vedo.printc(_v(), c=c, bold=bold)
    return data

print_inheritance_tree(C)

Prints the inheritance tree of class C.

Source code in vedo/utils.py
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
def print_inheritance_tree(C) -> None:
    """Prints the inheritance tree of class C."""

    # Adapted from: https://stackoverflow.com/questions/26568976/
    def class_tree(cls):
        subc = [class_tree(sub_class) for sub_class in cls.__subclasses__()]
        return {cls.__name__: subc}

    def print_tree(tree, indent=8, current_ind=0):
        for k, v in tree.items():
            if current_ind:
                before_dashes = current_ind - indent
                m = " " * before_dashes + "└" + "─" * (indent - 1) + " " + k
                vedo.printc(m)
            else:
                vedo.printc(k)
            for sub_tree in v:
                print_tree(sub_tree, indent=indent, current_ind=current_ind + indent)

    if str(C.__class__) != "<class 'type'>":
        C = C.__class__
    ct = class_tree(C)
    print_tree(ct)

print_table(*columns, headers=None, c='g')

Print lists as tables.

Examples:

from vedo.utils import print_table
list1 = ["A", "B", "C"]
list2 = [142, 220, 330]
list3 = [True, False, True]
headers = ["First Column", "Second Column", "Third Column"]
print_table(list1, list2, list3, headers=headers)

Source code in vedo/utils.py
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
def print_table(*columns, headers=None, c="g") -> None:
    """
    Print lists as tables.

    Examples:
        ```python
        from vedo.utils import print_table
        list1 = ["A", "B", "C"]
        list2 = [142, 220, 330]
        list3 = [True, False, True]
        headers = ["First Column", "Second Column", "Third Column"]
        print_table(list1, list2, list3, headers=headers)
        ```

        ![](https://vedo.embl.es/images/feats/)
    """
    # If headers is not provided, use default header names
    corner = "─"
    if headers is None:
        headers = [f"Column {i}" for i in range(1, len(columns) + 1)]
    if len(headers) != len(columns):
        raise ValueError(
            f"print_table(headers=...) expected {len(columns)} headers, got {len(headers)}"
        )

    # Find the maximum length of the elements in each column and header
    max_lens = [max(len(str(x)) for x in column) for column in columns]
    max_len_headers = [
        max(len(str(header)), max_len) for header, max_len in zip(headers, max_lens)
    ]

    # Construct the table header
    header = (
        "│ "
        + " │ ".join(
            header.ljust(max_len) for header, max_len in zip(headers, max_len_headers)
        )
        + " │"
    )

    # Construct the line separator
    line1 = "┌" + corner.join("─" * (max_len + 2) for max_len in max_len_headers) + "┐"
    line2 = "└" + corner.join("─" * (max_len + 2) for max_len in max_len_headers) + "┘"

    # Print the table header
    vedo.printc(line1, c=c)
    vedo.printc(header, c=c)
    vedo.printc(line2, c=c)

    # Print the data rows
    for row in zip(*columns):
        row = (
            "│ "
            + " │ ".join(
                str(col).ljust(max_len) for col, max_len in zip(row, max_len_headers)
            )
            + " │"
        )
        vedo.printc(row, bold=False, c=c)

    # Print the line separator again to close the table
    vedo.printc(line2, c=c)

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.

Parameters:

Name Type Description Default
iterable iterable or int

an iterable object, or an integer N (equivalent to range(N))

required
c str

color in hex format

None
title str

title text

''
eta bool

estimate time of arrival

True
delay float

minimum time before printing anything, if negative use the default value set in vedo.settings.progressbar_delay

-1
width int

width of the progress bar

25

Examples:

import time
for i in progressbar(range(100), c='r'):
    time.sleep(0.1)

Source code in vedo/utils.py
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
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`.

    Args:
        iterable (iterable or int):
            an iterable object, or an integer N (equivalent to `range(N)`)
        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

    Examples:
        ```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

round_to_digit(x, p)

Round a real number to the specified number of significant digits.

Source code in vedo/utils.py
1917
1918
1919
1920
1921
1922
1923
1924
def round_to_digit(x, p) -> float:
    """Round a real number to the specified number of significant digits."""
    if not x:
        return 0
    r = np.round(x, p - int(np.floor(np.log10(abs(x)))) - 1)
    if int(r) == r:
        return int(r)
    return r

segment_segment_distance(p1, p2, q1, q2)

Compute the distance of a segment to a segment defined by p1 and p2 and q1 and q2.

Returns the distance, the closest point on line 1, the closest point on line 2. Their parametric coords (-inf <= t0, t1 <= inf) are also returned.

Source code in vedo/utils.py
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
def segment_segment_distance(p1, p2, q1, q2):
    """
    Compute the distance of a segment to a segment
    defined by `p1` and `p2` and `q1` and `q2`.

    Returns the distance,
    the closest point on line 1, the closest point on line 2.
    Their parametric coords (-inf <= t0, t1 <= inf) are also returned.
    """
    closest_pt1 = [0, 0, 0]
    closest_pt2 = [0, 0, 0]
    t1, t2 = 0.0, 0.0
    d = vtki.vtkLine.DistanceBetweenLineSegments(
        p1, p2, q1, q2, closest_pt1, closest_pt2, t1, t2
    )
    return np.sqrt(d), closest_pt1, closest_pt2, t1, t2

sort_by_column(arr, nth, invert=False)

Sort a numpy array by its n-th column.

Source code in vedo/utils.py
1411
1412
1413
1414
1415
1416
1417
def sort_by_column(arr, nth, invert=False) -> np.ndarray:
    """Sort a numpy array by its `n-th` column."""
    arr = np.asarray(arr)
    arr = arr[arr[:, nth].argsort()]
    if invert:
        return np.flip(arr, axis=0)
    return arr

string_match(pattern, text)

Check if the text matches the provided pattern with wildcards.

Examples:

string_match("Elephant?", "Elephant2") # True string_match("Elephant", "Elephant2") # False string_match("Elephnt", "Elephao_nt25") # True string_match("Eleph[aeiou]nt", "Elephant") # True string_match("Eleph[aeiou]nt", "Elephynt") # False

Source code in vedo/utils.py
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
def string_match(pattern: str, text: str) -> bool:
    """
    Check if the text matches the provided pattern with wildcards.

    Examples:
        string_match("Elephant?", "Elephant2")      # True
        string_match("Elephant",  "Elephant2")      # False
        string_match("Eleph*nt*", "Elephao_nt25")   # True
        string_match("Eleph[aeiou]nt", "Elephant")  # True
        string_match("Eleph[aeiou]nt", "Elephynt")  # False
    """
    # Characters we DON'T want to escape: *, ?, [, ]
    # Step 1: Temporarily replace wildcards with placeholders
    pattern = pattern.replace("*", "__STAR__").replace("?", "__QMARK__")

    # Step 2: Escape everything else
    pattern = re.escape(pattern)

    # Step 3: Restore wildcards (and allow [] to be unescaped)
    pattern = pattern.replace("__STAR__", ".*").replace("__QMARK__", ".")
    pattern = pattern.replace(r"\[", "[").replace(r"\]", "]")

    # Step 4: Anchor for full match
    pattern = "^" + pattern + "$"
    return bool(re.match(pattern, text))

triangle_solver(**input_dict)

Solve a triangle from any 3 known elements. (Note that there might be more than one solution or none). Angles are in radians.

Examples:

print(triangle_solver(a=3, b=4, c=5))
print(triangle_solver(a=3, ac=0.9273, ab=1.5716))
print(triangle_solver(a=3, b=4, ab=1.5716))
print(triangle_solver(b=4, bc=.64, ab=1.5716))
print(triangle_solver(c=5, ac=.9273, bc=0.6435))
print(triangle_solver(a=3, c=5, bc=0.6435))
print(triangle_solver(b=4, c=5, ac=0.927))

Source code in vedo/utils.py
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
def triangle_solver(**input_dict):
    """
    Solve a triangle from any 3 known elements.
    (Note that there might be more than one solution or none).
    Angles are in radians.

    Examples:
    ```python
    print(triangle_solver(a=3, b=4, c=5))
    print(triangle_solver(a=3, ac=0.9273, ab=1.5716))
    print(triangle_solver(a=3, b=4, ab=1.5716))
    print(triangle_solver(b=4, bc=.64, ab=1.5716))
    print(triangle_solver(c=5, ac=.9273, bc=0.6435))
    print(triangle_solver(a=3, c=5, bc=0.6435))
    print(triangle_solver(b=4, c=5, ac=0.927))
    ```
    """
    a = input_dict.get("a")
    b = input_dict.get("b")
    c = input_dict.get("c")
    ab = input_dict.get("ab")
    bc = input_dict.get("bc")
    ac = input_dict.get("ac")

    if ab is not None and bc is not None:
        ac = np.pi - bc - ab
    elif bc is not None and ac is not None:
        ab = np.pi - bc - ac
    elif ab is not None and ac is not None:
        bc = np.pi - ab - ac

    if a is not None and b is not None and c is not None:
        ab = np.arccos((a**2 + b**2 - c**2) / (2 * a * b))
        sinab = np.sin(ab)
        ac = np.arcsin(a / c * sinab)
        bc = np.arcsin(b / c * sinab)

    elif a is not None and b is not None and ab is not None:
        c = np.sqrt(a**2 + b**2 - 2 * a * b * np.cos(ab))
        sinab = np.sin(ab)
        ac = np.arcsin(a / c * sinab)
        bc = np.arcsin(b / c * sinab)

    elif a is not None and ac is not None and ab is not None:
        h = a * np.sin(ac)
        b = h / np.sin(bc)
        c = b * np.cos(bc) + a * np.cos(ac)

    elif b is not None and bc is not None and ab is not None:
        h = b * np.sin(bc)
        a = h / np.sin(ac)
        c = np.sqrt(a * a + b * b)

    elif c is not None and ac is not None and bc is not None:
        h = c * np.sin(bc)
        b1 = c * np.cos(bc)
        b2 = h / np.tan(ab)
        b = b1 + b2
        a = np.sqrt(b2 * b2 + h * h)

    elif a is not None and c is not None and bc is not None:
        # double solution
        h = c * np.sin(bc)
        k = np.sqrt(a * a - h * h)
        omega = np.arcsin(k / a)
        cosbc = np.cos(bc)
        b = c * cosbc - k
        phi = np.pi / 2 - bc - omega
        ac = phi
        ab = np.pi - ac - bc
        if k:
            b2 = c * cosbc + k
            ac2 = phi + 2 * omega
            ab2 = np.pi - ac2 - bc
            return [
                {"a": a, "b": b, "c": c, "ab": ab, "bc": bc, "ac": ac},
                {"a": a, "b": b2, "c": c, "ab": ab2, "bc": bc, "ac": ac2},
            ]

    elif b is not None and c is not None and ac is not None:
        # double solution
        h = c * np.sin(ac)
        k = np.sqrt(b * b - h * h)
        omega = np.arcsin(k / b)
        cosac = np.cos(ac)
        a = c * cosac - k
        phi = np.pi / 2 - ac - omega
        bc = phi
        ab = np.pi - bc - ac
        if k:
            a2 = c * cosac + k
            bc2 = phi + 2 * omega
            ab2 = np.pi - ac - bc2
            return [
                {"a": a, "b": b, "c": c, "ab": ab, "bc": bc, "ac": ac},
                {"a": a2, "b": b, "c": c, "ab": ab2, "bc": bc2, "ac": ac},
            ]

    else:
        vedo.logger.error(f"Case {input_dict} is not supported.")
        return []

    return [{"a": a, "b": b, "c": c, "ab": ab, "bc": bc, "ac": ac}]

vector(x, y=None, z=0.0, dtype=np.float64)

Return a 3D numpy array representing a vector.

If y is None, assume input is already in the form [x,y,z].

Source code in vedo/utils.py
1863
1864
1865
1866
1867
1868
1869
1870
1871
def vector(x, y=None, z=0.0, dtype=np.float64) -> np.ndarray:
    """
    Return a 3D numpy array representing a vector.

    If `y` is `None`, assume input is already in the form `[x,y,z]`.
    """
    if y is None:  # assume x is already [x,y,z]
        return np.asarray(x, dtype=dtype)
    return np.array([x, y, z], dtype=dtype)

versor(x, y=None, z=0.0, dtype=np.float64)

Return the unit vector. Input can be a list of vectors.

Source code in vedo/utils.py
1874
1875
1876
1877
1878
1879
def versor(x, y=None, z=0.0, dtype=np.float64) -> np.ndarray:
    """Return the unit vector. Input can be a list of vectors."""
    v = vector(x, y, z, dtype)
    if isinstance(v[0], np.ndarray):
        return np.divide(v, mag(v)[:, None])
    return v / mag(v)

vtk2numpy(varr)

Convert a vtkDataArray, vtkIdList or vtTransform into a numpy array.

Source code in vedo/utils.py
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
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
        M = [[varr.GetElement(i, j) for j in range(4)] for i in range(4)]
        return np.array(M)
    return vtk_to_numpy(varr)

vtkCameraToK3D(vtkcam)

Convert a vtkCamera object into a 9-element list to be used by the K3D backend.

Output format is

[posx,posy,posz, targetx,targety,targetz, upx,upy,upz].

Source code in vedo/utils.py
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
def vtkCameraToK3D(vtkcam) -> np.ndarray:
    """
    Convert a `vtkCamera` object into a 9-element list to be used by the K3D backend.

    Output format is:
        `[posx,posy,posz, targetx,targety,targetz, upx,upy,upz]`.
    """
    cpos = np.array(vtkcam.GetPosition())
    kam = [cpos.tolist()]
    kam.append(vtkcam.GetFocalPoint())
    kam.append(vtkcam.GetViewUp())
    return np.array(kam).ravel()

vtk_version_at_least(major, minor=0, build=0)

Check the installed VTK version.

Return True if the requested VTK version is greater or equal to the actual VTK version.

Parameters:

Name Type Description Default
major int

Major version.

required
minor int

Minor version.

0
build int

Build version.

0
Source code in vedo/utils.py
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
def vtk_version_at_least(major, minor=0, build=0) -> bool:
    """
    Check the installed VTK version.

    Return `True` if the requested VTK version is greater or equal to the actual VTK version.

    Args:
        major (int):
            Major version.
        minor (int):
            Minor version.
        build (int):
            Build version.
    """
    needed_version = 10000000000 * int(major) + 100000000 * int(minor) + int(build)
    try:
        vtk_version_number = vtki.VTK_VERSION_NUMBER
    except AttributeError:  # as error:
        ver = vtki.vtkVersion()
        vtk_version_number = (
            10000000000 * ver.GetVTKMajorVersion()
            + 100000000 * ver.GetVTKMinorVersion()
            + ver.GetVTKBuildVersion()
        )
    return vtk_version_number >= needed_version