Skip to content

vedo.assembly

assembly

Assembly

Bases: CommonVisual, Actor3DHelper

Group many objects and treat them as a single new object.

Source code in vedo/assembly.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
class Assembly(CommonVisual, Actor3DHelper):
    """
    Group many objects and treat them as a single new object.
    """

    def __init__(self, *meshs):
        """
        Group many objects and treat them as a single new object,
        keeping track of internal transformations.

        A file can be loaded by passing its name as a string.
        Format must be `.npy`.

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

            ![](https://vedo.embl.es/images/animation/39766016-85c1c1d6-52e3-11e8-8575-d167b7ce5217.gif)
        """
        super().__init__()

        self.actor = vtki.vtkAssembly()
        self.actor.retrieve_object = weak_ref_to(self)

        self.name = "Assembly"
        self.filename = ""
        self.rendered_at = set()
        self.scalarbar = None
        self.info = {}
        self.time = 0

        self.transform = LinearTransform()

        # Init by filename
        if len(meshs) == 1 and isinstance(meshs[0], str):
            filename = vedo.file_io.download(meshs[0], verbose=False)
            data = np.load(filename, allow_pickle=True)
            try:
                # old format with a single object
                meshs = [vedo.file_io.from_numpy(dd) for dd in data]
            except TypeError:
                # new format with a dictionary
                data = data.item()
                meshs = []
                for ad in data["objects"][0]["parts"]:
                    obb = vedo.file_io.from_numpy(ad)
                    meshs.append(obb)
                self.transform = LinearTransform(data["objects"][0]["transform"])
                self.actor.SetPosition(self.transform.T.GetPosition())
                self.actor.SetOrientation(self.transform.T.GetOrientation())
                self.actor.SetScale(self.transform.T.GetScale())

        # Name and load from dictionary
        if len(meshs) == 1 and isinstance(meshs[0], dict):
            meshs = meshs[0]
            for name in meshs:
                meshs[name].name = name
            meshs = list(meshs.values())
        else:
            if len(meshs) == 1:
                meshs = meshs[0]
            else:
                meshs = vedo.utils.flatten(meshs)

        self.objects = [m for m in meshs if m]
        self.actors = [m.actor for m in self.objects]

        scalarbars = []
        for a in self.actors:
            if isinstance(a, vtki.get_class("Prop3D")):  # and a.GetNumberOfPoints():
                self.actor.AddPart(a)
            if hasattr(a, "scalarbar") and a.scalarbar is not None:
                scalarbars.append(a.scalarbar)

        if len(scalarbars) > 1:
            self.scalarbar = Group(scalarbars)
        elif len(scalarbars) == 1:
            self.scalarbar = scalarbars[0]

        self.pipeline = vedo.utils.OperationNode(
            "Assembly",
            parents=self.objects,
            comment=f"#meshes {len(self.objects)}",
            c="#f08080",
        )
        ##########################################

    def __str__(self):
        return summary_string(self, self._summary_rows())

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

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

    def _summary_rows(self):
        rows = []
        cname = self.__class__.__name__

        if self.name:
            rows.append(("name", self.name))
            if "legend" in self.info.keys() and self.info["legend"]:
                rows.append(("legend", self.info["legend"]))

        n = len(self.unpack())
        names = np.unique([a.name for a in self.unpack() if a.name])
        value = str(n)
        if len(names) > 0:
            value += " " + str(names).replace("'", "")[:56]
        rows.append(("n. of objects", value))
        rows.append(("position", str(self.actor.GetPosition())))
        rows.append(
            ("bounds", format_bounds(self.actor.GetBounds(), vedo.utils.precision))
        )

        if "Histogram1D" in cname:
            if self.title != "":
                rows.append(("title", f"{self.title}"))
            if self.xtitle and self.xtitle != " ":
                rows.append(("xtitle", f"{self.xtitle}"))
            if self.ytitle and self.ytitle != " ":
                rows.append(("ytitle", f"{self.ytitle}"))
            rows.append(("entries", f"{self.entries}"))
            rows.append(("mean, mode", f"{self.mean:.6f}, {self.mode:.6f}"))
            rows.append(("std", f"{self.std:.6f}"))
        elif "Histogram2D" in cname:
            if self.title != "":
                rows.append(("title", f"{self.title}"))
            if self.xtitle and self.xtitle != " ":
                rows.append(("xtitle", f"{self.xtitle}"))
            if self.ytitle and self.ytitle != " ":
                rows.append(("ytitle", f"{self.ytitle}"))
            rows.append(("entries", f"{self.entries}"))
            rows.append(("mean", f"{vedo.utils.precision(self.mean, 6)}"))
            rows.append(("std", f"{vedo.utils.precision(self.std, 6)}"))

        return rows

    def _repr_html_(self):
        """
        HTML representation of the Assembly object for Jupyter Notebooks.

        Returns:
            HTML text with the image and some properties.
        """
        import io
        import base64
        from PIL import Image

        library_name = "vedo.assembly.Assembly"
        help_url = "https://vedo.embl.es/docs/vedo/assembly.html"

        arr = self.thumbnail(zoom=1.1, elevation=-60)

        im = Image.fromarray(arr)
        buffered = io.BytesIO()
        im.save(buffered, format="PNG", quality=100)
        encoded = base64.b64encode(buffered.getvalue()).decode("utf-8")
        url = "data:image/png;base64," + encoded
        image = f"<img src='{url}'></img>"

        # statisitics
        bounds = "<br/>".join(
            [
                vedo.utils.precision(min_x, 4)
                + " ... "
                + vedo.utils.precision(max_x, 4)
                for min_x, max_x in zip(self.bounds()[::2], self.bounds()[1::2])
            ]
        )

        help_text = ""
        if self.name:
            help_text += f"<b> {self.name}: &nbsp&nbsp</b>"
        help_text += (
            '<b><a href="' + help_url + '" target="_blank">' + library_name + "</a></b>"
        )
        if self.filename:
            dots = ""
            if len(self.filename) > 30:
                dots = "..."
            help_text += f"<br/><code><i>({dots}{self.filename[-30:]})</i></code>"

        allt = [
            "<table>",
            "<tr>",
            "<td>",
            image,
            "</td>",
            "<td style='text-align: center; vertical-align: center;'><br/>",
            help_text,
            "<table>",
            "<tr><td><b> nr. of objects </b></td><td>"
            + str(self.actor.GetNumberOfPaths())
            + "</td></tr>",
            "<tr><td><b> position </b></td><td>"
            + str(self.actor.GetPosition())
            + "</td></tr>",
            "<tr><td><b> diagonal size </b></td><td>"
            + vedo.utils.precision(self.diagonal_size(), 5)
            + "</td></tr>",
            "<tr><td><b> bounds </b> <br/> (x/y/z) </td><td>"
            + str(bounds)
            + "</td></tr>",
            "</table>",
            "</table>",
        ]
        return "\n".join(allt)

    def __add__(self, obj):
        """
        Add an object to the assembly
        """
        if isinstance(getattr(obj, "actor", None), vtki.get_class("Prop3D")):
            self.objects.append(obj)
            self.actors.append(obj.actor)
            self.actor.AddPart(obj.actor)

            if hasattr(obj, "scalarbar") and obj.scalarbar is not None:
                if self.scalarbar is None:
                    self.scalarbar = obj.scalarbar
                    return self

                def unpack_group(scalarbar):
                    if isinstance(scalarbar, Group):
                        return scalarbar.unpack()
                    else:
                        return scalarbar

                if isinstance(self.scalarbar, Group):
                    self.scalarbar += unpack_group(obj.scalarbar)
                else:
                    self.scalarbar = Group(
                        [unpack_group(self.scalarbar), unpack_group(obj.scalarbar)]
                    )
            self.pipeline = vedo.utils.OperationNode(
                "add mesh", parents=[self, obj], c="#f08080"
            )
        return self

    def __isub__(self, obj):
        """
        Remove an object to the assembly.
        """
        if not vedo.utils.is_sequence(obj):
            obj = [obj]
        for a in obj:
            if a:
                try:
                    self.actor.RemovePart(a)
                    self.objects.remove(a)
                    if a in self.actors:
                        self.actors.remove(a)
                except TypeError:
                    self.actor.RemovePart(a.actor)
                    self.objects.remove(a)
                    if a.actor in self.actors:
                        self.actors.remove(a.actor)
        return self

    def rename(self, name: str) -> Assembly:
        """Set a new name for the Assembly object."""
        self.name = name
        return self

    def add(self, obj):
        """
        Add an object to the assembly.
        """
        self.__add__(obj)
        return self

    def remove(self, obj):
        """
        Remove an object to the assembly.
        """
        self.__isub__(obj)
        return self

    def __contains__(self, obj):
        """Allows to use `in` to check if an object is in the `Assembly`."""
        return obj in self.objects

    def __getitem__(self, i):
        """Return i-th object."""
        if isinstance(i, int):
            return self.objects[i]
        elif isinstance(i, str):
            for m in self.objects:
                if i == m.name:
                    return m
        return None

    def __len__(self):
        """Return nr. of objects in the assembly."""
        return len(self.objects)

    def write(self, filename="assembly.npy") -> Self:
        """
        Write the object to file in `numpy` format (npy).
        """
        vedo.file_io.write(self, filename)
        return self

    # TODO ####
    # def propagate_transform(self):
    #     """Propagate the transformation to all parts."""
    #     # navigate the assembly and apply the transform to all parts
    #     # and reset position, orientation and scale of the assembly
    #     for i in range(self.actor.GetNumberOfPaths()):
    #         path = self.actor.GetPath(i)
    #         obj = path.GetLastNode().GetViewProp()
    #         obj.SetUserTransform(self.transform.T)
    #         obj.SetPosition(0, 0, 0)
    #         obj.SetOrientation(0, 0, 0)
    #         obj.SetScale(1, 1, 1)
    #     raise NotImplementedError()

    def unpack(self, i=None) -> list[vedo.Mesh] | vedo.Mesh:
        """Unpack the list of objects from a `Assembly`.

        If `i` is given, get `i-th` object from a `Assembly`.
        Input can be a string, in this case returns the first object
        whose name contains the given string.

        Examples:
            - [custom_axes4.py](https://github.com/marcomusy/vedo/tree/master/examples/pyplot/custom_axes4.py)
        """
        if i is None:
            return self.objects
        elif isinstance(i, int):
            return self.objects[i]
        elif isinstance(i, str):
            for m in self.objects:
                if i == m.name:
                    return m
        return []

    def recursive_unpack(self) -> list["vedo.Mesh"]:
        """Flatten out an Assembly."""

        def _genflatten(lst):
            if lst:
                ##
                if isinstance(lst[0], Assembly):
                    lst = lst[0].unpack()
                ##
                for elem in lst:
                    if isinstance(elem, Assembly):
                        apos = elem.actor.GetPosition()
                        asum = np.sum(apos)
                        for x in elem.unpack():
                            if asum:
                                yield x.clone().shift(apos)
                            else:
                                yield x
                    else:
                        yield elem

        return list(_genflatten([self]))

    def pickable(self, value=True) -> Assembly:
        """Set/get the pickability property of an assembly and its elements"""
        self.actor.SetPickable(value)
        # set property to each element
        for elem in self.recursive_unpack():
            elem.pickable(value)
        return self

    def clone(self) -> Assembly:
        """Make a clone copy of the object. Same as `copy()`."""
        newlist = []
        for a in self.objects:
            newlist.append(a.clone())
        return Assembly(newlist)

    def clone2d(
        self, pos="bottom-left", size=1, rotation=0, ontop=False, justify="bottom-left"
    ) -> Group:
        """
        Convert the `Assembly` into a `Group` of 2D objects.

        Args:
            pos (list, str):
                Position in 2D, as a string or list (x,y).
                The center of the renderer is [-1,-1] while top-right is [1,1].
                Any combination of "center", "top", "bottom", "left" and "right" will work.
            size (float):
                global scaling factor for the 2D object.
                The scaling is normalized to the x-range of the original object.
            rotation (float):
                rotation angle in degrees.
            ontop (bool):
                if `True` the now 2D object is rendered on top of the 3D scene.
            scale (float):
                deprecated, use `size` instead.
            justify (str):
                justification for the 2D object.

        Returns:
            `Group` object.
        """
        padding = 0.05
        x0, x1 = self.xbounds()
        y0, y1 = self.ybounds()
        pp = self.pos()
        x0 -= pp[0]
        x1 -= pp[0]
        y0 -= pp[1]
        y1 -= pp[1]

        # choose offset based on justification
        offset = [x0, y0]
        if "cent" in justify:
            offset = [(x0 + x1) / 2, (y0 + y1) / 2]
            if "right" in justify:
                offset[0] = x1
            if "left" in justify:
                offset[0] = x0
            if "top" in justify:
                offset[1] = y1
            if "bottom" in justify:
                offset[1] = y0
        elif "top" in justify:
            if "right" in justify:
                offset = [x1, y1]
            elif "left" in justify:
                offset = [x0, y1]
            else:
                raise ValueError(f"incomplete justify='{justify}'")
        elif "bottom" in justify:
            if "right" in justify:
                offset = [x1, y0]
            elif "left" in justify:
                offset = [x0, y0]
            else:
                raise ValueError(f"incomplete justify='{justify}'")

        # choose position
        if "cent" in pos:
            offset = [(x0 + x1) / 2, (y0 + y1) / 2]
            position = [0.0, 0.0]
            if "right" in pos:
                offset[0] = x1
                position = [1 - padding, 0]
            if "left" in pos:
                offset[0] = x0
                position = [-1 + padding, 0]
            if "top" in pos:
                offset[1] = y1
                position = [0, 1 - padding]
            if "bottom" in pos:
                offset[1] = y0
                position = [0, -1 + padding]
        elif "top" in pos:
            if "right" in pos:
                offset = [x1, y1]
                position = [1 - padding, 1 - padding]
            elif "left" in pos:
                offset = [x0, y1]
                position = [-1 + padding, 1 - padding]
            else:
                raise ValueError(f"incomplete position pos='{pos}'")
        elif "bottom" in pos:
            if "right" in pos:
                offset = [x1, y0]
                position = [1 - padding, -1 + padding]
            elif "left" in pos:
                offset = [x0, y0]
                position = [-1 + padding, -1 + padding]
            else:
                raise ValueError(f"incomplete position pos='{pos}'")
        else:
            position = pos

        group = Group()

        bnds = self.bounds()
        cm = [(bnds[0] + bnds[1]) / 2, (bnds[2] + bnds[3]) / 2, 0]

        for a in self.recursive_unpack():
            if not isinstance(a, vedo.Points):
                continue
            if a.npoints == 0:
                continue

            s = size * 500 / (x1 - x0)
            if a.properties.GetRepresentation() == 1:
                # wireframe is not rendered correctly in 2d
                b = a.boundaries().lw(1).c(a.color(), a.alpha())
                if rotation:
                    b.rotate_z(rotation, around=cm)
                a2d = b.clone2d(size=s, offset=offset)
            else:
                if rotation:
                    a = a.clone().rotate_z(rotation, around=cm)
                a2d = a.clone2d(size=s, offset=offset)
            a2d.pos(position).ontop(ontop)
            group += a2d

        try:  # copy info from Histogram1D
            group.entries = self.entries
            group.frequencies = self.frequencies
            group.errors = self.errors
            group.edges = self.edges
            group.centers = self.centers
            group.mean = self.mean
            group.mode = self.mode
            group.std = self.std
        except AttributeError:
            pass

        group.name = self.name
        return group

    def copy(self) -> Assembly:
        """Return a copy of the object. Alias of `clone()`."""
        return self.clone()

