Ejemplo n.º 1
0
 def __init__(self):
     self.app=QtGui.QApplication(sys.argv)
     self.window = opengl.GLViewWidget()
     self.window.setGeometry(0,410,800,800)
     self.window.setCameraPosition(distance=12,azimuth=270)
     x_axis=opengl.GLGridItem()
     x_axis.setSize(x=10,y=10)
     #y_axis=opengl.GLGridItem()
     #y_axis.rotate(90,0,1,0)
     #self.window.addItem(y_axis)
     self.grid=Cell()
     self.q=Qlearning(no_of_actions,no_of_states,state_combinations)
     self.window.addItem(x_axis)
     self.current_node=self.grid.grid_nodes[0]
     self.nodes=opengl.GLScatterPlotItem(pos=self.grid.grid_nodes,color=glColor((0,255,0)),size=7)
     self.goal=opengl.GLScatterPlotItem(pos=self.grid.goal_node,color=glColor((0,0,255)),size=15)
     self.current_node_item=opengl.GLScatterPlotItem(pos=self.current_node,color=glColor((255,0,0)),size=9)
     self.blocked=opengl.GLScatterPlotItem(pos=self.grid.blocked_nodes,color=glColor((255,255,255)),size=13)
     self.counter=0
     self.generation_counter=0
     self.step_counter=0
     self.tracker=[]
     self.window.addItem(self.nodes)
     self.window.addItem(self.blocked)
     self.window.addItem(self.current_node_item)
     self.window.addItem(self.goal)
     self.window.show()
Ejemplo n.º 2
0
def render_image(image, metadata=None, feature=None, alpha=1, feature_size=4):
    pg.mkQApp()
    view = gl.GLViewWidget()
    view.show()
    if isinstance(metadata, type(None)):
        metadata = {'voxel_size_x': 1, 'voxel_size_y': 1, 'voxel_size_z': 1}
    image_positions = index2position(image, metadata)
    view.opts['center'] = QVector3D(image_positions.T[0].flatten().max() / 2,
                                    image_positions.T[1].flatten().max() / 2,
                                    image_positions.T[2].flatten().max() /
                                    2)  # rotation centre of the camera
    view.opts['distance'] = image_positions.flatten().max(
    ) * 2  # distance of the camera respect to the center
    image_color = np.zeros([len(image_positions), 4]) + np.array(
        [0.1, 0.1, 1, alpha])
    point_image = gl.GLScatterPlotItem(pos=image_positions,
                                       color=image_color,
                                       pxMode=False)
    view.addItem(point_image)
    if not isinstance(feature, type(None)):
        feature = feature.T
        feature = np.array([
            feature[0] * metadata['voxel_size_x'],
            feature[1] * metadata['voxel_size_y'],
            feature[2] * metadata['voxel_size_z']
        ])
        feature_size = np.ones(feature.shape[1]) * feature_size
        feature_color = np.zeros([feature.shape[1], 1]) + np.array(
            [1, 0, 0, 1])
        point_feature = gl.GLScatterPlotItem(pos=feature.T,
                                             color=feature_color,
                                             size=feature_size)
        view.addItem(point_feature)
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
    def initialize(self, agents):
        start_color = np.array([0.0, 1.0, 0.0, 1.0]).reshape((1, 4))
        end_color = np.array([1.0, 0.0, 0.0, 1.0]).reshape((1, 4))

        for agent in agents:
            start = np.array([
                agent.sy - self.map.rows // 2, agent.sx - self.map.cols // 2,
                self.map.grid[agent.sy][agent.sx]
            ]).reshape((1, 3))

            agent_symbol = gl.GLScatterPlotItem(pos=start,
                                                color=start_color,
                                                size=20)
            self.agents[agent.num] = agent_symbol
            self.w.addItem(agent_symbol)

            end = np.array([
                agent.fy - self.map.rows // 2, agent.fx - self.map.cols // 2,
                self.map.grid[agent.fy][agent.fx]
            ]).reshape((1, 3))

            goal = gl.GLScatterPlotItem(pos=end, color=end_color, size=20)
            self.w.addItem(goal)

        self.app.processEvents()
