Exemple #1
0
    def __init__(self, *args, **kwargs):
        self.dt = kwargs.pop("dt", 100) # update every dt milliseconds
        self.timerId = None
        self.isplaying = False
        self.counter = 0 # frame counter

        self.plotter = vedo.Plotter(*args, **kwargs) # setup the Plotter object
        self.timerevt = self.plotter.addCallback('timer', self.handle_timer)
Exemple #2
0
def viz_mean_excitability(sid, rid):
    regpos, w, obsmask, surfaces, contacts = read_structural_data(sid, rid)
    vlines, vmeshes, vcontacts = viz_structure(regpos, w, surfaces, contacts)

    # Load results
    nreg = regpos.shape[0]
    res = io.parse_csv([
        f"run/solo/INC/vep/id{sid:03d}/output/r{rid:02d}_all/chain_{chain}.csv"
        for chain in [1, 2]
    ])
    cinf = res['c']
    # cmean = np.mean(cinf, axis=0)
    # pexc = np.mean(cinf > 2.0, axis=0)
    scalar = np.percentile(cinf, 50, axis=0)

    # Regions
    cmap = 'plasma'
    # vmin = np.min(scalar)
    # vmax = np.max(scalar)
    vmin, vmax = -2, 2

    vpoints = []
    for i in range(nreg):
        if not obsmask[i]:
            vpoints.append(
                vp.Sphere(regpos[i],
                          r=4,
                          c=vp.colorMap(scalar[i], cmap, vmin, vmax)))
        else:
            vpoints.append(
                vp.Cube(regpos[i],
                        side=6,
                        c=vp.colorMap(scalar[i], cmap, vmin, vmax)))

    vbar = vp.Points(regpos, r=0.01).pointColors(scalar,
                                                 cmap=cmap,
                                                 vmin=vmin,
                                                 vmax=vmax)
    vbar.addScalarBar(horizontal=True, pos=(0.8, 0.02))

    def slider(widget, event):
        percentile = widget.GetRepresentation().GetValue()
        scalar = np.percentile(cinf, percentile, axis=0)
        for i in range(nreg):
            vpoints[i].color(vp.colorMap(scalar[i], cmap, vmin, vmax))

    vplotter = vp.Plotter(axes=0)
    vplotter.addSlider2D(slider,
                         0.,
                         100.,
                         value=50.0,
                         pos=3,
                         title="Percentile")
    vplotter.show(vpoints, vlines, vmeshes, vcontacts, vbar)
Exemple #3
0
def viz_network_scalar(centres,
                       scalars,
                       weights,
                       obsmask,
                       surfs,
                       view='topdown',
                       size=(1000, 1000),
                       cmap='viridis',
                       vmin=None,
                       vmax=None):
    vp.embedWindow(False)

    if vmin is None:
        vmin = np.min(scalars)
    if vmax is None:
        vmax = np.max(scalars)

    vlines, vmeshes = viz_structure(centres, weights, surfs, w_perc=3)
    nreg = centres.shape[0]

    # Regions
    vpoints = []
    for i in range(nreg):
        if not obsmask[i]:
            vpoints.append(
                vp.Sphere(centres[i],
                          r=4,
                          c=vp.colorMap(scalars[i], cmap, vmin, vmax)))
        else:
            vpoints.append(
                vp.Cube(centres[i],
                        side=6,
                        c=vp.colorMap(scalars[i], cmap, vmin, vmax)))

    if view == 'topdown':
        args = dict(elevation=0, azimuth=0, roll=0, zoom=1.4)
    elif view == 'leftright':
        args = dict(elevation=0, azimuth=270, roll=90, zoom=1.4)
    elif view == 'rightleft':
        args = dict(elevation=0, azimuth=90, roll=270, zoom=1.4)
    else:
        raise ValueError(f"Unexpected view: {view}")

    vplotter = vp.Plotter(axes=0, offscreen=True, size=size)
    vplotter.show(vpoints, vlines, vmeshes, N=1, **args)
    img = vp.screenshot(None, scale=1, returnNumpy=True)
    vp.clear()
    vp.closePlotter()

    return img
Exemple #4
0
def viz_excitability(sid, rid):
    regpos, w, obsmask, surfaces, contacts = read_structural_data(sid, rid)
    vlines, vmeshes, vcontacts = viz_structure(regpos, w, surfaces, contacts)

    # Load results
    nreg = regpos.shape[0]
    res = io.parse_csv([
        f"run/solo/INC/vep/id{sid:03d}/output/r{rid:02d}_all/chain_{chain}.csv"
        for chain in [1, 2]
    ])
    cinf = res['c']

    ctr = 2.0
    pexc = np.mean(cinf > ctr, axis=0)

    # Regions
    cmap = 'Reds'
    vmin, vmax = 0, 0.15
    # vmin, vmax = -2, 0

    vpoints = []
    for i in range(nreg):
        if not obsmask[i]:
            vpoints.append(
                vp.Sphere(regpos[i],
                          r=4,
                          c=vp.colorMap(pexc[i], cmap, vmin, vmax)))
        else:
            vpoints.append(
                vp.Cube(regpos[i],
                        side=6,
                        c=vp.colorMap(pexc[i], cmap, vmin, vmax)))

    vbar = vp.Points(regpos, r=0.01).pointColors(pexc,
                                                 cmap=cmap,
                                                 vmin=vmin,
                                                 vmax=vmax)
    vbar.addScalarBar(horizontal=True, pos=(0.8, 0.02))

    def cslider(widget, event):
        ctr = widget.GetRepresentation().GetValue()
        pexc = np.mean(cinf > ctr, axis=0)
        for i in range(nreg):
            vpoints[i].color(vp.colorMap(pexc[i], cmap, vmin, vmax))

    vplotter = vp.Plotter(axes=0)
    vplotter.addSlider2D(cslider, -3.0, 3.0, value=2.0, pos=3, title="c")
    vplotter.show(vpoints, vlines, vmeshes, vcontacts, vbar)