add(obj)

Add an object to the assembly.

Source code in vedo/assembly.py
455
456
457
458
459
460
def add(self, obj):
    """
    Add an object to the assembly.
    """
    self.__add__(obj)
    return self

clone()

Make a clone copy of the object. Same as copy().

Source code in vedo/assembly.py
559
560
561
562
563
564
def clone(self) -> Assembly:
    """Make a clone copy of the object. Same as `copy()`."""
    newlist = []
    for a in self.objects:
        newlist.append(a.clone())
    return Assembly(newlist)

clone2d(pos='bottom-left', size=1, rotation=0, ontop=False, justify='bottom-left')

Convert the Assembly into a Group of 2D objects.

Parameters:

Name Type Description Default
pos (list, str)

Position in 2D, as a string or list (x,y). The center of the renderer is [-1,-1] while top-right is [1,1]. Any combination of "center", "top", "bottom", "left" and "right" will work.

'bottom-left'
size float

global scaling factor for the 2D object. The scaling is normalized to the x-range of the original object.

1
rotation float

rotation angle in degrees.

0
ontop bool

if True the now 2D object is rendered on top of the 3D scene.

False
scale float

deprecated, use size instead.

required
justify str

justification for the 2D object.

'bottom-left'

Returns:

Type Description
Group