Ejemplo n.º 4
0
def plotDetectedPointsGraph(data):
    if not hasattr(plotDetectedPointsGraph,"sp"):
        plotDetectedPointsGraph.sp = [None, None] # keep 2 copies
        plotDetectedPointsGraph.spIndex = 0;

    global widgetDetectedPoints
    if widgetDetectedPoints == None:
        widgetDetectedPoints = gl.GLViewWidget()
        widgetDetectedPoints.opts['distance'] = 20 # distance of camera from center
        widgetDetectedPoints.opts['fov'] = 60  # horizontal field of view in degrees
        widgetDetectedPoints.opts['azimuth'] = -75 # camera's azimuthal angle in degrees, 仰俯角
        widgetDetectedPoints.opts['elevation'] = 30 # camera's angle of elevation in degrees, 方位角
        widgetDetectedPoints.setGeometry(100, 100, 800, 800)
        widgetDetectedPoints.show()
        widgetDetectedPoints.setWindowTitle('Detected Points')
        gridX = gl.GLGridItem()
        gridX.rotate(0, 0, 1, 0)
        gridX.translate(0, 0, 0)
        widgetDetectedPoints.addItem(gridX)
        # center dot
        pos = np.array([0.0, 0.0, 0.0])
        size = np.array([0.2])
        color = np.array([1.0, 0.0, 0.0, 0.5])
        center  = gl.GLScatterPlotItem(pos=pos, size=size, color=color, pxMode=False)
        widgetDetectedPoints.addItem(center)
        # axis
        axis = gl.GLAxisItem(antialias=True, glOptions='translucent')
        axis.setSize(x=10, y=10, z=10)
        widgetDetectedPoints.addItem(axis)

    if data["type"] == MMWDEMO_OUTPUT_MSG_DETECTED_POINTS and len(data["x"]) > 0:
        x = data["x"]
        y = data["y"]
        z = data["z"]
        v = data["velocity"]
        s = data["snr"]
        n = data["noise"]

        pos = np.empty((len(data["x"]), 3))
        size = np.empty(len(data["x"]))
        color = np.empty((len(data["x"]), 4))
        for i in range(len(x)):
            pos[i] = (x[i], y[i], z[i])
            size[i] = s[i] / 2000
            if v[i]>= 0:
                color[i] = (0.0, v[i], 0.0, 1.0) #color (r,g,b,a)
            else:
                color[i] = (-v[i], 0.0, 0.0, 1.0) #color (r,g,b,a)

        sp1 = gl.GLScatterPlotItem(pos=pos, size=size, color=color, pxMode=False)
        #sp1.translate(0, 0, 0)

        if plotDetectedPointsGraph.sp[plotDetectedPointsGraph.spIndex] != None:
            sp2 = plotDetectedPointsGraph.sp[plotDetectedPointsGraph.spIndex]
            widgetDetectedPoints.removeItem(sp2)

        plotDetectedPointsGraph.sp[plotDetectedPointsGraph.spIndex] = sp1
        widgetDetectedPoints.addItem(sp1)
        plotDetectedPointsGraph.spIndex = (plotDetectedPointsGraph.spIndex + 1) % len(plotDetectedPointsGraph.sp)
Ejemplo n.º 5
0
    def __init__(self, N, clusters):
        self.clusters = clusters

        self.w = gl.GLViewWidget()
        self.w.opts['distance'] = 100
        self.w.setWindowTitle('RGB space')
        self.w.setGeometry(100, 100, 500, 500)
        self.w.show()
        # create the background grids
        gx = gl.GLGridItem()
        gx.rotate(90, 0, 1, 0)
        gx.translate(0, 10, 10)
        self.w.addItem(gx)
        gy = gl.GLGridItem()
        gy.rotate(90, 1, 0, 0)
        gy.translate(10, 0, 10)
        self.w.addItem(gy)
        gz = gl.GLGridItem()
        gz.translate(10, 10, 0)
        self.w.addItem(gz)

        self.curve1 = gl.GLLinePlotItem()
        self.curve2 = gl.GLLinePlotItem()
        self.curve3 = gl.GLLinePlotItem()
        self.w.addItem(self.curve1)
        self.w.addItem(self.curve2)
        self.w.addItem(self.curve3)
        self.pca = decomposition.PCA(n_components=3)

        self.centers = [None for _ in range(clusters)]
        for i in range(clusters):
            pts = np.array([0, 0, 0]) / 14
            self.centers[i] = gl.GLScatterPlotItem(pos=pts,
                                                   color=pg.glColor(
                                                       0, 0, 255, 255))
            self.w.addItem(self.centers[i])

        self.cyl = []
        for i in range(clusters):
            CYL = gl.MeshData.cylinder(rows=10,
                                       cols=20,
                                       radius=[1., 1.0],
                                       length=5.)
            self.cyl.append(
                gl.GLMeshItem(meshdata=CYL,
                              smooth=True,
                              drawEdges=True,
                              edgeColor=(1, 0, 0, 0.1),
                              shader='balloon'))
            self.cyl[-1].setGLOptions('additive')
            self.w.addItem(self.cyl[-1])

        self.traces = dict()
        for i in range(N):
            pts = np.array([0, 0, 0]) / 14
            self.traces[i] = gl.GLScatterPlotItem(pos=pts,
                                                  color=pg.glColor(
                                                      100, 100, 100, 100))
            self.w.addItem(self.traces[i])
