Ejemplo n.º 1
0
    def setup(self):
        self.settings.New('sample', dtype=str, initial='')
        self.settings.New('z_slice', dtype=float, choices=[0.0], initial=0.0)
        self.settings.New('show_3d', dtype=bool, initial=False)
        self.settings.New('vol_alpha',
                          dtype=float,
                          vmin=0.0,
                          vmax=1.0,
                          initial=0.5)
        self.settings.New('vol_colormap',
                          dtype=str,
                          initial='viridis',
                          choices=[
                              'viridis', 'plasma', 'inferno', 'magma',
                              'cividis', 'Greys', 'Purples', 'Blues', 'Greens',
                              'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd',
                              'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu',
                              'PuBuGn', 'BuGn', 'YlGn'
                          ])
        # self.settings.New('vol_percentile', dtype=int, vmin=0, vmax=49,
        #                   initial=5)
        self.settings.New('vol_percentile_min',
                          dtype=int,
                          vmin=0,
                          vmax=100,
                          initial=5)
        self.settings.New('vol_percentile_max',
                          dtype=int,
                          vmin=0,
                          vmax=100,
                          initial=95)
        self.settings.New('vol_transparent_percentile',
                          dtype=int,
                          vmin=0,
                          vmax=100,
                          initial=5)
        self.settings.New('vol_transparent_min', dtype=bool, initial=False)
        self.settings.z_slice.updated_choice_index_value.connect(
            self.on_update_zslice_choice)
        # self.settings.vol_colormap.updated_value.connect(self.calculate_volume)
        # self.settings.vol_alpha.updated_value.connect(self.calculate_volume)
        HyperSpectralBaseView.setup(self)
        voldata = np.empty((1, 1, 1, 4), dtype=np.ubyte)
        voldata[0, 0, 0, :] = [255, 255, 255, 0]
        self.volitem = GLVolumeItem(data=voldata)
        self.glview = GLViewWidget()
        self.glaxis = GLAxisItem()
        self.glgrid = GLGridItem()
        self.glview.addItem(self.glgrid)
        self.glview.addItem(self.glaxis)
        self.glview.addItem(self.volitem)
        self.gldock = self.dockarea.addDock(name='3D',
                                            widget=self.glview,
                                            position='below',
                                            relativeTo=self.image_dock)

        self.calculate_3d_pushButton = QPushButton(text='calculate_3d')
        self.settings_ui.layout().addWidget(self.calculate_3d_pushButton)
        self.calculate_3d_pushButton.clicked.connect(self.calculate_volume)
        self.image_dock.raiseDock()
Ejemplo n.º 2
0
    def _refresh_grid(self):
        if self.grid is not None:
            self.removeItem(self.grid)
            self.grid = None

        if self.orbital is None or not self.options.is_show_grid():
            return

        self.grid = GLGridItem()
        self.grid.setSize(x=8, y=8, z=8)
        self.grid.scale(1 / self.dx, 1 / self.dy, 1 / self.dz)
        self.addItem(self.grid)
Ejemplo n.º 3
0
    def _refresh_grid(self):
        if self.grid is not None:
            self.removeItem(self.grid)
            self.grid = None

        if self.orbital is None or not self.options.is_show_grid():
            return

        self.grid = GLGridItem()
        dx, dy, dz = [self.orbital.psi[key] for key in ['dx', 'dy', 'dz']]
        self.grid.scale(1 / dx, 1 / dy, 1 / dz)
        self.addItem(self.grid)
Ejemplo n.º 4
0
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        xgrid, ygrid, zgrid = (GLGridItem() for i in range(3))
        xgrid.rotate(90, 0, 1, 0)
        ygrid.rotate(90, 1, 0, 0)
        self.plot = GLScatterPlotItem(pos=np.asarray([0, 0, 0]))
        self.graphicsView.addItem(self.plot)
        self.graphicsView.addItem(xgrid)
        self.graphicsView.addItem(ygrid)
        self.graphicsView.addItem(zgrid)
        self.graphicsView.setBackgroundColor((111, 111, 111))

        self.tweets = TweetStream(self)
        self.tweets.svd_signal.connect(self.processSVD)
        self.tweets.twt_signal.connect(self.processTweet)

        self.started = False
        self.pushButton.clicked.connect(self.processStartStop)

        self.show()
Ejemplo n.º 5
0
    def _create_grid(self):
        from pyqtgraph.opengl import GLGridItem

        gx = GLGridItem()
        gx.rotate(90, 0, 1, 0)
        gx.translate(-10, 0, 0)
        self.widget.addItem(gx)
        gy = GLGridItem()
        gy.rotate(90, 1, 0, 0)
        gy.translate(0, -10, 0)
        self.widget.addItem(gy)
        gz = GLGridItem()
        gz.translate(0, 0, -10)
        self.widget.addItem(gz)