Group object.

Source code in vedo/assembly.py
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
def clone2d(
    self, pos="bottom-left", size=1, rotation=0, ontop=False, justify="bottom-left"
) -> Group:
    """
    Convert the `Assembly` into a `Group` of 2D objects.

    Args:
        pos (list, str):
            Position in 2D, as a string or list (x,y).
            The center of the renderer is [-1,-1] while top-right is [1,1].
            Any combination of "center", "top", "bottom", "left" and "right" will work.
        size (float):
            global scaling factor for the 2D object.
            The scaling is normalized to the x-range of the original object.
        rotation (float):
            rotation angle in degrees.
        ontop (bool):
            if `True` the now 2D object is rendered on top of the 3D scene.
        scale (float):
            deprecated, use `size` instead.
        justify (str):
            justification for the 2D object.

    Returns:
        `Group` object.
    """
    padding = 0.05
    x0, x1 = self.xbounds()
    y0, y1 = self.ybounds()
    pp = self.pos()
    x0 -= pp[0]
    x1 -= pp[0]
    y0 -= pp[1]
    y1 -= pp[1]

    # choose offset based on justification
    offset = [x0, y0]
    if "cent" in justify:
        offset = [(x0 + x1) / 2, (y0 + y1) / 2]
        if "right" in justify:
            offset[0] = x1
        if "left" in justify:
            offset[0] = x0
        if "top" in justify:
            offset[1] = y1
        if "bottom" in justify:
            offset[1] = y0
    elif "top" in justify:
        if "right" in justify:
            offset = [x1, y1]
        elif "left" in justify:
            offset = [x0, y1]
        else:
            raise ValueError(f"incomplete justify='{justify}'")
    elif "bottom" in justify:
        if "right" in justify:
            offset = [x1, y0]
        elif "left" in justify:
            offset = [x0, y0]
        else:
            raise ValueError(f"incomplete justify='{justify}'")

    # choose position
    if "cent" in pos:
        offset = [(x0 + x1) / 2, (y0 + y1) / 2]
        position = [0.0, 0.0]
        if "right" in pos:
            offset[0] = x1
            position = [1 - padding, 0]
        if "left" in pos:
            offset[0] = x0
            position = [-1 + padding, 0]
        if "top" in pos:
            offset[1] = y1
            position = [0, 1 - padding]
        if "bottom" in pos:
            offset[1] = y0
            position = [0, -1 + padding]
    elif "top" in pos:
        if "right" in pos:
            offset = [x1, y1]
            position = [1 - padding, 1 - padding]
        elif "left" in pos:
            offset = [x0, y1]
            position = [-1 + padding, 1 - padding]
        else:
            raise ValueError(f"incomplete position pos='{pos}'")
    elif "bottom" in pos:
        if "right" in pos:
            offset = [x1, y0]
            position = [1 - padding, -1 + padding]
        elif "left" in pos:
            offset = [x0, y0]
            position = [-1 + padding, -1 + padding]
        else:
            raise ValueError(f"incomplete position pos='{pos}'")
    else:
        position = pos

    group = Group()

    bnds = self.bounds()
    cm = [(bnds[0] + bnds[1]) / 2, (bnds[2] + bnds[3]) / 2, 0]

    for a in self.recursive_unpack():
        if not isinstance(a, vedo.Points):
            continue
        if a.npoints == 0:
            continue

        s = size * 500 / (x1 - x0)
        if a.properties.GetRepresentation() == 1:
            # wireframe is not rendered correctly in 2d
            b = a.boundaries().lw(1).c(a.color(), a.alpha())
            if rotation:
                b.rotate_z(rotation, around=cm)
            a2d = b.clone2d(size=s, offset=offset)
        else:
            if rotation:
                a = a.clone().rotate_z(rotation, around=cm)
            a2d = a.clone2d(size=s, offset=offset)
        a2d.pos(position).ontop(ontop)
        group += a2d

    try:  # copy info from Histogram1D
        group.entries = self.entries
        group.frequencies = self.frequencies
        group.errors = self.errors
        group.edges = self.edges
        group.centers = self.centers
        group.mean = self.mean
        group.mode = self.mode
        group.std = self.std
    except AttributeError:
        pass

    group.name = self.name
    return group