Ejemplo n.º 6
0
    def __init__(self):
        visual_multiplier = [10, 200 / 120, 5 / 1400]
        # Get the directory for the data
        data_dir = dirname(realpath(__file__)) + r"\data\regular"
        data_file_name = [
            "#full_data_path.npy",
            "#acc_data_path.npy",
            "break_data_path.npy",
            "#coast_data_path.npy",
        ]
        # Initiate the data array
        full_data = np.empty((3,))
        # iterating through all files and adding them to a huge array
        for filename in os.listdir(data_dir):
            if filename not in data_file_name:
                continue
            filepath = data_dir + sep + filename
            # Loading data
            data = np.load(filepath)
            full_data = np.vstack((full_data, data))

        pos_data_mask = full_data[:, 0] >= 0
        self.pos_data = full_data[pos_data_mask]
        neg_data_mask = full_data[:, 0] < 0
        self.neg_data = full_data[neg_data_mask]

        # PyQtGraph stuff
        self.app = QtGui.QApplication(sys.argv)
        self.w = gl.GLViewWidget()
        self.w.opts["distance"] = 40
        self.w.setWindowTitle("RL Throttle Visualized")
        self.w.setGeometry(0, 30, 1920, 1080)
        self.w.show()

        # Adding a grid
        gz = gl.GLGridItem(QtGui.QVector3D(20, 10, 1))
        gz.translate(0, 5, 0)
        self.w.addItem(gz)

        gz = gl.GLGridItem(QtGui.QVector3D(10, 20, 1))
        gz.rotate(90, 0, 1, 0)
        gz.rotate(90, 0, 0, 1)
        gz.translate(0, 0, 0)
        self.w.addItem(gz)

        # Create the scatter plot
        blue_color = [0.1, 0.5, 1, 0.9]
        self.pos_data[:, 0] = self.pos_data[:, 0] * visual_multiplier[0]
        self.pos_data[:, 1] = self.pos_data[:, 1] * visual_multiplier[1]
        self.pos_data[:, 2] = self.pos_data[:, 2] * visual_multiplier[2]
        scatter = gl.GLScatterPlotItem(pos=self.pos_data, size=1, color=blue_color)
        self.w.addItem(scatter)

        red_color = [1, 0.3, 0.05, 0.9]
        self.neg_data[:, 0] = self.neg_data[:, 0] * visual_multiplier[0]
        self.neg_data[:, 1] = self.neg_data[:, 1] * visual_multiplier[1]
        self.neg_data[:, 2] = self.neg_data[:, 2] * visual_multiplier[2]
        scatter = gl.GLScatterPlotItem(pos=self.neg_data, size=1, color=red_color)
        self.w.addItem(scatter)
Ejemplo n.º 7
0
 def calibrate(self):
   # read file and run calibration algorithm
   (self.acc_offset, self.acc_scale) = cal_lib.calibrate_from_file(acc_file_name)
   (self.magn_offset, self.magn_scale) = cal_lib.calibrate_from_file(magn_file_name)
   
   # map floats into integers
   self.acc_offset = map(int, self.acc_offset)
   self.magn_offset = map(int, self.magn_offset)
   
   # show calibrated tab
   self.tabWidget.setCurrentIndex(1)
   
   #populate acc calibration output on gui
   self.calRes_acc_OSx.setText(str(self.acc_offset[0]))
   self.calRes_acc_OSy.setText(str(self.acc_offset[1]))
   self.calRes_acc_OSz.setText(str(self.acc_offset[2]))
   
   self.calRes_acc_SCx.setText(str(self.acc_scale[0]))
   self.calRes_acc_SCy.setText(str(self.acc_scale[1]))
   self.calRes_acc_SCz.setText(str(self.acc_scale[2]))
   
   #populate acc calibration output on gui
   self.calRes_magn_OSx.setText(str(self.magn_offset[0]))
   self.calRes_magn_OSy.setText(str(self.magn_offset[1]))
   self.calRes_magn_OSz.setText(str(self.magn_offset[2]))
   
   self.calRes_magn_SCx.setText(str(self.magn_scale[0]))
   self.calRes_magn_SCy.setText(str(self.magn_scale[1]))
   self.calRes_magn_SCz.setText(str(self.magn_scale[2]))
   
   # compute calibrated data
   self.acc_cal_data = cal_lib.compute_calibrate_data(self.acc_data, self.acc_offset, self.acc_scale)
   self.magn_cal_data = cal_lib.compute_calibrate_data(self.magn_data, self.magn_offset, self.magn_scale)
   
   # populate 2D graphs with calibrated data
   self.accXY_cal.plot(x = self.acc_cal_data[0], y = self.acc_cal_data[1], clear = True, pen='r')
   self.accYZ_cal.plot(x = self.acc_cal_data[1], y = self.acc_cal_data[2], clear = True, pen='g')
   self.accZX_cal.plot(x = self.acc_cal_data[2], y = self.acc_cal_data[0], clear = True, pen='b')
   
   self.magnXY_cal.plot(x = self.magn_cal_data[0], y = self.magn_cal_data[1], clear = True, pen='r')
   self.magnYZ_cal.plot(x = self.magn_cal_data[1], y = self.magn_cal_data[2], clear = True, pen='g')
   self.magnZX_cal.plot(x = self.magn_cal_data[2], y = self.magn_cal_data[0], clear = True, pen='b')
   
   # populate 3D graphs with calibrated data
   acc3D_cal_data = np.array(self.acc_cal_data).transpose()
   magn3D_cal_data = np.array(self.magn_cal_data).transpose()
   
   sp = gl.GLScatterPlotItem(pos=acc3D_cal_data, color = (1, 1, 1, 1), size=2)
   self.acc3D_cal.addItem(sp)
   
   sp = gl.GLScatterPlotItem(pos=magn3D_cal_data, color = (1, 1, 1, 1), size=2)
   self.magn3D_cal.addItem(sp)
   
   #enable calibration buttons to activate calibration storing functions
   self.saveCalibrationHeaderButton.setEnabled(True)
   self.saveCalibrationHeaderButton.clicked.connect(self.save_calibration_header)