Exemple #5
0
def viz_seizure(sid, rid):
    regpos, w, obsmask, surfaces, contacts = read_structural_data(sid, rid)
    vlines, vmeshes, vcontacts = viz_structure(regpos, w, surfaces, contacts)

    # Load results
    nreg = regpos.shape[0]
    res = io.parse_csv([
        f"run/solo/INC/vep/id{sid:03d}/output/r{rid:02d}_all/chain_{chain}.csv"
        for chain in [1, 2]
    ])
    tinf = res['t']

    t = 0.0
    psz = np.mean(tinf < t, axis=0)

    # Regions
    cmap = 'bwr'
    vmin, vmax = 0, 1

    vpoints = []
    for i in range(nreg):
        if not obsmask[i]:
            vpoints.append(
                vp.Sphere(regpos[i],
                          r=4,
                          c=vp.colorMap(psz[i], cmap, vmin, vmax)))
        else:
            vpoints.append(
                vp.Cube(regpos[i],
                        side=6,
                        c=vp.colorMap(psz[i], cmap, vmin, vmax)))

    vbar = vp.Points(regpos, r=0.01).pointColors(psz,
                                                 cmap=cmap,
                                                 vmin=vmin,
                                                 vmax=vmax)
    vbar.addScalarBar(horizontal=True, pos=(0.8, 0.02))

    def tslider(widget, event):
        t = widget.GetRepresentation().GetValue()
        psz = np.mean(tinf < t, axis=0)
        for i in range(nreg):
            vpoints[i].color(vp.colorMap(psz[i], cmap, vmin, vmax))

    vplotter = vp.Plotter(axes=0)
    vplotter.addSlider2D(tslider, 0, 90.0, value=0.0, pos=3, title="t")
    vplotter.show(vpoints, vlines, vmeshes, vcontacts, vbar)
Exemple #6
0
def plot_mesh(mesh, arrows, cones, complete=True, mesh2=None):
    """ Plot mesh.

    Args:
        mesh (vedo.pointcloud.Points): Mesh object.
        arrows (vedo.shapes.Arrows): Load arrows.
        cones (vedo.shapes.Cones): Cones to represent constrain nodes.
        complete (:obj:`bool`, optional): If true plot mesh with loads and constrain nodes. Defaults to True.
        mesh2 (:obj:`vedo.pointcloud.Points`, optional): Mesh without faces. Defaults to None.
    """
    vp = vt.Plotter()

    vp += mesh
    if complete:
        vp += arrows
        vp += cones
    if mesh2 is not None:
        vp += mesh2
    return vp
    def __init__(self, model, project_parameters):
        super().__init__(model, project_parameters)

        ######### GUI attributes
        self.Continue = True
        self.timestep = 0
        self.slider1 = Slider(0)
        self.Plot = vedo.Plotter(title="Simulation Results", interactive=False)
        self.Plot.addSlider2D(self.slider1.GenericSlider,
                              -200,
                              400,
                              value=0,
                              pos=3,
                              title="Pressure (MPa)")
        self.Plot += vedo.Text2D(
            'Move the slider to change the Pressure on the Face of the Bunny',
            s=1.2)
        self.PauseButton = self.Plot.addButton(
            self.PauseButtonFunc,
            pos=(0.9, .9),  # x,y fraction from bottom left corner
            states=["PAUSE", "CONTINUE"],
            c=["w", "w"],
            bc=["b", "g"],  # colors of states
            font="courier",  # arial, courier, times
            size=25,
            bold=True,
            italic=False,
        )

        self.StopButton = self.Plot.addButton(
            self.StopButtonFunc,
            pos=(0.1, .9),  # x,y fraction from bottom left corner
            states=["STOP"],
            c=["w"],
            bc=["r"],  # colors of states
            font="courier",  # arial, courier, times
            size=25,
            bold=True,
            italic=False,
        )
        self.Plot.show()
Exemple #8
0
def animation(coord, connect, amp, disp_vector):
    """ Plot deformed mesh animation.

    Args:
        coord (:obj:`numpy.array`): Coordinates of the element.
        connect (:obj:`numpy.array`): Element connectivity.
        amp (:obj:`int`): Amplitude. 
        disp_vector (:obj:`numpy.array`): Displacement.
    """
    vt.printc("Press F1 to exit.", c="red", invert=1)
    vp = vt.Plotter(axes=0, interactive=0)
    vp += __doc__
    ind_faces_U = free_faces(coord, connect)
    aux = np.linspace(-1, 1, num=400)
    factor = amp * np.sin(aux * 2 * np.pi)
    while True:
        for f in factor:
            coord3D_U = fc.apply_U(disp_vector, coord, factor=f)
            verts_U = coord3D_U[:, 1:]
            mesh = build_mesh(verts_U, ind_faces_U)
            vp.clear()
            vp.add(mesh)
            vp.show()