copy()

Return a copy of the object. Alias of clone().

Source code in vedo/assembly.py
705
706
707
def copy(self) -> Assembly:
    """Return a copy of the object. Alias of `clone()`."""
    return self.clone()

pickable(value=True)

Set/get the pickability property of an assembly and its elements

Source code in vedo/assembly.py
551
552
553
554
555
556
557
def pickable(self, value=True) -> Assembly:
    """Set/get the pickability property of an assembly and its elements"""
    self.actor.SetPickable(value)
    # set property to each element
    for elem in self.recursive_unpack():
        elem.pickable(value)
    return self

recursive_unpack()

Flatten out an Assembly.

Source code in vedo/assembly.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
def recursive_unpack(self) -> list["vedo.Mesh"]:
    """Flatten out an Assembly."""

    def _genflatten(lst):
        if lst:
            ##
            if isinstance(lst[0], Assembly):
                lst = lst[0].unpack()
            ##
            for elem in lst:
                if isinstance(elem, Assembly):
                    apos = elem.actor.GetPosition()
                    asum = np.sum(apos)
                    for x in elem.unpack():
                        if asum:
                            yield x.clone().shift(apos)
                        else:
                            yield x
                else:
                    yield elem

    return list(_genflatten([self]))

remove(obj)

Remove an object to the assembly.