Ejemplo n.º 8
0
    def drawDetector(self, meta):

        _len_x = meta.len_x()
        _len_y = meta.len_y()
        _len_z = meta.len_z()
        self._dims = [_len_x, _len_y, _len_z]

        # # Draw a cylinder for the detector:

        cylinderPoints = gl.MeshData.cylinder(
            2,
            10,
            radius=[1.5 * meta.radius(), 1.5 * meta.radius()],
            length=meta.len_z())
        cylinder = gl.GLMeshItem(meshdata=cylinderPoints,
                                 drawEdges=True,
                                 drawFaces=False,
                                 smooth=False,
                                 glOptions='translucent')
        # cylinder.translate(0,0,-_len_z*0.5)
        self.addItem(cylinder)

        # Draw locations of all sipms and PMTs

        # Using points to draw pmts and sipms, since a scatter plot is
        # easy and cheap to draw
        pmt_data = meta.pmt_data()
        n_pmts = len(pmt_data.index)

        _pmt_pts = np.ndarray((n_pmts, 3))
        _pmt_pts[:, 0] = pmt_data.X
        _pmt_pts[:, 1] = pmt_data.Y
        _pmt_pts[:, 2] = meta.max_z()

        pmtPointsCollection = gl.GLScatterPlotItem(pos=_pmt_pts,
                                                   size=20.32,
                                                   color=[0, 0, 1.0, 1.0],
                                                   pxMode=False)
        self.addItem(pmtPointsCollection)

        _sipm_pts = np.ndarray((len(meta.sipm_data().index), 3))
        _sipm_pts[:, 0] = meta.sipm_data().X
        _sipm_pts[:, 1] = meta.sipm_data().Y
        _sipm_pts[:, 2] = meta.min_z()
        sipmPointsCollection = gl.GLScatterPlotItem(pos=_sipm_pts,
                                                    size=2,
                                                    color=[0, 1.0, 1.0, 1.0],
                                                    pxMode=False)
        self.addItem(sipmPointsCollection)

        self.setCenter((0, 0, 0.5 * _len_z))
Ejemplo n.º 9
0
    def run(self, data):

        # check dimensionality of data. add zeros if needed
        if data.shape[1] < 3:

            # determine number of zeros to be added
            missing_dims = 3 - data.shape[1]

            for d in data:
                if self.data is None:
                    self.data = np.array([np.append(d, missing_dims * [0])])
                else:
                    self.data = np.vstack((self.data, np.append(d, missing_dims * [0])))
        else:
            # store data reference
            self.data = data

        # store data dimensionality
        self.data_dim = data.shape[1]

        # prepare network
        self.prepare()

        # skip viz if not needed
        if not self.viz:
            return

        # number of datapoints
        n = data.shape[0]

        # create color and size arrays
        color = np.array(n * [[1, 0, 0, 0.7]])
        size = np.array(n * [0.02])

        # plot data distribution
        self.dist_plot = gl.GLScatterPlotItem(pos=self.data, size=size, color=color, pxMode=False)
        self.w.addItem(self.dist_plot)

        # plot nodes
        self.node_plot = gl.GLScatterPlotItem(pos=self.node_positions, size=self.node_sizes, color=self.node_colors,
                                              pxMode=False)
        self.w.addItem(self.node_plot)

        # plot network
        self.draw()

        # start timer, therefore training
        self.t.start(self.freq)

        # run QT App
        QtGui.QApplication.instance().exec_()
Ejemplo n.º 10
0
 def init_cloud(self):
     w = gl.GLViewWidget(self)
     w.opts['pos'] = 1
     gx = gl.GLGridItem()
     self.cloudPlot = gl.GLScatterPlotItem(pos=np.zeros(3),
                                           color=np.zeros((1, 3)),
                                           size=1,
                                           pxMode=True)
     self.camPlot = gl.GLScatterPlotItem(pos=np.zeros(3),
                                         color=np.array([0, 0, 0]),
                                         size=1,
                                         pxMode=True)
     w.addItem(self.cloudPlot)
     w.addItem(self.camPlot)
     return w
    def initialize_plot(self):
        self.Time = np.array([])
        self.X = np.array([])
        self.Y = np.array([])
        self.Z = np.array([])
        self.Zmax = 10
        self.Zmin = 0

        self.opts['distance'] = 20
        self.show()

        self.axes = gl.GLAxisItem(size=None,
                                  antialias=True,
                                  glOptions='translucent')
        self.axes.translate(0, 0, 0)
        self.addItem(self.axes)

        self.initialize_grid()

        #Inital scatter plot
        pos = np.empty((1, 3))
        size = np.empty((1))
        color = np.empty((1, 4))
        pos[0] = (0, 0, 0)
        size[0] = 0.0
        color[0] = (1.0, 0.0, 0.0, 0.5)

        self.scatter_plot = gl.GLScatterPlotItem(pos=pos,
                                                 size=size,
                                                 color=color,
                                                 pxMode=False)
        self.addItem(self.scatter_plot)

        #Initial marker
        pos2 = np.empty((1, 3))
        size2 = np.empty((1))
        color2 = np.empty((1, 4))
        pos2[0] = (0, 0, 0)
        size2[0] = self.size_marker
        color2[0] = (1.0, 1.0, 1.0, 1.0)

        self.marker = gl.GLScatterPlotItem(pos=pos2,
                                           size=size2,
                                           color=color2,
                                           pxMode=False)
        self.addItem(self.marker)

        self.reset_view()