Exemple #9
0
def viz_param_manifold(filename, size):
    data = np.load(filename)

    vline = vp.Tube(data['boundary_hns'], r=0.08)
    vline.color('g')

    # HNS manifold
    vmesh_hns = vp.Mesh([data['verts_hns'], data['triangs_hns']])
    k = 3
    prior = (2 * np.pi)**(-k / 2) * (np.exp(
        -0.5 * np.sum(vmesh_hns.points()**2, axis=1)))
    vmesh_hns.pointColors(prior, cmap='Reds', vmin=0)
    vmesh_hns.addScalarBar(horizontal=True,
                           nlabels=6,
                           c='k',
                           pos=(0.74, 0.01),
                           titleFontSize=44)
    vmesh_hns.scalarbar.SetLabelFormat("%.2g")
    vmesh_hns.scalarbar.SetBarRatio(1.0)

    # Inverted HNS manifold
    vmesh_hnsi = vp.Mesh([data['verts_hnsi'], data['triangs_hnsi']])
    # vmesh_hnsi.color([0.68, 0.68, 0.68])
    vmesh_hnsi.color([0.9, 0.9, 0.9]).alpha(0.0)

    # Invisible points to set the extent
    vpoints = vp.Points([(-5.01, -5.01, -5.01), (5.01, 5.01, 5.01)]).alpha(0.0)

    vplotter = vp.Plotter(offscreen=True,
                          size=size,
                          axes=dict(xyGrid=True,
                                    yzGrid=True,
                                    zxGrid=True,
                                    xTitleSize=0,
                                    yTitleSize=0,
                                    zTitleSize=0,
                                    xHighlightZero=True,
                                    yHighlightZero=True,
                                    zHighlightZero=True,
                                    xHighlightZeroColor='b',
                                    yHighlightZeroColor='b',
                                    zHighlightZeroColor='b',
                                    numberOfDivisions=10,
                                    axesLineWidth=5,
                                    tipSize=0.02,
                                    gridLineWidth=2,
                                    xLabelSize=0.05,
                                    yLabelSize=0.05,
                                    zLabelSize=0.05,
                                    xLabelOffset=0.05,
                                    yLabelOffset=0.05,
                                    zLabelOffset=0.0,
                                    zTitleRotation=225))
    vlabels = [
        vp.Text2D("H", (0.09 * size[0], 0.10 * size[1]), s=3, font='Arial'),
        vp.Text2D("N", (0.87 * size[0], 0.16 * size[1]), s=3, font='Arial'),
        vp.Text2D("S", (0.49 * size[0], 0.90 * size[1]), s=3, font='Arial')
    ]

    k = 2
    vecs = np.array([[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
                      [0, 0, 0, 0, 0, 0]],
                     [[k, -k, 0, 0, 0, 0], [0, 0, k, -k, 0, 0],
                      [0, 0, 0, 0, k, -k]]])
    varrows = vp.Arrows(vecs[0].T, vecs[1].T, s=1.2, c='k')

    vp.show([vline, vmesh_hns, vmesh_hnsi, vpoints, varrows] + vlabels,
            camera=dict(pos=(16, 13, 20),
                        focalPoint=(0, 0, 1.5),
                        viewup=(0, 0, 1)))

    img = vp.screenshot(None, scale=1, returnNumpy=True)
    vp.clear()
    vp.closePlotter()

    return img
Exemple #10
0
"""Create a simple Play/Pause app with a timer event
You can interact with the scene during the loop!
..press q to quit"""
import vedo


def buttonfunc():
    global timerId
    plotter.timerCallback("destroy", timerId)
    if "Play" in button.status():
        # instruct to call handle_timer() every 10 msec:
        timerId = plotter.timerCallback("create", dt=10)
    button.switch()

def handle_timer(event):
    ### Animate your stuff here ######################################
    earth.rotateZ(1)            # rotate the Earth by 1 deg
    plotter.render()


plotter = vedo.Plotter()

timerId = None
button = plotter.addButton(buttonfunc, states=[" Play ","Pause"], size=40)
evntId = plotter.addCallback("timer", handle_timer)

earth = vedo.Earth()

plotter.show(earth, __doc__, axes=1, bg2='b9', viewup='z')
    meshes.append(mesh)
    displacements.append(displacement)
    # plot things:
    txt = vedo.Text2D(f"step{i}")
    arrow = vedo.Arrow2D([0, 0], F * 20).z(1)
    vedo.dolfin.plot(mesh, arrow, txt, c='grey5', at=i, N=N,
                     zoom=1.1)  #PRESS q

dmesh_i = meshes[0]  # initial mesh
dmesh_f = meshes[-1]  # final mesh

vmesh_i = vedo.Mesh([dmesh_i.coordinates(), dmesh_i.cells()], c='grey5').z(-1)
vmesh_f = vedo.Mesh(
    [dmesh_f.coordinates(), dmesh_f.cells()], c='grey3').wireframe()

plt = vedo.Plotter()

# move a few points along the deformation of the circle
seeds = vedo.Circle(r=50,
                    res=res).points()[:,
                                      (0, 1)]  # make points 2d with [:,(0,1)]
endpoints = []
for i, p in enumerate(seeds):
    line = [p]
    for u in displacements:
        p = p + u(p)
        line.append(p)
    plt += vedo.Line(line, c=i, lw=4).z(1)
    endpoints.append(p)

plt += [vmesh_i, vmesh_f, __doc__]
Exemple #12
0
        plt.add(objs, resetcam=False)
    return [x, y]


# Load some 2D shape and make it symmetric
shape = vedo.load(vedo.dataurl + 'timecourse1d.npy')[55]
shaper = vedo.Line(shape).mirror('x').reverse()
shape = vedo.merge(shape, shaper)
x, y, _ = shape.points().T

# Compute Fourier Discrete Transform in x and y separately:
fourierX = DFT(x)
fourierY = DFT(y)

vedo.settings.defaultFont = 'Glasgo'
plt = vedo.Plotter(size=(1500, 750), bg='black', axes=1, interactive=False)
txt = vedo.Text2D(f"{__doc__} (order={order})",
                  c='red9',
                  bg='white',
                  pos='bottom-center')
plt.show(shape, txt, mode='image', zoom=1.9)

objs, points = [], []
times = np.linspace(0, 2 * np.pi, len(fourierX), endpoint=False)
for time in times:
    x, _ = epicycles(time, 0, fourierX, order)
    _, y = epicycles(time, np.pi / 2, fourierY, order)
    points.append([x, y])