Ejemplo n.º 6
0
 def _create_grid(self):
     from pyqtgraph.opengl import GLGridItem
     gx = GLGridItem()
     gx.rotate(90, 0, 1, 0)
     gx.translate(-10, 0, 0)
     self.widget.addItem(gx)
     gy = GLGridItem()
     gy.rotate(90, 1, 0, 0)
     gy.translate(0, -10, 0)
     self.widget.addItem(gy)
     gz = GLGridItem()
     gz.translate(0, 0, -10)
     self.widget.addItem(gz)
Ejemplo n.º 7
0
class MiniRealSpacePlot(GLViewWidget):
    def __init__(self, *args, **kwargs):

        self.options = None
        self.grid = None
        self.bonds = []
        self.photon = None
        self.photon_parameters = ['p', 45, 0]
        self.mesh = []
        self.orbital = None
        self.orientation = [0, 0, 0]

        super(MiniRealSpacePlot, self).__init__(*args, **kwargs)
        self._setup()

        self.show()

    def set_orbital(self, orbital):

        self.orbital = orbital
        self.orientation = [0, 0, 0]

        self.refresh_plot()

    def set_options(self, options):

        self.options = options
        self._connect()

    def rotate_orbital(self, phi=0, theta=0, psi=0):

        old_axes = get_rotation_axes(*self.orientation[:2])
        new_axes = get_rotation_axes(phi, theta)
        for item in chain(self.bonds, self.mesh):
            # Undo current orientation
            self._rotate_item(item, old_axes, *self.orientation, backward=True)
            # Actuallly rotate to new orientation
            self._rotate_item(item, new_axes, phi, theta, psi, backward=False)

        self.orientation = [phi, theta, psi]

    def rotate_photon(self, polarization='p', alpha=0, beta=0):

        if self.photon is not None:
            self.removeItem(self.photon)
            self.photon = None

        self.photon_parameters = [polarization, alpha, beta]
        self._refresh_photon()

    def refresh_plot(self):

        self._refresh_grid()
        self._refresh_bonds()
        self._refresh_photon()
        self._refresh_mesh()

    def reset_camera(self, distance=75, elevation=90, azimuth=-90):

        # View from top
        self.setCameraPosition(distance=distance,
                               elevation=elevation,
                               azimuth=azimuth)

    def toggle_show_grid(self, state):

        if self.grid is not None:
            self.grid.setVisible(state)

    def toggle_show_bonds(self, state):

        if self.bonds:
            for bond in self.bonds:
                bond.setVisible(state)

    def toggle_show_photon(self, state):

        if self.photon is not None:
            self.photon.setVisible(state)

    def toggle_show_mesh(self, state):

        if self.mesh:
            for mesh in self.mesh:
                mesh.setVisible(state)

    def wheelEvent(self, event, *args, **kwargs):

        event.accept()

        super().wheelEvent(event, *args, **kwargs)

    def _refresh_mesh(self):

        if self.mesh:
            for mesh in self.mesh:
                self.removeItem(mesh)

            self.mesh = []

        if self.orbital is None or not self.options.is_show_mesh():
            return

        data = self.orbital.psi['data']
        plus_mesh = self._get_iso_mesh(data, 'red', 1)
        minus_mesh = self._get_iso_mesh(data, 'blue', -1)
        self.addItem(plus_mesh)
        self.addItem(minus_mesh)

        self.mesh = [plus_mesh, minus_mesh]

        # Updating the mesh after iso val change would leave it
        # unrotated
        axes = get_rotation_axes(*self.orientation[:2])
        for item in self.mesh:
            self._rotate_item(item, axes, *self.orientation, backward=False)

    def _refresh_bonds(self):

        if self.bonds:
            for bond in self.bonds:
                self.removeItem(bond)

            self.bonds = []

        if self.orbital is None or not self.options.is_show_bonds():
            return

        color = (0.8, 0.8, 0.8, 1)  # light gray

        for bond in self.orbital.get_bonds():
            new_bond = GLLinePlotItem(pos=bond,
                                      color=color,
                                      width=5,
                                      antialias=True)
            self.bonds.append(new_bond)

            self.addItem(new_bond)

    def _refresh_photon(self):

        # Couldn't find the bug without second part of if so I removed
        # it for now
        if self.photon:
            self.removeItem(self.photon)
            self.photon = None

        polarization, alpha, beta = self.photon_parameters

        if self.orbital is None or not self.options.is_show_photon():
            return

        color = (1, 1, 0.0, 1)  # color for wavy light ray (yellow)
        ray_length = 50  # length of wavy light ray
        amplitude = 5  # amplitude of oscillation
        wavelength = 5  # wavelength of oscillation
        n_points = 200  # number of points along wavy light ray

        alpha = alpha * np.pi / 180
        beta = (180 + beta) * np.pi / 180
        direction = [
            np.sin(alpha) * np.cos(beta),
            np.sin(alpha) * np.sin(beta),
            np.cos(alpha)
        ]

        x0 = np.linspace(0, ray_length * direction[0], n_points)
        y0 = np.linspace(0, ray_length * direction[1], n_points)
        z0 = np.linspace(0, ray_length * direction[2], n_points)
        t = np.linspace(0, ray_length, n_points)

        if polarization == 's':
            pol_1 = [np.sin(beta), -np.cos(beta), 0]
            pol_2 = [0, 0, 0]

        elif polarization == 'p':
            pol_1 = [0, 0, 0]
            pol_2 = [
                np.cos(alpha) * np.cos(beta),
                np.cos(alpha) * np.sin(beta), -np.sin(alpha)
            ]

        # ... to be updated ...
        elif polarization == 'unpolarized':
            pol_1 = [0, 0, 0]
            pol_2 = [
                np.sin(beta) + np.cos(alpha) * np.cos(beta),
                -np.cos(beta) + np.cos(alpha) * np.sin(beta), -np.sin(alpha)
            ]

        elif polarization == 'C+':
            pol_1 = [np.sin(beta), -np.cos(beta), 0]
            pol_2 = [
                np.cos(alpha) * np.cos(beta),
                np.cos(alpha) * np.sin(beta), -np.sin(alpha)
            ]

        elif polarization == 'C-':
            pol_1 = [np.sin(beta), -np.cos(beta), 0]
            pol_2 = [
                -np.cos(alpha) * np.cos(beta), -np.cos(alpha) * np.sin(beta),
                +np.sin(alpha)
            ]

        # show C+ spiral ... until I have a better idea ...
        elif polarization == 'CDAD':
            pol_1 = [np.sin(beta), -np.cos(beta), 0]
            pol_2 = [
                np.cos(alpha) * np.cos(beta),
                np.cos(alpha) * np.sin(beta), -np.sin(alpha)
            ]

        dx = amplitude * pol_1[0] * np.cos(2 * np.pi * t / wavelength) + \
            amplitude * pol_2[0] * np.sin(2 * np.pi * t / wavelength)
        dy = amplitude * pol_1[1] * np.cos(2 * np.pi * t / wavelength) + \
            amplitude * pol_2[1] * np.sin(2 * np.pi * t / wavelength)
        dz = amplitude * pol_1[2] * np.cos(2 * np.pi * t / wavelength) + \
            amplitude * pol_2[2] * np.sin(2 * np.pi * t / wavelength)

        pos = np.array([x0 + dx, y0 + dy, z0 + dz]).T

        photon_line = GLLinePlotItem(pos=pos,
                                     color=color,
                                     width=5,
                                     antialias=True)
        photon_line.setGLOptions('translucent')
        self.photon = photon_line
        self.addItem(photon_line)

    def _refresh_grid(self):

        if self.grid is not None:
            self.removeItem(self.grid)
            self.grid = None

        if self.orbital is None or not self.options.is_show_grid():
            return

        self.grid = GLGridItem()
        dx, dy, dz = [self.orbital.psi[key] for key in ['dx', 'dy', 'dz']]
        self.grid.scale(1 / dx, 1 / dy, 1 / dz)
        self.addItem(self.grid)

    def _rotate_item(self, item, axes, phi, theta, psi, backward=False):

        if backward:
            # Undo Rotation in reverse order
            item.rotate(psi, axes[2][0], axes[2][1], axes[2][2], local=True)
            item.rotate(theta, axes[1][0], axes[1][1], axes[1][2], local=True)
            item.rotate(phi, axes[0][0], axes[0][1], axes[0][2], local=True)

        else:
            item.rotate(-phi, axes[0][0], axes[0][1], axes[0][2], local=True)
            item.rotate(-theta, axes[1][0], axes[1][1], axes[1][2], local=True)
            item.rotate(-psi, axes[2][0], axes[2][1], axes[2][2], local=True)

    def _get_iso_mesh(self, data, color, sign):

        iso_val = sign * self.options.get_iso_val()
        vertices, faces = isosurface(data, iso_val * data.max())
        nx, ny, nz = data.shape

        # Center Isosurface around Origin
        vertices[:, 0] = vertices[:, 0] - nx / 2
        vertices[:, 1] = vertices[:, 1] - ny / 2
        vertices[:, 2] = vertices[:, 2] - nz / 2

        mesh_data = MeshData(vertexes=vertices, faces=faces)
        colors = np.zeros((mesh_data.faceCount(), 4), dtype=float)
        # Sets color to Red (RGB, 0 = red, 1 = green, 2 = blue)
        if color == 'red':
            colors[:, 0] = 1.0
            colors[:, 1] = 0.2
            colors[:, 2] = 0.2

        elif color == 'blue':
            colors[:, 0] = 0.2
            colors[:, 1] = 0.2
            colors[:, 2] = 1.0
        # Transparency (I guess)
        colors[:, 3] = 1
        mesh_data.setFaceColors(colors)

        mesh = GLMeshItem(meshdata=mesh_data,
                          smooth=True,
                          shader='edgeHilight')
        mesh.setGLOptions('translucent')

        return mesh

    def _setup(self):

        # Set Fixed Size. Due to some unknown reason subclassing from a
        # second class like FixedSizeWidget while also
        # subclassing from gl.GLViewWidget throws error
        width = 275
        ratio = 1
        height = width * ratio
        self.resize(width, height)
        self.setMaximumSize(width, height)
        self.setMinimumSize(width, height)

        self.reset_camera()

    def _connect(self):

        self.options.set_camera.connect(self.reset_camera)
        self.options.show_grid_changed.connect(self.toggle_show_grid)
        self.options.show_mesh_changed.connect(self.toggle_show_mesh)
        self.options.show_bonds_changed.connect(self.toggle_show_bonds)
        self.options.show_photon_changed.connect(self.toggle_show_photon)
        self.options.iso_val_changed.connect(self._refresh_mesh)