Ejemplo n.º 12
0
        def drawObjects(self, view_manager):

            geom = view_manager._geometry
            view = view_manager.getView()

            spts = self._process.getData()
            color = [128, 128, 128, 128]

            # Make a collection to add the points to:
            points = np.ndarray((spts.size(), 3))

            for i in xrange(len(spts)):
                thisPoint = spts[i]

                points[i][0] = thisPoint.X()
                points[i][1] = thisPoint.Y()
                points[i][2] = thisPoint.Z()

            glPointsCollection = gl.GLScatterPlotItem(pos=points,
                                                      size=5,
                                                      color=color)

            view.addItem(glPointsCollection)

            self._drawnObjects.append(glPointsCollection)
    def showMultipleOrbits(self):
        self.finished = False
        
        self.orbitPlot.clear()

        firstPass = True

        for orbit, params in self.currentOrbits.items():

            if firstPass:
                # Create the celestial body
                radius = np.linalg.norm([0, params.body.radius, 0])
                md = gl.MeshData.sphere(rows=200, cols=300, radius=radius)
                m1 = gl.GLMeshItem(meshdata=md,smooth=True,color=params.body.qtColor,shader="balloon",glOptions="additive")
                self.orbitPlot.plot.addItem(m1)
                firstPass = False
            
            rs = params.getRadiusArray()

            # Plot the initial point
            initialPoint = gl.GLScatterPlotItem(pos=np.array([rs[0,0], rs[0,1], rs[0,2]]), size=np.array([13]), color=(1,0,0,1.5))
            self.orbitPlot.plot.addItem(initialPoint)

            # Plot the trajectory
            orbit1 = np.array([rs[:,0], rs[:,1], rs[:,2]]).transpose()
            orbit = gl.GLLinePlotItem(pos=orbit1, color=params.color, antialias=True)
            self.orbitPlot.plot.addItem(orbit)

            # Adjust the plot
            self.orbitPlot.plot.setCameraPosition(distance=params.body.radius*10)
            self.orbitPlot.zgrid.scale(np.max(orbit1),np.max(orbit1),np.max(orbit1))
            self.orbitPlot.scaleAxis(params.body.radius*2)
            self.orbitPlot.createAxis()
Ejemplo n.º 14
0
 def __init__(self):
     super(PositionGraph, self).__init__()
     self.setWindowTitle('Anser Position')
     self.setBackgroundColor('w')
     anser_mesh = mesh.Mesh.from_file(
         utils.resource_path('./app/resources/cad/mesh.stl'))
     anser_mesh = gl.MeshData(vertexes=anser_mesh.vectors)
     m = gl.GLMeshItem(meshdata=anser_mesh,
                       shader='shaded',
                       color=(0, 1, 0, 0.1))
     m.rotate(135, 0, 0, 1)
     m.translate(240, 0, -240)
     m.scale(1, 1, 1)
     self.addItem(m)
     gx = gl.GLGridItem()
     gx.setSize(7, 7, 7)
     gx.scale(45, 45, 45)
     gx.rotate(45, 0, 0, 1)
     #self.addItem(gx)
     self.pos = np.empty((MAX_NUM_OF_SENSORS, 3))
     self.color = np.empty((MAX_NUM_OF_SENSORS, 4))
     size = np.empty(MAX_NUM_OF_SENSORS)
     for i in range(MAX_NUM_OF_SENSORS):
         self.pos[i] = (0, 0, 0)
         self.color[i] = (0, 0.0, 0.0, 0.0)
         size[i] = 6
     self.sp1 = gl.GLScatterPlotItem(pos=self.pos,
                                     size=size,
                                     color=self.color[0],
                                     pxMode=True)
     self.sp1.setGLOptions('translucent')
     self.addItem(self.sp1)
     self.setCameraPosition(100, 800, 30)
     self.sp1.rotate(135, 0, 0, 1)
Ejemplo n.º 15
0
Archivo: cloud.py Proyecto: YHanL/pyfor
    def plot3d(self, dim = "z", point_size=1, cmap='Spectral_r', max_points=5e5, n_bin=8, plot_trees=False):
        """
        Plots the three dimensional point cloud using a `Qt` backend. By default, if the point cloud exceeds 5e5 \
         points, then it is downsampled using a uniform random distribution. This is for performance purposes.

        :param point_size: The size of the rendered points.
        :param dim: The dimension upon which to color (i.e. "z", "intensity", etc.)
        :param cmap: The matplotlib color map used to color the height distribution.
        :param max_points: The maximum number of points to render.
        """
        from pyqtgraph.Qt import QtCore, QtGui
        import pyqtgraph as pg
        import pyqtgraph.opengl as gl

        # Randomly sample down if too large
        if dim == 'user_data' and plot_trees:
            dim = 'random_id'
            self._set_discrete_color(n_bin, self.data.points['user_data'])
            cmap = self._discrete_cmap(n_bin, base_cmap=cmap)

        if self.data.count > max_points:
                sample_mask = np.random.randint(self.data.count,
                                                size = int(max_points))
                coordinates = np.stack([self.data.points.x, self.data.points.y, self.data.points.z], axis = 1)[sample_mask,:]

                color_dim = np.copy(self.data.points[dim].iloc[sample_mask].values)
                print("Too many points, down sampling for 3d plot performance.")
        else:
            coordinates = np.stack([self.data.points.x, self.data.points.y, self.data.points.z], axis = 1)
            color_dim = np.copy(self.data.points[dim].values)

        # If dim is user data (probably TREE ID or some such thing) then we want a discrete colormap
        if dim != 'random_id':
            color_dim = (color_dim - np.min(color_dim)) / (np.max(color_dim) - np.min(color_dim))
            cmap = cm.get_cmap(cmap)
            colors = cmap(color_dim)

        else:
            colors = cmap(color_dim)

        # Start Qt app and widget
        pg.mkQApp()
        view = gl.GLViewWidget()


        # Create the points, change to opaque, set size to 1
        points = gl.GLScatterPlotItem(pos = coordinates, color = colors)
        points.setGLOptions('opaque')
        points.setData(size = np.repeat(point_size, len(coordinates)))

        # Add points to the viewer
        view.addItem(points)

        # Center on the arithmetic mean of the point cloud and display
        center = np.mean(coordinates, axis = 0)
        view.opts['center'] = pg.Vector(center[0], center[1], center[2])
        # Very ad-hoc
        view.opts['distance'] = (self.data.max[0] - self.data.min[0]) * 1.2
        #return(view.opts)
        view.show()