plt.interactive()
Exemple #13
0
def make_video(sid, rid, video_file):
    regpos, w, obsmask, surfaces, contacts = read_structural_data(sid, rid)
    vlines, vmeshes, vcontacts = viz_structure(regpos, w, surfaces, contacts)

    # Load results
    res = io.parse_csv([
        f"run/solo/INC/vep/id{sid:03d}/output/r{rid:02d}_all/chain_{chain}.csv"
        for chain in [1, 2]
    ])
    tinf = res['t']

    t = 0.0
    psz = np.mean(tinf < t, axis=0)
    nreg = regpos.shape[0]

    # Regions
    cmap = 'bwr'
    vpoints = []
    for i in range(nreg):
        if not obsmask[i]:
            vpoints.append(
                vp.Sphere(regpos[i], r=4, c=vp.colorMap(psz[i], cmap, 0, 1)))
        else:
            vpoints.append(
                vp.Cube(regpos[i], side=6, c=vp.colorMap(psz[i], cmap, 0, 1)))

    vbar = vp.Points(regpos, r=0.01).pointColors(psz,
                                                 cmap=cmap,
                                                 vmin=0,
                                                 vmax=1)
    vbar.addScalarBar(horizontal=True, pos=(0.8, 0.02))
    vtext = vp.Text2D(f"t = {t:4.1f} s", pos=0, s=2, c='black')

    center = np.mean(regpos, axis=0)
    dist = 2.5 * (np.max(regpos[:, 1]) - np.min(regpos[:, 1]))

    # Video -------------------------------------------------------
    vplotter = vp.Plotter(axes=0,
                          interactive=0,
                          offscreen=True,
                          size=(1800, 1800))
    nframes = 3000

    vplotter += vpoints
    vplotter += vlines
    vplotter += vmeshes

    video = vp.Video(name=video_file, duration=90)
    ratios = np.array([30, 3, 5, 30, 5, 3, 30, 10])
    frames = (nframes * ratios / np.sum(ratios)).astype(int)

    # Run and pause
    animate(vplotter,
            video,
            frames[0],
            vpoints,
            tinf,
            pos=center + dist * np.r_[0, 0, 1],
            foc=center,
            viewup=(0, 1, 1),
            prange=(0, 45),
            time=lambda p: p)
    animate(vplotter,
            video,
            frames[1],
            vpoints,
            tinf,
            pos=center + dist * np.r_[0, 0, 1],
            foc=center,
            viewup=(0, 1, 1),
            time=45.)

    ## Fly around
    pos = lambda angle: center + dist * np.array(
        [0, -np.sin(angle), np.cos(angle)])
    animate(vplotter,
            video,
            frames[2],
            vpoints,
            tinf,
            pos=pos,
            foc=center,
            viewup=(0, 1, 1),
            prange=(0, np.pi / 2),
            time=45.,
            endpoint=False)

    pos = lambda angle: center + dist * np.array(
        [-np.sin(angle), -np.cos(angle), 0])
    animate(vplotter,
            video,
            frames[3],
            vpoints,
            tinf,
            pos=pos,
            foc=center,
            viewup=(0, 0, 1),
            prange=(0, 2 * np.pi),
            time=45.)

    pos = lambda angle: center + dist * np.array(
        [0, -np.sin(angle), np.cos(angle)])
    animate(vplotter,
            video,
            frames[4],
            vpoints,
            tinf,
            pos=pos,
            foc=center,
            viewup=(0, 1, 1),
            prange=(np.pi / 2, 0),
            time=45.,
            startpoint=False)

    # Pause + run + pause
    animate(vplotter,
            video,
            frames[5],
            vpoints,
            tinf,
            pos=center + dist * np.r_[0, 0, 1],
            foc=center,
            viewup=(0, 1, 1),
            time=45.)
    animate(vplotter,
            video,
            frames[6],
            vpoints,
            tinf,
            pos=center + dist * np.r_[0, 0, 1],
            foc=center,
            viewup=(0, 1, 1),
            prange=(45, 90),
            time=lambda p: p)
    animate(vplotter,
            video,
            frames[7],
            vpoints,
            tinf,
            pos=center + dist * np.r_[0, 0, 1],
            foc=center,
            viewup=(0, 1, 1),
            time=90.)

    video.close()
Exemple #14
0
    if key == 'Left' and data_idx > 0:
        data_idx -= 1
    elif key == 'Right' and data_idx < data_length - 1:
        data_idx += 1

    pos, path = getpos(data_idx)
    plt.clear()

    plt.add(vedo.Points(pos, c='b'))
    plt.add(vedo.Text2D(path, pos=(.02, .02), c='k'))

    plt.add(boundary_mesh)
    plt.render()


plt = vedo.Plotter(interactive=False)

pos, path = getpos(data_idx)

pts = vedo.Points(pos, c='b')
plt.keyPressFunction = keyfunc

data_info = vedo.Text2D(path, pos=(.02, .02), c='k')

verts = [(-1.5, 0, -1.5), (-1.5, 0, 1.5), (1.5, 0, 1.5), (1.5, 0, -1.5),
         (-1.5, 5, -1.5), (-1.5, 5, 1.5), (1.5, 5, 1.5), (1.5, 5, -1.5)]
# faces = [(3,2,1,0),(0,1,5,4),(4,5,6,7),(2,3,7,6),(1,2,6,5),(4,7,3,0)]
faces = [(3, 2, 1, 0), (0, 1, 5, 4), (4, 7, 3, 0)]

boundary_mesh = vedo.Mesh([verts, faces]).lineColor('black').lineWidth(1)
Exemple #15
0
        self.actor.points(self.positions())  # update all positions
        return self


################################################################################
if __name__ == "__main__":

    vedo.settings.allowInteraction = True

    np.random.seed(6)
    boids = []
    for i in range(500):
        c = 'black' if i % 50 else 'red'
        boids.append(Boid(np.random.randn(3), np.random.randn(3), c=c))
    flock = Flock(boids)

    plt = vedo.Plotter(bg2='lb', interactive=False)
    axes = vedo.Axes(xrange=(-3, 3),
                     yrange=(-3, 3),
                     zrange=(-3, 3),
                     yzGrid=True,
                     zxGrid2=True)
    plt += [__doc__, flock.actor, axes]

    pb = vedo.ProgressBar(0, 100)
    for i in pb.range():
        flock.move()
        plt.show(resetcam=False, viewup='z')
        pb.print()