Source code in vedo/assembly.py
462
463
464
465
466
467
def remove(self, obj):
    """
    Remove an object to the assembly.
    """
    self.__isub__(obj)
    return self

rename(name)

Set a new name for the Assembly object.

Source code in vedo/assembly.py
450
451
452
453
def rename(self, name: str) -> Assembly:
    """Set a new name for the Assembly object."""
    self.name = name
    return self

unpack(i=None)

Unpack the list of objects from a Assembly.

If i is given, get i-th object from a Assembly. Input can be a string, in this case returns the first object whose name contains the given string.

Examples:

Source code in vedo/assembly.py
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
def unpack(self, i=None) -> list[vedo.Mesh] | vedo.Mesh:
    """Unpack the list of objects from a `Assembly`.

    If `i` is given, get `i-th` object from a `Assembly`.
    Input can be a string, in this case returns the first object
    whose name contains the given string.

    Examples:
        - [custom_axes4.py](https://github.com/marcomusy/vedo/tree/master/examples/pyplot/custom_axes4.py)
    """
    if i is None:
        return self.objects
    elif isinstance(i, int):
        return self.objects[i]
    elif isinstance(i, str):
        for m in self.objects:
            if i == m.name:
                return m
    return []

write(filename='assembly.npy')

Write the object to file in numpy format (npy).