Ejemplo n.º 16
0
 def plotInit(self):
     #
     self.getLimitData()
     # Get ECT cap array data
     self.getData()
     # Load default image filter configuraiton
     self.default_config()
     # Set color normalization method
     (self.values_norm,
      self.color_values_norm) = self.image_filter.color_normalizer(
          value=self.epsilon_sensing_domain,
          cmap=self.cmap,
          base_opacity=self.base_opacity,
          norm_method=self.norm_method,
          gamma=self.gamma,
          initial=True,
          coordinates=self.fem.sensing_domain_coordinates)
     # Set opacity filter
     self.image_filter.opacity_filter(
         opacity_filter=self.opacity_filter,
         opacity_param=self.opacity_param,
         values=self.epsilon_sensing_domain,
         values_norm=self.values_norm,
         color_values_norm=self.color_values_norm,
         coordinates=self.fem.sensing_domain_coordinates)
     # Create openGL scatter plot and add
     self.item_dof = gl.GLScatterPlotItem(
         pos=self.fem.sensing_domain_coordinates,
         color=self.color_values_norm,
         size=0.001 * self.unit_scale,
         pxMode=False)
     self.item_dof.setGLOptions('additive')
     self.gl_widget.addItem(self.item_dof)
     # Add tracker
     self.trackerInit()
Ejemplo n.º 17
0
 def show_droppoint(self, curve_list):
     colors = np.zeros((2, 2, 3), dtype=float)
     colors[..., 0] = 0
     colors[..., 2] = 1
     colors[..., 1] = 1
     self.clear_point()
     for curve in curve_list:
         ret = curve.calc_droppoint()
         if ret is not None:
             x, y = ret
             '''
             x = int(x)
             y = int(y)
             z = np.ones((2,2))
             x1 = np.linspace(x-5, x+5, 2)
             y1 = np.linspace(y-5, y+5, 2)
             l = gl.GLSurfacePlotItem(x1, y1, z=z, colors=colors.reshape(2*2,3), shader='shaded', smooth=False)
             '''
             pos = np.empty((1, 3))
             size = np.empty((1))
             color = np.empty((1, 4))
             pos[0] = (x, y, 0)
             size[0] = 10
             color[0] = (0., 1., 0., .5)
             l = gl.GLScatterPlotItem(pos=pos,
                                      size=size,
                                      color=color,
                                      pxMode=False)
             self.point_item_list.append(l)
             self.w.addItem(l)
Ejemplo n.º 18
0
    def drawEvent(self):
        self.colorize()
        ## 3D Viewport
        if self.plot3DView is None:
            self.plot3DView = gl.GLScatterPlotItem(
                pos=self.parameters["posArray"],
                color=self.colorArray,
                size=self.parameters["plWeights"],
                pxMode=False)
        else:
            self.plot3DView.pos = self.parameters["posArray"]
            self.plot3DView.color = self.colorArray
            self.plot3DView.size = self.parameters["plWeights"]
            self.plot3DView.update()
        ## 2D Viewport
        self.plotFlatMap.setPosition(self.parameters["posArray"])
        self.plotFlatMap.setColor(self.colorArray)
        self.plotFlatMap.setWeights(self.parameters["plWeights"])
        self.plotFlatMap.update()

        if self.parameters['colorMask'] == 'charge':
            variable = self.parameters["charge"]
        else:
            variable = self.parameters["time"]
        self.figCanvas.setData(variable)

        ## Tracking
        if self.parameters["trackingEnabled"]:
            self.plotTracks.pos = self.parameters["trackPosition"]
            self.plotTracks.color = self.parameters["trackColors"]
            self.plotTracks.update()