Exemple #16
0
def viz_observation_manifold(t3, tlim, size):
    tmin = 0
    tmax = 2 * tlim

    # tlim line
    vline1 = vp.Tube([[tmin, tlim, t3], [tmax, tlim, t3]], r=2.0)
    vline1.color('g')

    # t = 0 line
    vline2 = vp.Tube([[tmin, tlim, t3], [tmin, tmax, t3]], r=2.0)
    vline2.color((1, 1, 1))

    # Manifold
    verts = [[tmin, tlim, t3], [tmax, tlim, t3], [tmin, tmax, t3],
             [tmax, tmax, t3]]
    triangs = [[0, 1, 3], [0, 3, 2]]
    vmesh1 = vp.Mesh([verts, triangs])
    vmesh1.color((1, 1, 1))

    # Inverse manifold
    verts = [[tmin, tmin, t3], [tmax, tmin, t3], [tmin, tlim, t3],
             [tmax, tlim, t3]]
    triangs = [[0, 1, 3], [0, 3, 2]]
    vmesh2 = vp.Mesh([verts, triangs])
    vmesh2.color((0.9, 0.9, 0.9)).alpha(0.0)

    # Invisible points to set the extent
    vpoints = vp.Points([(tmin - 0.1, tmin - 0.1, tmin - 0.1),
                         (1.01 * tmax, 1.01 * tmax, 1.01 * tmax)]).alpha(0.0)

    lpos = [(p, str(p)) for p in [0, 50, 100, 150]]

    vplotter = vp.Plotter(offscreen=True,
                          size=size,
                          axes=dict(xyGrid=True,
                                    yzGrid=True,
                                    zxGrid=True,
                                    xTitleSize=0,
                                    yTitleSize=0,
                                    zTitleSize=0,
                                    xPositionsAndLabels=lpos,
                                    yPositionsAndLabels=lpos,
                                    zPositionsAndLabels=lpos[1:],
                                    axesLineWidth=5,
                                    tipSize=0.02,
                                    gridLineWidth=2,
                                    xLabelSize=0.05,
                                    yLabelSize=0.05,
                                    zLabelSize=0.05,
                                    xLabelOffset=0.05,
                                    yLabelOffset=0.05,
                                    zLabelOffset=0.0,
                                    zTitleRotation=225))
    vlabels = [
        vp.Text2D("H", (0.09 * size[0], 0.10 * size[1]), s=3, font='Arial'),
        vp.Text2D("N", (0.87 * size[0], 0.16 * size[1]), s=3, font='Arial'),
        vp.Text2D("S", (0.49 * size[0], 0.90 * size[1]), s=3, font='Arial')
    ]

    vp.show([vline1, vline2, vmesh1, vpoints] + vlabels,
            camera=dict(pos=(378, 324, 450),
                        focalPoint=(tlim, tlim, tlim + 27),
                        viewup=(0, 0, 1)))

    img = vp.screenshot(None, scale=1, returnNumpy=True)
    vp.clear()
    vp.closePlotter()

    return img
Exemple #17
0
def _view(scene,
          backend='2d',
          sea=True,
          width=1024,
          height=600,
          camera_pos=(50, -25, 10),
          lookat=(0, 0, 0),
          visual_alpha=1.0,
          do_meshes=True,
          geometry_size=1,
          force_normalize=False,
          force_scale=1,
          cog_normalize=False,
          cog_scale=1):

    camera = dict()
    camera['viewup'] = [0, 0, 1]
    camera['pos'] = camera_pos
    camera['focalPoint'] = lookat

    vtkp.embedWindow(backend=backend)  # screenshot
    vtkp.settings.usingQt = False

    vp = DAVE.visual.Viewport(scene)

    vp.visual_alpha = visual_alpha
    vp.show_meshes = do_meshes
    vp.show_geometry = (geometry_size > 0)
    vp.geometry_scale = geometry_size
    vp.force_do_normalize = force_normalize
    vp.show_force = (force_scale > 0)
    vp.force_scale = force_scale
    vp.cog_scale = cog_scale
    vp.cog_do_normalize = cog_normalize

    vtkp.settings.lightFollowsCamera = True

    offscreen = vtkp.Plotter(axes=0, offscreen=True, size=(width, height))

    vp.show_global = sea

    vp.create_world_actors()
    vp.create_visuals(recreate=True)
    vp.position_visuals()
    vp.update_visibility()

    warningshown = False

    for va in vp.visuals:
        for a in va.actors:
            if a.GetVisibility():
                if backend == 'panel':
                    # Work-around for panel
                    tr = vtk.vtkTransform()
                    tr.SetMatrix(a.GetMatrix())

                    a.SetScale(tr.GetScale())
                    a.SetPosition(tr.GetPosition())
                    a.SetOrientation(tr.GetOrientation())

                    scale = tr.GetScale()
                    orientation = tr.GetOrientation()

                    if not warningshown:
                        if isinstance(va.node, DAVE.Visual):
                            if scale != (1, 1, 1):
                                if orientation != (0, 0, 0):
                                    print(
                                        'WARNING: THIS INTERACTIVE VIEWER WRONGLY HANDLES SCALE IN COMBINATION WITH ORIENTATION.'
                                    )
                                    if va.node is not None:
                                        print(
                                            f'VISUAL FOR {va.node.name} IS NOT DISPLAYED CORRECTLY.'
                                        )
                                    print(
                                        'USE show(...) or Gui for correct visualization'
                                    )
                                    warningshown = True

                    tr0 = vtk.vtkTransform()
                    tr0.Identity()
                    a.SetUserTransform(tr0)

                offscreen.add(a)

    return offscreen.show(camera=camera)
Exemple #18
0
f1_list = sorted(f1_files)
f2_list = sorted(f2_files)