Source code in vedo/assembly.py
487
488
489
490
491
492
def write(self, filename="assembly.npy") -> Self:
    """
    Write the object to file in `numpy` format (npy).
    """
    vedo.file_io.write(self, filename)
    return self

Group

Form groups of generic objects (not necessarily meshes).

Source code in vedo/assembly.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
class Group:
    """Form groups of generic objects (not necessarily meshes)."""

    def __init__(self, objects=()):
        """Form groups of generic objects (not necessarily meshes)."""

        self.objects = []

        if isinstance(objects, dict):
            for name in objects:
                objects[name].name = name
            objects = list(objects.values())
        elif vedo.utils.is_sequence(objects):
            self.objects = list(objects)

        self.actor = vtki.vtkPropAssembly()
        self.actor.retrieve_object = weak_ref_to(self)

        self.name = "Group"
        self.filename = ""
        self.trail = None
        self.trail_points = []
        self.trail_segment_size = 0
        self.trail_offset = None
        self.shadows = []
        self.info = {}
        self.rendered_at = set()
        self.scalarbar = None

        for a in vedo.utils.flatten(objects):
            if a:
                self.actor.AddPart(a.actor)

        self.actor.PickableOff()

    def __str__(self):
        return summary_string(self, self._summary_rows())

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

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

    def _summary_rows(self):
        rows = []
        if self.name:
            rows.append(("name", self.name))
            if "legend" in self.info.keys() and self.info["legend"]:
                rows.append(("legend", self.info["legend"]))

        parts = self.unpack()
        n = len(parts)
        names = [a.name for a in parts if hasattr(a, "name") and a.name]
        value = str(n)
        if names:
            value += " " + str(names).replace("'", "")[:56]
        rows.append(("n. of objects", value))
        return rows

    def __iadd__(self, obj):
        """Add an object to the group."""
        if not vedo.utils.is_sequence(obj):
            obj = [obj]
        for a in obj:
            if a:
                try:
                    self.actor.AddPart(a)
                except TypeError:
                    self.actor.AddPart(a.actor)
                    self.objects.append(a)
        return self

    def __isub__(self, obj):
        """Remove an object to the group."""
        if not vedo.utils.is_sequence(obj):
            obj = [obj]
        for a in obj:
            if a:
                try:
                    self.actor.RemovePart(a)
                except TypeError:
                    self.actor.RemovePart(a.actor)
                if a in self.objects:
                    self.objects.remove(a)
        return self

    def rename(self, name: str) -> Group:
        """Set a new name for the Group object."""
        self.name = name
        return self

    def add(self, obj):
        """Add an object to the group."""
        self.__iadd__(obj)
        return self

    def remove(self, obj):
        """Remove an object to the group."""
        self.__isub__(obj)
        return self

    def _unpack(self):
        """Unpack the group into its elements"""
        elements = []
        self.actor.InitPathTraversal()
        parts = self.actor.GetParts()
        parts.InitTraversal()
        for i in range(parts.GetNumberOfItems()):
            ele = parts.GetItemAsObject(i)
            elements.append(ele)

        # gr.InitPathTraversal()
        # for _ in range(gr.GetNumberOfPaths()):
        #     path  = gr.GetNextPath()
        #     print([path])
        #     path.InitTraversal()
        #     for i in range(path.GetNumberOfItems()):
        #         a = path.GetItemAsObject(i).GetViewProp()
        #         print([a])

        return elements

    def unpack(self):
        """Unpack the group into its vedo objects."""
        return self.objects

    def clear(self) -> Group:
        """Remove all parts"""
        for a in self._unpack():
            self.actor.RemovePart(a)
        self.objects = []
        return self

    def on(self) -> Group:
        """Switch on visibility"""
        self.actor.VisibilityOn()
        return self

    def off(self) -> Group:
        """Switch off visibility"""
        self.actor.VisibilityOff()
        return self

    def pickable(self, value=True) -> Group:
        """The pickability property of the Group."""
        self.actor.SetPickable(value)
        return self

    def use_bounds(self, value=True) -> Group:
        """Set the use bounds property of the Group."""
        self.actor.SetUseBounds(value)
        return self

    def print(self) -> Group:
        """Print info about the object."""
        print(self)
        return self