Ejemplo n.º 19
0
 def processData(self, xyzData, energy, pos, begin, end):
     self.xyzData[begin:end] = xyzData[begin:end]
     self.energy[begin:end] = energy[begin:end]
     self.pos[begin:end] = pos[begin:end]
     self.num += 1
     print(self.num, "/", self.numThreads)
     self.progress.setValue(self.num)
     # self.show()
     if self.num == self.numThreads:
         energy = [float(i) for i in self.energy] # This is for python3 compatibility
         minEnergy = min(energy)
         maxEnergy = max(energy)
         # self.normEnergy = map(lambda x:(x - minEnergy)/(maxEnergy - minEnergy), energy)
         # self.progress.close()
         self.normEnergy = divide(
             subtract(energy, minEnergy), subtract(maxEnergy, minEnergy))
         self.color = hot(self.normEnergy)
         maxPos = self.pos[self.previousDataSize - 1]
         self.xMaxPos = int(maxPos[0])
         self.yMaxPos = int(maxPos[1])
         self.zMaxPos = int(maxPos[2])
         # self.xPlaneLabel.setText("X-Plane: Max %i" % self.xMaxPos)
         # self.yPlaneLabel.setText("Y-Plane: Max %i" % self.yMaxPos)
         # self.zPlaneLabel.setText("Z-Plane: Max %i" % self.zMaxPos)
         self.plot = gl.GLScatterPlotItem(
             pos=self.pos, size=self.size, color=self.color, pxMode=False)
         self.plotWidget.addItem(self.plot)
         self.plotAlreadyThere = True
Ejemplo n.º 20
0
 def __init__(self, path):
     super(LBViewer,self).__init__()
     
     print('PATH PATH PATH',path)
     
     self.frametimer = clock()
     
     self.input_recorder = InputRecorder()
     self.cycle = 'Cycle'
     self.cycle_means = 0
     
     self.framerate = 30
     self.lovebug = LoveBug(input_recorder=self.input_recorder, fullShell=False, framerate=self.framerate, path=('../' if len(path) == 1 else path[1]))
     self.showlist = ['Hearts','Mandel','Triangles','Rainbow Galaxy','Rainbow Molecule','Rainbow Glow','Fire Glow','Yellow Glow',
                      'Purple Glow','Snow','Water','Rainbow Animals','Fireworks','Flowers','Sunrise','Fire','Bigger Fire',
                      'Fast Rainbow','Pineapples','Bananas','Reactive Spots']
     self.numCycle = 18
     self.lightshow = self.showlist[0] #set default light show
     
     self.init_ui()
     self.qt_connections()
     
     self.shell = gl.GLScatterPlotItem(pos = self.lovebug.get3DPoints(), size = 20.0, pxMode = False)
     self.shell.setGLOptions('additive')
     self.view.addItem(self.shell)
     
     self.t = QtCore.QTimer()
     self.t.timeout.connect(self.update)
     self.t.start(1)
Ejemplo n.º 21
0
def render_label(labels, metadata=None, alpha=0.01):
    """
    labels.shape: (x_size, y_size, z_size)
    """

    if isinstance(metadata, type(None)):
        metadata = {'voxel_size_x': 1, 'voxel_size_y': 1, 'voxel_size_z': 1}

    pg.mkQApp()
    view = gl.GLViewWidget()
    view.show()
    label_positions = index2position(labels, metadata)
    view.opts['center'] = QVector3D(label_positions.T[0].flatten().max() / 2,
                                    label_positions.T[1].flatten().max() / 2,
                                    label_positions.T[2].flatten().max() /
                                    2)  # rotation centre of the camera
    view.opts['distance'] = label_positions.flatten().max(
    ) * 2  # distance of the camera respect to the center
    label_color = np.array(label_to_rgba(labels, alpha))
    point_label = gl.GLScatterPlotItem(pos=label_positions,
                                       color=label_color,
                                       pxMode=False)
    view.addItem(point_label)
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
Ejemplo n.º 22
0
def create_3d_cams(view):
    cam_coords = np.array([c['coord_m'] for c in CAPTURES])
    cam_plot = gl.GLScatterPlotItem(pos=cam_coords,
                                    color=(1.0, 0.0, 0.0, 1.0),
                                    size=20,
                                    pxMode=True)
    view.addItem(cam_plot)
Ejemplo n.º 23
0
 def add_marker(self, pos, color, size=0.1):
     points = np.array([pos])
     p = gl.GLScatterPlotItem(pos=points,
                              color=np.array(color),
                              size=size,
                              pxMode=False)
     self.glview.addItem(p)
Ejemplo n.º 24
0
def create_3d_side(view):
    side_plot = gl.GLScatterPlotItem(pos=np.array([]),
                                     color=(0.0, 0.5, 1.0, 1.0),
                                     size=5,
                                     pxMode=True)
    view.addItem(side_plot)
    return side_plot
Ejemplo n.º 25
0
def visualize_3d():
    #app = QtGui.QApplication([])
    w = gl.GLViewWidget()
    w.show()
    g = gl.GLGridItem()
    w.addItem(g)

    df = pd.read_csv('positions_d.txt')
    df = df[df.columns[0:3]].values / 5

    cmap = plt.get_cmap('cool')
    colors = []
    for i in range(df.shape[0]):
        normal_num = i / df.shape[0]
        colors.append(cmap(normal_num))

    colors = np.array(colors)

    indexesFinal = np.array([[1, 2]])
    sp2 = gl.GLScatterPlotItem(pos=df, size=0.1, pxMode=False, color=colors)
    w.addItem(sp2)

    sp2 = gl.GLLinePlotItem(pos=df, width=0.5)
    w.addItem(sp2)

    ## Start Qt event loop unless running in interactive mode.
    if __name__ == '__main__':
        import sys
        if (sys.flags.interactive != 1) or not hasattr(QtCore, PYQT_VERSION):
            QtGui.QApplication.instance().exec_()