# print(f1_list)
# print(f2_list)

index = 3

medium = pv.read(tmp_folder + 'porousMedium.vti')
grains = medium.get_array('tag').reshape([nz, ny, nx])
grains = grains[:, :, n_slices_start:nx-n_slices_end]
grains = grains[:,:,:]
print(grains.shape)
grains = vd.Volume(grains).isosurface(1)

plt = vd.Plotter(axes=9, bg='w', bg2='w', size=(1200,900), offscreen=False)  # Create a vedo plotter; axes=9 is just an outline
plt += grains.c("gray").opacity(0.4)
cam = dict(pos=(179, 313, 136),
           focalPoint=(45.0, 49.5, 44.0),
           viewup=(-0.163, -0.252, 0.954),
           distance=309,
           clippingRange=(158, 501))

plt.show(camera=cam, interactive=True)  # .screenshot(f'animation_and_plotting/gif_images/test{index}.png', scale=4)
plt.close()
# exit()

# for index in range(len(f1_list)):
f1_mesh = pv.read(f1_list[index])
f1_density = f1_mesh.get_array('Density').reshape([nz, ny, nx])
f1_density = f1_density[:, :, n_slices_start:nx-n_slices_end]
Exemple #19
0
import numpy as np

from geom.geometry3d import rot3d_from_rtp, rot3d_from_z_vec, rot3d_from_x_vec
import vedo
import trimesh
import pyvista as pv
import cv2 as cv

plt1 = vedo.Plotter(title='Confirm Perch Location',
                    pos=[0, 0],
                    interactive=True,
                    sharecam=False)
plt2 = vedo.Plotter(title='Simulated Camera View',
                    sharecam=False,
                    pos=[800, 0],
                    size=[1155.5, 650],
                    interactive=False)

approved = False
user_responded = False


def confirm_perch_placement(environment, placed_cameras, focus_id):
    global approved
    global user_responded

    plt1.keyPressFunction = perch_keyfunc
    plt1.clear()
    approved = False

    plt2.clear()