add(obj)

Add an object to the group.

Source code in vedo/assembly.py
121
122
123
124
def add(self, obj):
    """Add an object to the group."""
    self.__iadd__(obj)
    return self

clear()

Remove all parts

Source code in vedo/assembly.py
156
157
158
159
160
161
def clear(self) -> Group:
    """Remove all parts"""
    for a in self._unpack():
        self.actor.RemovePart(a)
    self.objects = []
    return self

off()

Switch off visibility

Source code in vedo/assembly.py
168
169
170
171
def off(self) -> Group:
    """Switch off visibility"""
    self.actor.VisibilityOff()
    return self

on()

Switch on visibility

Source code in vedo/assembly.py
163
164
165
166
def on(self) -> Group:
    """Switch on visibility"""
    self.actor.VisibilityOn()
    return self

pickable(value=True)

The pickability property of the Group.

Source code in vedo/assembly.py
173
174
175
176
def pickable(self, value=True) -> Group:
    """The pickability property of the Group."""
    self.actor.SetPickable(value)
    return self

print()

Print info about the object.

Source code in vedo/assembly.py
183
184
185
186
def print(self) -> Group:
    """Print info about the object."""
    print(self)
    return self

remove(obj)

Remove an object to the group.

Source code in vedo/assembly.py
126
127
128
129
def remove(self, obj):
    """Remove an object to the group."""
    self.__isub__(obj)
    return self

rename(name)

Set a new name for the Group object.

Source code in vedo/assembly.py
116
117
118
119
def rename(self, name: str) -> Group:
    """Set a new name for the Group object."""
    self.name = name
    return self

unpack()

Unpack the group into its vedo objects.

Source code in vedo/assembly.py
152
153
154
def unpack(self):
    """Unpack the group into its vedo objects."""
    return self.objects

use_bounds(value=True)

Set the use bounds property of the Group.

Source code in vedo/assembly.py
178
179
180
181
def use_bounds(self, value=True) -> Group:
    """Set the use bounds property of the Group."""
    self.actor.SetUseBounds(value)
    return self