def start_graph():
    print("Setting up graph")
    global app, graph_region, w, g, d3, t
    app = QtGui.QApplication([])
    w = gl.GLViewWidget()
    w.resize(800, 600)
    w.opts['distance'] = 20
    w.show()
    w.setWindowTitle('LIDAR Point Cloud')

    g = gl.GLGridItem()
    #g.translate(0,0,-10)
    w.addItem(g)

    #pos3 = np.zeros((100, 100, 3))
    #pos3[:, :, :2] = np.mgrid[:100, :100].transpose(1, 2, 0) * [-0.1, 0.1]
    #pos3 = pos3.reshape(10000, 3)
    #d3 = (pos3 ** 2).sum(axis=1) ** 0.5

    graph_region = gl.GLScatterPlotItem(pos=np.zeros((1, 3), dtype=np.float32), color=(0, 1, 0, 0.5), size=0.1, pxMode=False)
    #graph_region.rotate(180, 1, 0, 0)
    #graph_region.translate(0, 0, 2.4)
    w.addItem(graph_region)
    t = QtCore.QTimer()
    t.timeout.connect(update_graph)
    t.start(50)

    QtGui.QApplication.instance().exec_()
    global RUNNING
    RUNNING = False
    print("\n[STOP]\tGraph Window closed. Stopping...")
Ejemplo n.º 27
0
def create_3d_volume(view):
    volume_plot = gl.GLScatterPlotItem(pos=np.array([]),
                                       color=(0.0, 1.0, 0.0, 1.0),
                                       size=10,
                                       pxMode=True)
    view.addItem(volume_plot)
    return volume_plot
    def __init__(self,
                 data_shape=1024,
                 color=(1.0, 0.0, 0.0, 1.0),
                 start_angle=-3 * np.pi / 4.,
                 stop_angle=3 * np.pi / 4.,
                 widget=None):
        if not widget:
            self.app = QtGui.QApplication([])
            self.widget = gl.GLViewWidget()
            self.widget.opts['distance'] = 40
            self.widget.show()
        else:
            self.widget = widget

        self.axis = gl.GLAxisItem()
        self.axis.translate(0, 0, 1)
        self.widget.addItem(self.axis)

        self.gz = gl.GLGridItem()
        self.widget.addItem(self.gz)

        radius = np.ones((data_shape)) * 5
        self.start_angle = start_angle
        self.stop_angle = stop_angle
        self.angle = np.linspace(self.start_angle, self.stop_angle, data_shape)
        x = np.sin(self.angle) * radius
        y = np.cos(self.angle) * radius
        z = np.ones((data_shape))
        pts = np.vstack([x, y, z]).transpose()
        # self.line_plot = gl.GLLinePlotItem(pos=pts, color=np.array(color * data_shape).reshape((data_shape, 3)))
        self.line_plot = gl.GLScatterPlotItem(
            pos=pts,
            color=np.array(color * data_shape).reshape((data_shape, 4)),
            size=3.0)
        self.widget.addItem(self.line_plot)
Ejemplo n.º 29
0
def make_points(xyzs, point_colours, sizes, pxMode = True):
    """
    This function returns points Item that can be viz by pyqtgraph.
 
    Parameters
    ----------
    xyzs : ndarray of shape(Nvertices,3)
        ndarray of shape(Nvertices,3) of the line.
        
    point_colour : ndarray of shape(4), optional
        array of colours specifying the colours of the line, if a single tuple is given all points assumes that colour.
    
    sizes : float, optional
        list of floats of points sizes, if single val is given all point assumes that size
        
    pxMode: bool, option
        if True size is measured in pixels, if False size is based on units of the xyzs
        
    Returns
    -------
    points : point object
        point for visualisation.
    """
    points = gl.GLScatterPlotItem(pos=xyzs, color=point_colours, size=sizes, pxMode = pxMode)
    return points
Ejemplo n.º 30
0
    def __init__(self):

        self.app = QtGui.QApplication([])
        self.view = gl.GLViewWidget()
        self.view.opts['distance'] = 10
        self.view.show()
        self.view.setWindowTitle("Points Visualizer")

        grid = gl.GLGridItem(size=QtGui.QVector3D(10, 10, 1))
        grid.setSpacing(0.5, 0.5, 0.5)
        self.view.addItem(grid)

        axis = GLRGBAxisItem(size=QtGui.QVector3D(0.5, 0.5, 0.5))
        self.view.addItem(axis)

        self.gtFrustum = GLFrustumItem(frustumColor=(0.8, 0, 0, 0.6),
                                       size=QtGui.QVector3D(0.5, 0.5, 0.5))
        self.view.addItem(self.gtFrustum)

        self.gtLine = gl.GLLinePlotItem(color=(0.8, 0, 0, 0.6))
        self.view.addItem(self.gtLine)
        self.gtPositions = []

        self.estimatedFrustum = GLFrustumItem(frustumColor=(1, 1, 1, 0.6),
                                              size=QtGui.QVector3D(
                                                  0.5, 0.5, 0.5))
        self.view.addItem(self.estimatedFrustum)

        self.estimatedLine = gl.GLLinePlotItem(color=(1, 1, 1, 0.6))
        self.view.addItem(self.estimatedLine)
        self.estimatedPositions = []

        self.points = gl.GLScatterPlotItem(color=(0, 0.8, 0, 1), size=3.0)
        self.points.setData(pos=np.zeros((1, 3)))
        self.view.addItem(self.points)