Exemple #20
0
def optimize(seg_env_prototype=None,
             target_prototype=None,
             cluster_env_path=None,
             full_env_path=None,
             N_its=1,
             enable_user_confirmation=True,
             preloaded_vars=None,
             visualize_with_vedo=False):

    if preloaded_vars is None:
        env, camera_list, optimization_options, pso_options = initialize(
            seg_env_prototype,
            target_prototype,
            cluster_env_path,
            full_env_path,
            load_full_env=True)

        if enable_user_confirmation:
            # surface_confirmation.confirm_surfaces(environment=env, N_max=10)
            surface_confirmation_demo.confirm_surfaces(environment=env,
                                                       N_max=10)
        env.post_process_environment()

        preloaded_vars = {
            'env': copy.deepcopy(env),
            'camera_list': copy.deepcopy(camera_list),
            'optimization_options': copy.deepcopy(optimization_options),
            'pso_options': copy.deepcopy(pso_options)
        }

        # SAVE THIS!
        pickle_env = open("../test/preloaded_environment_apartment.p", 'wb')
        pickle.dump(preloaded_vars, pickle_env)
        pickle_env.close()

    else:
        # work around to the seg fault issue... load everything in advance, then just pass it in!
        env = preloaded_vars['env']
        camera_list = initialize_camera_list()
        optimization_options = initialize_opt_options()
        pso_options = initialize_pso_options()

        env.vedo_mesh = vedo.mesh.Mesh(env.obs_mesh)
        env.opt_options = optimization_options
        env.correct_normals()
        env.n_points = optimization_options.n_points
        env.generate_integration_points()
        env.perch_regions = []
        env.perch_area = 0
        env.set_surface_as_perchable()
        optimization_options.log_performance = False

    # env.plot_environment()

    # PSO:
    # base dimension for simple 2d problem is 2. scales up depending on selected opt
    camera_particle_dimension = optimization_options.get_particle_size()
    n_cams = len(camera_list)
    N_iterations = pso_options["N_iterations"]
    N_particles = pso_options["N_particles"]

    if pso_options["greedy_search"]:
        particle_dimension = camera_particle_dimension
        num_optimizations = n_cams
    else:
        particle_dimension = n_cams * camera_particle_dimension
        num_optimizations = 1

    # for logging
    pso_keypoints = np.zeros([N_its, num_optimizations, N_iterations, 3])
    optimization_options.search_time = np.zeros(
        [N_its, num_optimizations, N_iterations + 1])
    optimization_options.best_fitness = np.zeros(
        [N_its, num_optimizations, N_iterations + 1])
    optimization_options.pts_searched = np.zeros(
        [N_its, num_optimizations, N_iterations + 1])

    bounds = (np.zeros(particle_dimension), np.ones(particle_dimension)
              )  # particle boundaries

    # for velocity update:
    # 'w' is velocity decay aka inertia,
    # 'c1' is "cognitive parameter", e.g. attraction to particle best,
    # 'c2' is "social parameter", e.g. attraction to local/global best
    # 'k' = number of neighbors to consider
    # 'p' = the Minkowski p-norm. 1 for absolute val dist, 2 for norm dist
    options = {
        'c1': pso_options["pso_c1"],
        'c2': pso_options["pso_c2"],
        'w': pso_options["pso_w"],
        'k': pso_options["pso_k"],
        'p': pso_options["pso_p"]
    }

    optimal_cameras = PlacedCameras()

    fig_num = 1

    if pso_options['individual_surface_opt']:
        num_surface_loops = len(env.perch_regions)
        surface_number = range(num_surface_loops)
        N_particles = env.assign_particles_to_surfaces(
            N_particles,
            pso_options["pso_k"],
            neighborhood_search=pso_options["local_search"])
    else:
        num_surface_loops = 1
        surface_number = [-1]
        N_particles = [N_particles]

    # STORE FOR ANALYSIS LATER
    if optimization_options.log_performance:
        pso_best_fitnesses = np.zeros(num_optimizations)
        pso_points_searched = np.zeros(num_optimizations)
        pso_search_time = np.zeros(num_optimizations)
        pso_keypoints = []
        for i in range(num_optimizations):
            pso_keypoints.append([[], [], [], []])

    # store, for each optimization, time, num particles searched, fitness, standard deviation
    bh = pso_options["boundary_handling"]

    # for i in range(num_optimizations):
    i = 0
    while i < num_optimizations:
        if optimization_options.log_performance:
            optimization_options.data_index = 0
        start_time = datetime.now()

        if pso_options["greedy_search"]:
            search_cameras_list = [copy.deepcopy(camera_list[i])]
        else:
            search_cameras_list = camera_list

        best_cost = np.finfo(float).max
        best_pos_surf = -1
        best_pos = np.zeros(particle_dimension)

        for j in range(num_surface_loops):
            # Future work: investigate velocity clamping...
            optimization_options.surface_number = j
            # if pso_options["local_search"]:
            #     optimizer = ps.single.LocalBestPSO(n_particles=N_particles[j], dimensions=particle_dimension,
            #                                        options=options, bounds=bounds, bh_strategy=bh)
            # else:
            #     optimizer = ps.single.GlobalBestPSO(n_particles=N_particles[j], dimensions=particle_dimension,
            #                                         options=options, bounds=bounds, bh_strategy=bh)

            optimization_options.surface_number = surface_number[j]
            # this flag gets reset if the current search has too little variance
            optimization_options.continue_searching = True
            optimization_options.stagnant_loops = 0

            if visualize_with_vedo:
                plt1 = vedo.Plotter(title='Confirm Perch Location',
                                    pos=[0, 0],
                                    interactive=False,
                                    sharecam=False)
                plt1.clear()

                # draw wireframe lineset of camera frustum
                # env_mesh = trimesh.load(env.full_env_path)

                env_mesh = trimesh.load(
                    '/home/simon/catkin_ws/src/mesh_partition/datasets/' +
                    env.name + '_1m_pt1.ply')

                R = np.zeros([4, 4])
                R[:3, :3] = env.R
                env_mesh.vertices = trimesh.transform_points(
                    env_mesh.vertices, R)
                env_mesh_vedo = vedo.mesh.Mesh(env_mesh)
                target_mesh_pymesh = env.generate_target_mesh(shape='box')
                target_mesh = trimesh.Trimesh(target_mesh_pymesh.vertices,
                                              target_mesh_pymesh.faces)
                target_mesh_vedo = vedo.mesh.Mesh(target_mesh)
                target_colors = 0.5 * np.ones([len(target_mesh.faces), 4])
                target_colors[:, 0] *= 0
                target_colors[:, 2] *= 0
                target_mesh_vedo.alpha(0.6)
                target_mesh_vedo.cellIndividualColors(target_colors,
                                                      alphaPerCell=True)
                env_mesh.visual.face_colors[:, -1] = 255
                env_mesh_vedo.cellIndividualColors(
                    env_mesh.visual.face_colors / 255, alphaPerCell=True)

                geom_list = [env_mesh_vedo, target_mesh_vedo]

                if env.name == 'office3' or env.name == 'apartment':
                    env_mesh2 = trimesh.load(
                        '/home/simon/catkin_ws/src/mesh_partition/datasets/' +
                        env.name + '_1m_pt2.ply')
                    env_mesh_vedo2 = vedo.mesh.Mesh(env_mesh2)

                    env_mesh2.visual.face_colors[:, -1] = 150
                    env_mesh_vedo2.cellIndividualColors(
                        env_mesh2.visual.face_colors / 255, alphaPerCell=True)
                    geom_list.append(env_mesh_vedo2)

                for s in env.perch_regions:
                    surf_mesh = trimesh.Trimesh(vertices=s.points,
                                                faces=s.faces)
                    vedo_surf_mesh = vedo.mesh.Mesh(surf_mesh)
                    vedo_surf_mesh.color('g')
                    vedo_surf_mesh.opacity(0.7)
                    geom_list.append(vedo_surf_mesh)

                for i_ in range(len(optimal_cameras.cameras)):
                    quad_mesh = trimesh.load(
                        "/home/simon/catkin_ws/src/perch_placement/src/ui/models/white-red-black_quad2.ply"
                    )
                    R = rot3d_from_x_vec(
                        optimal_cameras.cameras[i_].wall_normal)
                    R2 = rot3d_from_rtp(np.array([0, -90, 0]))
                    R_aug = np.zeros([4, 4])
                    R_aug[:3, :3] = R.dot(R2)
                    R_aug[:3, -1] = optimal_cameras.cameras[i_].pose[:3]
                    quad_mesh.vertices = trimesh.transform_points(
                        quad_mesh.vertices, R_aug)
                    quad_mesh_vedo = vedo.mesh.Mesh(quad_mesh)
                    quad_mesh_vedo.cellIndividualColors(
                        quad_mesh.visual.face_colors / 255, alphaPerCell=True)

                    pymesh_frustum = optimal_cameras.cameras[
                        i_].generate_discrete_camera_mesh(degrees_per_step=20,
                                                          environment=env)
                    pymesh_verts = pymesh_frustum.vertices.copy()
                    pymesh_verts.flags.writeable = True
                    pymesh_faces = pymesh_frustum.faces.copy()
                    pymesh_faces.flags.writeable = True

                    frustum = trimesh.Trimesh(
                        vertices=pymesh_frustum.vertices.copy(),
                        faces=pymesh_frustum.faces.copy())
                    vedo_frustum = vedo.mesh.Mesh(frustum)
                    vedo_frustum.alpha(0.3)
                    vedo_frustum.color("b")
                    quad_mesh_vedo.color('o')
                    geom_list.append(quad_mesh_vedo)
                    geom_list.append(vedo_frustum)

                for actor in geom_list:
                    plt1.add(actor)
            else:
                plt1 = None

            # if pso_options["multi_threading"]:
            #     # noinspection PyTypeChecker
            #     surf_best_cost, surf_best_pos = optimizer.optimize(evaluate_swarm, iters=N_iterations, environment=env,
            #                                                        cameras=search_cameras_list,
            #                                                        placed_cameras=optimal_cameras,
            #                                                        opt_options=optimization_options,
            #                                                        n_processes=multiprocessing.cpu_count(),
            #                                                        vedo_plt=plt1)
            # else:
            #     surf_best_cost, surf_best_pos = optimizer.optimize(evaluate_swarm, iters=N_iterations, environment=env,
            #                                                        cameras=search_cameras_list,
            #                                                        placed_cameras=optimal_cameras,
            #                                                        opt_options=optimization_options,
            #                                                        vedo_plt=plt1)

            pso_params = PSO_Hyperparameters(w=pso_options["pso_w"],
                                             c1=pso_options["pso_c1"],
                                             c2=pso_options["pso_c2"],
                                             lr=1,
                                             k=pso_options["pso_k"],
                                             p=pso_options["pso_p"],
                                             N_particles=N_particles[j],
                                             N_iterations=N_iterations)

            surf_best_cost, surf_best_pos = run_pso(
                fitness_function=evaluate_swarm,
                pso_hyper_parameters=pso_params,
                environment=env,
                cameras=search_cameras_list,
                placed_cameras=optimal_cameras,
                opt_options=optimization_options,
                local_pso=True)

            if surf_best_cost < best_cost:
                best_cost = copy.deepcopy(surf_best_cost)
                best_pos = copy.deepcopy(surf_best_pos)
                if pso_options["individual_surface_opt"]:
                    best_pos_surf = j
                # print("Surface " + str(j) + " has lowest cost so far.. ")
                # print("Particle: " + str(best_pos))

        if optimization_options.log_performance:
            pso_search_time[i] = (datetime.now() - start_time).total_seconds()
            pso_best_fitnesses[i] = best_cost

        if pso_options["greedy_search"]:
            search_cameras_list_copy = copy.deepcopy(search_cameras_list)
            optimization_options.surface_number = best_pos_surf
            best_cam = convert_particle_to_state(
                environment=env,
                particle=best_pos,
                cameras=search_cameras_list_copy,
                opt_options=optimization_options)[0]
            optimal_cameras.cameras.append(copy.deepcopy(best_cam))

            if enable_user_confirmation:
                if confirm_perch_placement(
                        environment=env,
                        placed_cameras=optimal_cameras.cameras,
                        focus_id=i):
                    best_cam_covariances = evaluate_camera_covariance(
                        environment=env, cameras=[best_cam])
                    optimal_cameras.append_covariances(best_cam_covariances)
                    i += 1
                else:
                    optimal_cameras.cameras.pop()
                    env.remove_rejected_from_perch_space(camera=best_cam,
                                                         r=0.3)
            else:
                best_cam_covariances = evaluate_camera_covariance(
                    environment=env, cameras=[best_cam])
                optimal_cameras.append_covariances(best_cam_covariances)
                i += 1

    evaluate_discrete_coverage(env.n_points, optimal_cameras, plot=True)

    return optimal_cameras.cameras