Ejemplo n.º 8
0
class Mini3DKSpacePlot(GLViewWidget):
    def __init__(self, *args, **kwargs):

        self.ID = None
        self.options = None
        self.grid = None
        self.hemisphere = None
        self.mesh = None
        self.orbital = None
        self.orientation = [0, 0, 0]
        self.E_kin = 30

        super(Mini3DKSpacePlot, self).__init__(*args, **kwargs)
        self._setup()

        self.show()

    def set_orbital(self, orbital, ID):

        self.ID = ID
        self.orbital = orbital
        self.orientation = [0, 0, 0]

        self.refresh_plot()

    def set_options(self, options):

        self.options = options
        self._connect()

    def rotate_orbital(self, phi=0, theta=0, psi=0):

        old_axes = get_rotation_axes(*self.orientation[:2])
        new_axes = get_rotation_axes(phi, theta)

        # Undo current orientation
        self._rotate_item(self.mesh,
                          old_axes,
                          *self.orientation,
                          backward=True)
        # Actuallly rotate to new orientation
        self._rotate_item(self.mesh, new_axes, phi, theta, psi, backward=False)

        self.orientation = [phi, theta, psi]

    def change_energy(self, E_kin):

        self.E_kin = E_kin

        self._refresh_hemisphere()

    def refresh_plot(self):

        self._refresh_hemisphere()
        self._refresh_grid()
        self._refresh_mesh()

    def reset_camera(self, distance=75, elevation=90, azimuth=-90):

        # View from top
        self.setCameraPosition(distance=distance,
                               elevation=elevation,
                               azimuth=azimuth)

    def toggle_show_grid(self, state):

        if self.grid is not None:
            self.grid.setVisible(state)

    def toggle_show_hemisphere(self, state):

        if self.hemisphere is not None:
            self.hemisphere.setVisible(state)

    def _refresh_mesh(self):

        if self.mesh is not None:
            self.removeItem(self.mesh)

            self.mesh = None

        if self.orbital is None:
            return

        data = self.orbital.psik['data']
        self.mesh = self._get_iso_mesh(data)
        self.addItem(self.mesh)

        # Updating the mesh after iso val change would leave it
        # unrotated
        axes = get_rotation_axes(*self.orientation[:2])
        self._rotate_item(self.mesh, axes, *self.orientation, backward=False)

    def wheelEvent(self, event, *args, **kwargs):

        event.accept()

        super().wheelEvent(event, *args, **kwargs)

    def _refresh_hemisphere(self):

        if self.hemisphere is not None:
            self.removeItem(self.hemisphere)
            self.hemisphere = None

        if self.orbital is None or not self.options.is_show_hemisphere():
            return

        k = energy_to_k(self.E_kin)
        kx, ky, kz = [self.orbital.psik[key] for key in ['kx', 'ky', 'kz']]
        self.dx, self.dy, self.dz = [
            kx[1] - kx[0], ky[1] - ky[0], kz[1] - kz[0]
        ]

        # this produces a hemisphere using the GLSurfacePlotItem, however,
        # the resulting hemisphere appears a little ragged at the circular
        # boundary
        #x = np.linspace(-k / self.dx, k / self.dx, 200)
        #y = np.linspace(-k / self.dy, k / self.dy, 200)
        #X, Y = np.meshgrid(x, y)
        #Z = np.sqrt(k**2 / (self.dx * self.dy) - X**2 - Y**2)

        # self.hemisphere = GLSurfacePlotItem(x=x, y=y, z=Z, color=(
        #    0.5, 0.5, 0.5, 0.7), shader='edgeHilight')
        # self.hemisphere.setGLOptions('translucent')

        # NEW method:
        nz = len(kz)
        X, Y, Z = np.meshgrid(kx / self.dx, ky / self.dy,
                              kz[nz // 2:] / self.dz)
        data = X**2 + Y**2 + Z**2
        iso = k**2 / (self.dx * self.dy)
        color = (0.5, 0.5, 0.5, 0.8)
        self.hemisphere = self._get_iso_mesh(data, iso, color, z_shift=False)

        self.addItem(self.hemisphere)

    def _refresh_grid(self):

        if self.grid is not None:
            self.removeItem(self.grid)
            self.grid = None

        if self.orbital is None or not self.options.is_show_grid():
            return

        self.grid = GLGridItem()
        self.grid.setSize(x=8, y=8, z=8)
        self.grid.scale(1 / self.dx, 1 / self.dy, 1 / self.dz)
        self.addItem(self.grid)

    def _rotate_item(self, item, axes, phi, theta, psi, backward=False):

        if backward:
            # Undo Rotation in reverse order
            item.rotate(psi, axes[2][0], axes[2][1], axes[2][2], local=True)
            item.rotate(theta, axes[1][0], axes[1][1], axes[1][2], local=True)
            item.rotate(phi, axes[0][0], axes[0][1], axes[0][2], local=True)

        else:
            item.rotate(-phi, axes[0][0], axes[0][1], axes[0][2], local=True)
            item.rotate(-theta, axes[1][0], axes[1][1], axes[1][2], local=True)
            item.rotate(-psi, axes[2][0], axes[2][1], axes[2][2], local=True)

    def _get_iso_mesh(self,
                      data,
                      iso=None,
                      color=(1, 0.2, 0.2, 1),
                      z_shift=True):

        if iso is None:
            iso_val = self.options.get_iso_val() * data.max()
        else:
            iso_val = iso

        vertices, faces = isosurface(data, iso_val)
        nx, ny, nz = data.shape

        # Center Isosurface around Origin
        vertices[:, 0] = vertices[:, 0] - nx / 2
        vertices[:, 1] = vertices[:, 1] - ny / 2
        if z_shift:
            vertices[:, 2] = vertices[:, 2] - nz / 2

        mesh_data = MeshData(vertexes=vertices, faces=faces)
        colors = np.zeros((mesh_data.faceCount(), 4), dtype=float)
        for idx in range(4):
            colors[:, idx] = color[idx]

        mesh_data.setFaceColors(colors)

        mesh = GLMeshItem(meshdata=mesh_data,
                          smooth=True,
                          shader='edgeHilight')
        mesh.setGLOptions('translucent')

        return mesh

    def _setup(self):

        # Set Fixed Size. Due to some unknown reason subclassing from a
        # second class like FixedSizeWidget while also
        # subclassing from gl.GLViewWidget throws error
        width = 275
        ratio = 1
        height = width * ratio
        self.resize(width, height)
        self.setMaximumSize(width, height)
        self.setMinimumSize(width, height)

        self.reset_camera()

    def _connect(self):

        self.options.set_camera.connect(self.reset_camera)
        self.options.show_grid_changed.connect(self.toggle_show_grid)
        self.options.show_hemisphere_changed.connect(
            self.toggle_show_hemisphere)
        self.options.iso_val_changed.connect(self._refresh_mesh)
Ejemplo n.º 9
0
class HyperSpec3DH5View(HyperSpectralBaseView):

    name = 'hyperspec_3d_h5'

    supported_measurements = [
        'oo_asi_hyperspec_3d_scan',
        'andor_asi_hyperspec_3d_scan',
    ]

    def scan_specific_setup(self):
        pass

    def setup(self):
        self.settings.New('sample', dtype=str, initial='')
        self.settings.New('z_slice', dtype=float, choices=[0.0], initial=0.0)
        self.settings.New('show_3d', dtype=bool, initial=False)
        self.settings.New('vol_alpha',
                          dtype=float,
                          vmin=0.0,
                          vmax=1.0,
                          initial=0.5)
        self.settings.New('vol_colormap',
                          dtype=str,
                          initial='viridis',
                          choices=[
                              'viridis', 'plasma', 'inferno', 'magma',
                              'cividis', 'Greys', 'Purples', 'Blues', 'Greens',
                              'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd',
                              'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu',
                              'PuBuGn', 'BuGn', 'YlGn'
                          ])
        # self.settings.New('vol_percentile', dtype=int, vmin=0, vmax=49,
        #                   initial=5)
        self.settings.New('vol_percentile_min',
                          dtype=int,
                          vmin=0,
                          vmax=100,
                          initial=5)
        self.settings.New('vol_percentile_max',
                          dtype=int,
                          vmin=0,
                          vmax=100,
                          initial=95)
        self.settings.New('vol_transparent_percentile',
                          dtype=int,
                          vmin=0,
                          vmax=100,
                          initial=5)
        self.settings.New('vol_transparent_min', dtype=bool, initial=False)
        self.settings.z_slice.updated_choice_index_value.connect(
            self.on_update_zslice_choice)
        # self.settings.vol_colormap.updated_value.connect(self.calculate_volume)
        # self.settings.vol_alpha.updated_value.connect(self.calculate_volume)
        HyperSpectralBaseView.setup(self)
        voldata = np.empty((1, 1, 1, 4), dtype=np.ubyte)
        voldata[0, 0, 0, :] = [255, 255, 255, 0]
        self.volitem = GLVolumeItem(data=voldata)
        self.glview = GLViewWidget()
        self.glaxis = GLAxisItem()
        self.glgrid = GLGridItem()
        self.glview.addItem(self.glgrid)
        self.glview.addItem(self.glaxis)
        self.glview.addItem(self.volitem)
        self.gldock = self.dockarea.addDock(name='3D',
                                            widget=self.glview,
                                            position='below',
                                            relativeTo=self.image_dock)

        self.calculate_3d_pushButton = QPushButton(text='calculate_3d')
        self.settings_ui.layout().addWidget(self.calculate_3d_pushButton)
        self.calculate_3d_pushButton.clicked.connect(self.calculate_volume)
        self.image_dock.raiseDock()

    def is_file_supported(self, fname):
        return np.any([(meas_name in fname)
                       for meas_name in self.supported_measurements])

    def reset(self):
        if hasattr(self, 'dat'):
            self.dat.close()
            del self.dat

        if hasattr(self, 'spec_map'):
            del self.spec_map

        if hasattr(self, 'scalebar'):
            self.imview.getView().removeItem(self.scalebar)
            del self.scalebar

        if hasattr(self, 'volume'):
            spoof_data = np.zeros((1, 1, 1, 4), dtype=np.ubyte)
            self.volitem.setData(spoof_data)
            del self.volume

        self.settings.show_3d.update_value(False)
        self.image_dock.raiseDock()

    def load_data(self, fname):
        self.dat = h5py.File(fname)
        for meas_name in self.supported_measurements:
            if meas_name in self.dat['measurement']:
                self.M = self.dat['measurement'][meas_name]

        for map_name in ['hyperspectral_map', 'spec_map']:
            if map_name in self.M:
                self.spec_map = np.array(self.M[map_name])
                self.h_span = self.M['settings'].attrs['h_span']
                self.x_array = np.array(self.M['h_array'])
                self.z_array = np.array(self.M['z_array'])
                units = self.M['settings/units'].attrs['h_span']
                if units == 'mm':
                    self.h_span = self.h_span * 1e-3
                    self.z_span = self.z_array * 1e-3
                    self.settings.z_slice.change_unit('mm')

                if 'dark_indices' in list(self.M.keys()):
                    print('dark indices found')
                    dark_indices = self.M['dark_indices']
                    if dark_indices.len() == 0:
                        self.spec_map = np.delete(self.spec_map,
                                                  list(dark_indices.shape), -1)
                    else:
                        self.spec_map = np.delete(self.spec_map,
                                                  np.array(dark_indices), -1)
                else:
                    print('no dark indices')

        self.hyperspec_data = self.spec_map[0, :, :, :]
        self.display_image = self.hyperspec_data.sum(axis=-1)
        self.settings.z_slice.change_choice_list(self.z_array.tolist())
        self.settings.z_slice.update_value(self.z_array[0])
        self.spec_x_array = np.arange(self.hyperspec_data.shape[-1])

        for x_axis_name in [
                'wavelength', 'wls', 'wave_numbers', 'raman_shifts'
        ]:
            if x_axis_name in self.M:
                x_array = np.array(self.M[x_axis_name])
                if 'dark_indices' in list(self.M.keys()):
                    dark_indices = self.M['dark_indices']
                    # The following is to read a dataset I initialized
                    # incorrectly for dark pixels. This can be replaced with
                    # the else statement entirely now that the measurement is
                    # fixed, but I still have a long measurement that will
                    # benefit from this.
                    if dark_indices.len() == 0:
                        x_array = np.delete(x_array, list(dark_indices.shape),
                                            0)
                    else:
                        x_array = np.delete(x_array, np.array(dark_indices), 0)
                self.add_spec_x_array(x_axis_name, x_array)
                self.x_axis.update_value(x_axis_name)

        sample = self.dat['app/settings'].attrs['sample']
        self.settings.sample.update_value(sample)
        self.calculate_volume()

    def on_update_zslice_choice(self, index):
        if hasattr(self, 'spec_map'):
            self.hyperspec_data = self.spec_map[index, :, :, :]
            self.display_images['default'] = self.hyperspec_data
            self.display_images['sum'] = self.hyperspec_data.sum(axis=-1)
            self.spec_x_arrays['default'] = self.spec_x_array
            self.spec_x_arrays['index'] = np.arange(
                self.hyperspec_data.shape[-1])
            self.recalc_bandpass_map()
            self.recalc_median_map()
            self.update_display()

    def calculate_volume(self):
        if not self.settings['show_3d']:
            print('calculate_volume called without show_3d')
            return

        print('calculating 3d volume')
        t0 = time.time()

        if hasattr(self, 'volume'):
            del self.volume

        if hasattr(self, 'mappable'):
            self.mappable.set_cmap(self.settings['vol_colormap'])
        else:
            self.mappable = ScalarMappable(cmap=self.settings['vol_colormap'])

        z_span = self.z_array[-1] - self.z_array[0]
        dx = self.x_array[1] - self.x_array[0]
        z_interp_array = np.linspace(np.amin(self.z_array),
                                     np.amax(self.z_array),
                                     num=z_span / dx)
        z_interp = None
        self.volume = None
        nz = len(z_interp_array)

        if self.settings['display_image'] == 'bandpass_map':
            print('bandpass_map selected')
            x, slice = self.get_xhyperspec_data(apply_use_x_slice=True)
            ind_min = np.nonzero(self.spec_x_array == x[0])[0][0]
            ind_max = np.nonzero(self.spec_x_array == x[-1])[0][0]
            data = np.zeros((len(self.z_array), ) + slice.shape)
            data = self.spec_map[:, :, :, ind_min:ind_max]
            # for kk in range(len(self.z_array)):
            #     print(
            #         'grabbing bandpass layer %d of %d' % (kk, len(self.z_array)))
            #     self.settings.z_slice.update_value(self.z_array[kk])
            #     x, data[kk, :, :, :] = self.get_xhyperspec_data(
            #         apply_use_x_slice=True)
            z_interp = interp1d(self.z_array, data, axis=0)
        else:
            z_interp = interp1d(self.z_array, self.spec_map, axis=0)

        data = z_interp(z_interp_array)
        self.volume = np.zeros(data.shape[:-1] + (4, ), dtype=np.ubyte)

        pmin = self.settings['vol_percentile_min']
        pmax = self.settings['vol_percentile_max']
        self.mappable.set_array(data.sum(axis=-1))
        vmin = np.percentile(data.sum(axis=-1), pmin)
        vmax = np.percentile(data.sum(axis=-1), pmax)
        tmin = np.percentile(data.sum(axis=-1),
                             self.settings['vol_transparent_percentile'])
        self.mappable.set_clim(vmin=vmin, vmax=vmax)
        # self.mappable.autoscale()

        for kk in range(nz):
            print('calculating rgba vals for %d of %d layers' % (kk, nz))
            sum_data = data[kk, :, :, :].sum(axis=-1)
            # print(sum_data.shape, self.volume.shape)
            self.volume[kk, :, :, :] = self.mappable.to_rgba(
                sum_data, alpha=self.settings['vol_alpha'], bytes=True)
            if self.settings['vol_transparent_min']:
                self.volume[kk, :, :, 3][np.nonzero(sum_data <= tmin)] = 0

        print('3d volume calculation complete')
        t1 = time.time()
        print('time elapsed: %0.3f s' % (t1 - t0))

        kwargs = {'x': len(self.x_array), 'y': len(self.x_array), 'z': nz}
        self.glaxis.setSize(**kwargs)
        self.glgrid.setSize(**kwargs)
        self.glgrid.setSpacing(x=1 / dx * 5, y=1 / dx * 5, z=1 / dx * 5)
        # print(self.mappable.get_cmap().name)
        # print(data.shape, self.volume.shape)

    def update_display(self):
        if hasattr(self, 'scalebar'):
            self.imview.getView().removeItem(self.scalebar)

        if self.display_image is not None:
            # pyqtgraph axes are x,y, but data is stored in (frame, y,x, time),
            # so we need to transpose
            self.imview.getImageItem().setImage(self.display_image.T)

            nn = self.display_image.shape

            if hasattr(self, 'h_span'):
                span = self.h_span
            else:
                span = -1
            self.scalebar = ConfocalScaleBar(span=span, num_px=nn[0])
            self.scalebar.setParentItem(self.imview.getView())
            self.scalebar.anchor((1, 1), (1, 1), offset=(-20, -20))

            if hasattr(self, 'volume') and self.settings['show_3d']:
                self.volitem.setData(np.swapaxes(self.volume, 0, 2))

            self.on_change_rect_roi()
            self.on_update_circ_roi()
Ejemplo n.º 10
0
    def init_plot(self):
        axis = GLAxisItem()
        axis.setSize(1000, 1000, 1000)
        self.widget.addItem(axis)
        xgrid = GLGridItem()
        ygrid = GLGridItem()
        zgrid = GLGridItem()

        xgrid.rotate(90, 0, 1, 0)
        ygrid.rotate(90, 1, 0, 0)
        xgrid.setSpacing(10, 10, 10)
        ygrid.setSpacing(10, 10, 10)
        zgrid.setSpacing(10, 10, 10)
        xgrid.setSize(2000, 2000, 2000)
        ygrid.setSize(2000, 2000, 2000)
        zgrid.setSize(2000, 2000, 2000)

        self.widget.addItem(xgrid)
        self.widget.addItem(ygrid)
        self.widget.addItem(zgrid)
        self.widget.addItem(self.letter)
        self.build_projections()
Ejemplo n.º 11
0
        for xi in range(-hsize, hsize + 1):
            for yi in range(-hsize, hsize + 1):
                if xi == -hsize and yi == -hsize:
                    # skip one corner for visual orientation
                    continue
                vec3 = QtGui.QVector3D(xi, yi, 0)
                pos = project.map(vec3).toPointF()
                painter.drawEllipse(pos, 1, 1)


pg.mkQApp("GLPainterItem Example")
glv = GLViewWidget()
glv.show()
glv.setWindowTitle('pyqtgraph example: GLPainterItem')
glv.setCameraPosition(distance=50, elevation=90, azimuth=0)

griditem = GLGridItem()
griditem.setSize(SIZE, SIZE)
griditem.setSpacing(1, 1)
glv.addItem(griditem)

axisitem = GLAxisItem()
axisitem.setSize(SIZE / 2, SIZE / 2, 1)
glv.addItem(axisitem)

paintitem = GLPainterItem()
glv.addItem(paintitem)

if __name__ == '__main__':
    pg.exec()
Ejemplo n.º 12
0
    def __init__(self, args, option='camera'):
        self.args = args
        self.fpsTime = 0
        self.option = option
        self.app = QtGui.QApplication(sys.argv)
        self.window = GLViewWidget()
        self.window.setGeometry(0, 150, 1920, 1080)
        self.window.setCameraPosition(distance=50, elevation=8)
        self.window.setWindowTitle("3D Pose Estimation")
        self.window.show()
        gx = GLGridItem()
        gy = GLGridItem()
        gz = GLGridItem()
        gx.rotate(90, 0, 1, 0)
        gy.rotate(90, 1, 0, 0)
        gx.translate(-10, 0, 0)
        gy.translate(0, -10, 0)
        gz.translate(0, 0, -10)
        self.window.addItem(gx)
        self.window.addItem(gy)
        self.window.addItem(gz)
        self.lines = {}
        keypoints = []
        self.connection = [[0, 1], [1, 2], [2, 3], [0, 4], [4, 5], [5, 6],
                           [0, 7], [7, 8], [8, 9], [9, 10], [8, 11], [11, 12],
                           [12, 13], [8, 14], [14, 15], [15, 16]]
        self.w, self.h = model_wh(self.args.resize)

        if self.w > 0 and self.h > 0:
            self.e = TfPoseEstimator(get_graph_path(self.args.model),
                                     target_size=(self.w, self.h),
                                     trt_bool=str2bool(self.args.tensorrt))
        else:
            self.e = TfPoseEstimator(get_graph_path(self.args.model),
                                     target_size=(432, 368),
                                     trt_bool=str2bool(self.args.tensorrt))

        print(self.args.option)
        image, ret_val = PoseEstimation.getframe(self.args.option)

        self.poseLifting = Prob3dPose(
            'lifting/prob_model/prob_model_params.mat')
        try:

            keypoints = self.mesh(image)
        except AssertionError:
            print("body not in image")
            keypoints = np.zeros((17, 3))
        except Exception:
            print("General exception")
            keypoints = np.zeros((17, 3))

        # self.lines = {}
        # self.connection = [
        #     [13, 16]
        # ]
        # p = []
        # p.append(keypoints[13])
        # p.append(keypoints[16])
        # p = np.array(p)
        finally:
            self.points = GLScatterPlotItem(
                pos=np.array(np.array(keypoints)),
                color=glColor((12, 255, 0)),
                size=15,
            )
            self.window.addItem(self.points)
            for n, pts in enumerate(self.connection):
                self.lines[n] = GLLinePlotItem(pos=np.array(
                    [keypoints[p] for p in pts]),
                                               color=glColor((0, 0, 255)),
                                               width=3,
                                               antialias=True)
                self.window.addItem(self.lines[n])