Exemple #21
0
# It would be more correct (API-wise) to call widget.Initialize() and
# widget.Start() here, but Initialize() calls RenderWindow.Render().
# That Render() call will get through before we can setup the
# RenderWindow() to render via the wxWidgets-created context; this
# causes flashing on some platforms and downright breaks things on
# other platforms.  Instead, we call widget.Enable().
widget.Enable(1)
widget.AddObserver("ExitEvent", lambda o,e,f=frame: f.Close())

##################################################### vedo example
def func(evt):
    print("Event dump:\n", evt)
    plt.camera.Azimuth(10) # rotate one camera

cone = vedo.shapes.Cone(c='green8')
axes = vedo.Axes(cone, c='white')
cube = vedo.shapes.Cube()

# Create 2 subwindows with a cone and a cube
plt = vedo.Plotter(N=2, bg='blue2', bg2='blue8', wxWidget=widget)
plt.addCallback("right mouse click", func)
plt.add([cone, axes, "right-click anywhere"], at=0).resetCamera()
plt.add([cube], at=1).resetCamera()
# plt.show() # vedo.show() is now disabled in wx

#####################################################
# Show everything
frame.Show()
app.MainLoop()
Exemple #22
0
##################################################### vedo
def funcMove(event):
    mesh = event.actor
    if not mesh: return

    ptid = mesh.closestPoint(event.picked3d, returnPointId=True)
    txt = f"Probed point:\n{vedo.utils.precision(event.picked3d, 3)}\n" \
          f"value = {vedo.utils.precision(arr[ptid], 2)}"

    vpt = vedo.shapes.Sphere(mesh.points(ptid), r=0.01, c='orange2').pickable(False)
    vig = vpt.vignette(txt, s=.05, offset=(0.5,0.5), font="VictorMono").followCamera()

    msg.text(txt)               # update the 2d text message
    plt.remove(plt.actors[-2:]).add([vpt, vig]) # remove last 2 objects, add the new ones
    widget.Render()             # need to manually call Render

msg = vedo.Text2D(pos='bottom-left', font="VictorMono")
msh = vedo.shapes.ParametricShape("RandomHills").cmap('terrain')
axs = vedo.Axes(msh)
arr = msh.pointdata["Scalars"]

plt = vedo.Plotter(bg='moccasin', bg2='blue9', wxWidget=widget)
plt.add([msh, axs, msg]).resetCamera()
plt.actors += [None,None,None]  # place holder for sphere, vignette, text2d
plt.addCallback('MouseMove', funcMove)

#####################################################
# Show everything
frame.Show()
app.MainLoop()