def create_3D_brain_volume(self): # get MRI data nii = load('inplane001.nii') data = nii.get_data() # To complete for the lack of sampling in the third dimension data = np.repeat(data, repeats=4, axis=2) # Create viewer w = gl.GLViewWidget() w.setCameraPosition(0, 0, 90) w.opts['distance'] = 500 self.tab6.layout.addWidget(w) # w.show() # create color image channels d2 = np.empty(data.shape + (4, ), dtype=np.ubyte) d2[..., 0] = data * (255. / (data.max() / 1)) d2[..., 1] = d2[..., 0] d2[..., 2] = d2[..., 0] d2[..., 3] = d2[..., 0] d2[..., 3] = (d2[..., 3].astype(float) / 255.)**2 * 255 # RGB orientation lines (optional) d2[:, 0, 0] = [255, 0, 0, 255] d2[0, :, 0] = [0, 255, 0, 255] d2[0, 0, :] = [0, 0, 255, 255] v = gl.GLVolumeItem(d2, sliceDensity=1, smooth=False) v.translate(-d2.shape[0] / 2, -d2.shape[1] / 2, -150) w.addItem(v)
def do_render(self, projected): projected = self.rescale(projected) x, y, z, _ = projected.shape print(x, y, z) d = float(max(x, y, z) * 2) if self.plot is None: self.plot = gl.GLVolumeItem(projected, smooth=False) self.addItem(self.plot) self.axis = gl.GLAxisItem(glOptions="opaque") self.addItem(self.axis) self.opts['distance'] = self.distance = d else: # Latest version has .setData but is not in PyPi self.plot.data = projected self.plot.initializeGL() ratio = d / self.distance self.opts['distance'] *= ratio self.distance = d self.plot.resetTransform() self.plot.translate(-x / 2, -y / 2, -z / 2) self.axis.setSize(x, y, z) self.axis.resetTransform() self.axis.translate(-x / 2, -y / 2, -z / 2)
def vis3D_projections(view, inj_array, ds_factor=1): ds_factor = 1 # disabled ds_factor because it isn't implemented # render the injection(s) as a volume # inj_array should be a list of tuples, with the first element in the tuple # being the plotting color (a RGB value), and the second element being the # ND-array of the volumetric data for a given injection vols = np.zeros(inj_array[0][1].shape + (4, ), dtype='float32') for inj in range(len(inj_array)): col = inj_array[inj][0] vols[..., 0] += col[0] * inj_array[inj][1] # red channel vols[..., 1] += col[1] * inj_array[inj][1] # green channel vols[..., 2] += col[2] * inj_array[inj][1] # blue channel vols[..., 3] += inj_array[inj][1] * 255 # alpha channel # Set alpha and make sure the maximum alpha is 255 vols[..., 3] *= 5 vols[..., 3] = np.clip(vols[..., 3], 0, 255) # now add the volume to the view window vi = pgl.GLVolumeItem(vols) vi.translate(-vols.shape[0] * (ds_factor / 2.), -vols.shape[1] * (ds_factor / 2.), -vols.shape[2] * (ds_factor / 2.)) vi.scale(ds_factor, ds_factor, ds_factor) vi.setGLOptions('additive') vi.rotate(-90, 1, 0, 0) view.setCameraPosition(distance=200, elevation=20, azimuth=90) view.addItem(vi) return view
def set_voxel_data(self, data): """ :param data: voxel data or None :type data: numpy.ndarray """ if self._voxel_item is not None: self.removeItem(self._voxel_item) self._voxel_item = None if data is None: return # FIXME: this depends on the voxel length defined in MATLAB scale = 100.0 voxels = self.color_map.map(data / np.amax(data).astype(np.float32)) l = round(len(data)**(1 / 3.0)) voxels = voxels.reshape((l, l, l, 4), order='F') self._voxel_item = gl.GLVolumeItem(voxels, smooth=True, sliceDensity=10) t = -l / 2 * scale self._voxel_item.translate(t, t, t) self._voxel_item.scale(scale, scale, scale) self.addItem(self._voxel_item)
def create_3D_volume_from_3D_np_array(np_array_3D, show_axis=False, show_box=False, scale=1): if show_axis: # RGB orientation lines (optional) np_array_3D[:, 1, 1] = [255, 0, 0, 255] # R-x np_array_3D[1, :, 1] = [0, 255, 0, 255] # G-y np_array_3D[1, 1, :] = [0, 0, 255, 255] # B-z # Create a box at the extremity of the array if show_box: for i in (0, -1): np_array_3D[:, :, i] = [0, 255, 0, 20] np_array_3D[:, i, :] = [0, 255, 0, 20] np_array_3D[i, :, :] = [0, 255, 0, 20] v = gl.GLVolumeItem(np_array_3D, sliceDensity=5, smooth=True) # Translate v.translate(-np_array_3D.shape[0] / 2 * scale, -np_array_3D.shape[1] / 2 * scale, -np_array_3D.shape[2] / 2 * scale) # Scale v.scale(scale, scale, scale) # shape_x = np_array_3D.shape[0] # shape_y = np_array_3D.shape[1] # shape_z = np_array_3D.shape[2] return v
def __init__(self): gl.GLViewWidget.__init__(self) #w.setBackgroundColor((135,206,235)) # skyblue from gnuplot self.setBackgroundColor((255,255,255)) # white, good for report #w.setBackgroundColor((255,255,255)) # black, also useful? Nx,Ny,Nz = 16,16,16 Lx,Ly,Lz = 16,16,16 self.data = 2*np.random.rand(Nx,Ny,Nz) - 1 self.Nx,self.Ny,self.Nz,self.Lx,self.Ly,self.Lz = Nx,Ny,Nz,Lx,Ly,Lz self.transparency = 1. self.sliceHeight = Nz self.powerParameter = 1.0 # Add explicit bounding box boundingBox = gl.GLBoxItem() boundingBox.scale(Lx, Ly, Lz) boundingBox.setColor([0,0,0]) # Paint it black self.addItem(boundingBox) self.boundingBox = boundingBox # Add a GL volume item, the main attraction # It works by drawing a configurable number of planes per small volume # Uses lot's of interpolation. volItem = gl.GLVolumeItem([]) volItem.scale(Lx/Nx, Ly/Ny, Lz/Nz) self.addItem(volItem) self.volItem = volItem # store a reference self.updateVolumeData()
def create_3D_volume_from_3D_np_array(arr, scale=1): volume = gl.GLVolumeItem(arr, sliceDensity=5, smooth=False) # Translate volume.translate(-arr.shape[0] / 2 * scale, -arr.shape[1] / 2 * scale, -arr.shape[2] / 2 * scale) # Scale # v.scale(scale, scale, scale) return volume
def generate_volumetric_model(self, voxels): self.voxels = voxels.reshape(self.xDim/2, self.yDim/2, self.zDim/2) self.voxels = np.kron(self.voxels, np.ones((2,2,2))) self.volume = np.kron(self.volume, np.ones((2,2,2,1))) unit0Index = np.asarray(np.where(self.voxels == 0)).T unit1Index = np.asarray(np.where(self.voxels == 1)).T unit2Index = np.asarray(np.where(self.voxels == 2)).T unit3Index = np.asarray(np.where(self.voxels == 3)).T unit4Index = np.asarray(np.where(self.voxels == 4)).T unit5Index = np.asarray(np.where(self.voxels == 5)).T unit6Index = np.asarray(np.where(self.voxels == 6)).T self.volume[unit0Index[:, 0], unit0Index[:, 1], unit0Index[:, 2]] = [106, 25, 205, 100] self.volume[unit1Index[:, 0], unit1Index[:, 1], unit1Index[:, 2]] = [160, 82, 45, 100] self.volume[unit2Index[:, 0], unit2Index[:, 1], unit2Index[:, 2]] = [147, 112, 216, 100] self.volume[unit3Index[:, 0], unit3Index[:, 1], unit3Index[:, 2]] = [70, 130, 180, 100] self.volume[unit4Index[:, 0], unit4Index[:, 1], unit4Index[:, 2]] = [32, 178, 170, 100] self.volume[unit5Index[:, 0], unit5Index[:, 1], unit5Index[:, 2]] = [0, 255, 0, 100] self.volume[unit6Index[:, 0], unit6Index[:, 1], unit6Index[:, 2]] = [0, 0, 0, 0] """ for i in range(0, self.xDim): for j in range(0, self.yDim): for l in range(0, self.zDim): elif self.voxels[i][j][l] == -1: self.volume[i][j][l] = [106, 25, 205, 100] if self.voxels[i][j][l] == 0: self.volume[i][j][l] = [160, 82, 45, 100] elif self.voxels[i][j][l] == 1: self.volume[i][j][l] = [147, 112, 216, 100] #self.volume[i][j][l] = [160, 82, 45, 100] elif self.voxels[i][j][l] == 2: self.volume[i][j][l] = [70, 130, 180, 100] #self.volume[i][j][l] = [160, 82, 45, 100] elif self.voxels[i][j][l] == 3: self.volume[i][j][l] = [32, 178, 170, 100] elif self.voxels[i][j][l] == 4: self.volume[i][j][l] = [0, 255, 0, 100] #elif self.voxels[i][j][l] == 5: # self.volume[i][j][l] = [100, 100, 100, 50] elif self.dem_surf is None: self.volume[i][j][l] = [0, 0, 0, 0] """ self.voxelModel = gl.GLVolumeItem(self.volume, smooth=True, sliceDensity=1) self.voxelModel.translate(-(self.xDim / 2), -(self.yDim / 2), 0) self.VolumeModelView.addItem(self.voxelModel)
def __init__(self, title='Volume Plot', origin=(0.0, 0.0, 0.0), roi=(1.0, 1.0, 1.0), size=(800, 600), parent=None): Viewer3D.__init__(self, title, origin, roi, size, parent) self.v = gl.GLVolumeItem(data=None) self.addItem(self.v)
def buttonTestView_clicked(self): ## Add grid to the 3D volume g = gl.GLGridItem() g.scale(10, 10, 1) self.graphicsViewStreamingData.addItem(g) ## Add data to the 3D volume data = MockVizData.Trace.generate() v = gl.GLVolumeItem(data) v.translate(-50, -50, -100) self.graphicsViewStreamingData.addItem(v)
def init_plane_item(self): cols = 150 rows = 150 plane = np.empty((cols, rows, 1) + (4, ), dtype=float) plane[:, :] = self.color item = gl.GLVolumeItem(plane, sliceDensity=5, smooth=True) item.scale(self.scale, self.scale, 1) init_pos = np.array([-cols // 2, -rows // 2, 0]) # self.pos += mvt item.translate(*init_pos) item.rotate(*self.rotation) return item
def __init__(self, log_dir): super(Visualizer, self).__init__() self.log_dir = log_dir self.show() self.ax = gl.GLAxisItem() self.ax.setSize(100,100,100) self.addItem(self.ax) self.v = gl.GLVolumeItem(np.zeros((10, 10, 10) + (4,), dtype=np.ubyte), smooth=False) self.addItem(self.v) self.setCameraPosition(azimuth=150, distance=150, elevation=0) self.read_collected.connect(self.set_data)
def showing_3D(matrix_3D=np.zeros((100, 100, 100)), Trans=120): # N là kích thước của vật thể 3 chiều # Mapping ảnh GrayScale sang ảnh màu RGB red = np.zeros((matrix_3D.shape), dtype=np.uint8) green = np.zeros((matrix_3D.shape), dtype=np.uint8) blue = np.zeros((matrix_3D.shape), dtype=np.uint8) # Thực hiện biến đổi màu cho toàn bộ không gian 3D for i in range(0, matrix_3D.shape[2]): RGB_Img = cv2.applyColorMap(matrix_3D[:, :, i], cv2.COLORMAP_JET) red[:, :, i] = RGB_Img[:, :, 0] green[:, :, i] = RGB_Img[:, :, 1] blue[:, :, i] = RGB_Img[:, :, 2] # Tạo không gian màu 4 chiều RGBA object_4D = np.empty(matrix_3D.shape + (4, ), dtype=np.uint8) # Nạp giá trị màu vào không gian object_4D[:, :, :, 0] = blue object_4D[:, :, :, 1] = green object_4D[:, :, :, 2] = red object_4D[:, :, :, 3] = 120 # Hiển thị trục tọa độ object_4D[:, 0, 0] = [255, 0, 0, 100] object_4D[0, :, 0] = [0, 255, 0, 100] object_4D[0, 0, :] = [0, 0, 255, 100] # Khởi tạo giao diện hiển thị 3D dùng PyQT app = QtGui.QApplication([]) window_3D = gl.GLViewWidget() window_3D.opts['distance'] = 500 window_3D.show() window_3D.setWindowTitle('Reconstructed Object') ## Khởi tạo vật thể 3D từ ma trận màu 4D volume = gl.GLVolumeItem(object_4D) ## Tọa độ của điểm tâm volume.translate(-100, -100, -100) # Hiển thị vật thể 3D window_3D.addItem(volume) # ## 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_() # Configuration volume return
def view3d(self, image3D): '''creates 3d rendering of current image stack, scale increase brightness''' self.Image3D=image3D if self.bViewSphereCenters: self.sphereCenterImage[0,0,0]=2*np.amax(image3D) if not hasattr(self,"view3Dwin"): self.view3Dwin = gl.GLViewWidget() self.view3Dwin.opts['distance'] = 300 self.view3Dwin.resize(800,800) self.view3Dwin.setWindowTitle('3D View ' ) self.view3Dwin.show() try: self.view3Dwin.removeItem(self.image3DVol) except: pass ax = gl.GLAxisItem() self.view3Dwin.addItem(ax) data=self.scale3D*image3D.astype(float) /float(image3D.max()) #normalize data to 1 if self.bViewSphereCenters: mask=2*self.scale3D*self.sphereCenterImage.astype(float) /float(self.sphereCenterImage.max()) if self.view3Dinvert : data=1-data if self.bViewSphereCenters: d2 = np.empty(data.shape + (4,), dtype=np.ubyte) d2[..., 0] = data * self.view3DColor.red() d2[..., 1] = data * self.view3DColor.green() d2[..., 2] = mask * self.view3DColor.blue() d2[..., 3] = (data)**self.view3DTransparency * 255. #sets transparency d2[:, 0:3, 0:3] = [255,0,0,20] #draw axes at corner of box d2[0:3, :, 0:3] = [0,255,0,20] d2[0:3, 0:3, :] = [0,0,255,20] else: d2 = np.empty(data.shape + (4,), dtype=np.ubyte) d2[..., 0] = data * self.view3DColor.red() d2[..., 1] = data * self.view3DColor.green() d2[..., 2] = data * self.view3DColor.blue() d2[..., 3] = (data)**self.view3DTransparency * 255. #sets transparency d2[:, 0:3, 0:3] = [255,0,0,20] #draw axes at corner of box d2[0:3, :, 0:3] = [0,255,0,20] d2[0:3, 0:3, :] = [0,0,255,20] self.image3DVol=gl.GLVolumeItem(d2) self.image3DVol.translate(-128,-128,-128) self.view3Dwin.addItem(self.image3DVol)
def update_all(self, only_fit_range: bool = False, *args, **kwargs): fit = self.fit pdb_filename = './test/data/atomic_coordinates/pdb_files/hGBP1_closed.pdb' residue_number = 18 atom_name = 'CB' free_diffusion = 8.0 atomic_slow_factor = 0.9 contact_distance = 4.5 av = chisurf.fluorescence.av.ACV( pdb_filename, radius1=5.0, linker_length=21.5, residue_seq_number=residue_number, atom_name=atom_name, diffusion_coefficients=(free_diffusion, atomic_slow_factor)) alpha = 0.1 data = av.rate_map min_v, max_v = chisurf.math.datatools.minmax(data.flatten(), ignore_zero=True) d1 = cm.jet((data - min_v) / (max_v - min_v)) * 255 d1 = d1.astype(dtype=np.ubyte) d2 = np.zeros_like(d1) nx, ny, nz = data.shape for ix in range(nx): for iy in range(ny): for iz in range(nz): d2[ix, iy, iz, 0] = d1[ix, iy, iz, 0] d2[ix, iy, iz, 1] = d1[ix, iy, iz, 1] d2[ix, iy, iz, 2] = d1[ix, iy, iz, 2] d2[ix, iy, iz, 3] = 255 * alpha if data[ix, iy, iz] > 0.0 else 0 #d2 = av.points v = gl.GLVolumeItem(d2) v.translate(-nx / 2, -ny / 2, -nz / 2) self.quenching_widget.addItem(v) ax = gl.GLAxisItem() self.quenching_widget.addItem(ax) self.quenching_widget.show()
def load_files(self, filenames): """Load *filenames* for display.""" filenames = filenames[::self.step] num = len(filenames) first = read_tiff(filenames[0])[::self.step, ::self.step] width, height = first.shape data = np.empty((width, height, num), dtype=np.float32) data[:,:,0] = first for i, filename in enumerate(filenames[1:]): data[:, :, i + 1] = read_tiff(filename)[::self.step, ::self.step] volume = create_volume(data) dx, dy, dz, _ = volume.shape volume_item = gl.GLVolumeItem(volume, sliceDensity=self.density) volume_item.translate(-dx / 2, -dy / 2, -dz / 2) volume_item.scale(0.05, 0.05, 0.05, local=False) self.volume_view.addItem(volume_item)
def __init__(self, map_3d): super(Show_vol, self).__init__() # 3D plot for psi self.w = gl.GLViewWidget() self.w.opts['distance'] = 200 self.w.show() # layout vlayout = QtGui.QVBoxLayout() vlayout.addWidget(self.w) data = map_3d d = np.empty(data.shape + (4, ), dtype=np.ubyte) # white scale dis = 255. #(data.astype(np.float) * (255./data.max())).astype(np.ubyte) alpha = (data.astype(np.float) * (255. / data.max())).astype(np.ubyte) d[..., 0] = dis d[..., 1] = dis d[..., 2] = dis d[..., 3] = alpha #((data/data.max())**2 * 255.).astype(np.ubyte) # show the x-y-z axis d[:, 0, 0] = [255, 0, 0, 100] d[0, :, 0] = [0, 255, 0, 100] d[0, 0, :] = [0, 0, 255, 100] self.v = gl.GLVolumeItem(d) self.v.translate(-data.shape[0] / 2, -data.shape[1] / 2, -data.shape[2] / 2) self.w.addItem(self.v) ax = gl.GLAxisItem() self.w.addItem(ax) self.setLayout(vlayout) self.resize(800, 800) self.show()
def main(args): app = QtGui.QApplication([]) w = gl.GLViewWidget() w.opts['distance'] = 200 w.show() #b = gl.GLBoxItem() #w.addItem(b) g = gl.GLGridItem() g.scale(10, 10, 1) w.addItem(g) data = np.fromfunction(psi, (100, 100, 200)) positive = np.log(np.clip(data, 0, data.max())**2) negative = np.log(np.clip(-data, 0, -data.min())**2) d2 = np.empty(data.shape + (4, ), dtype=np.ubyte) d2[..., 0] = positive * (255. / positive.max()) d2[..., 1] = negative * (255. / negative.max()) d2[..., 2] = d2[..., 1] d2[..., 3] = d2[..., 0] * 0.3 + d2[..., 1] * 0.3 d2[..., 3] = (d2[..., 3].astype(float) / 255.)**2 * 255 d2[:, 0, 0] = [255, 0, 0, 100] d2[0, :, 0] = [0, 255, 0, 100] d2[0, 0, :] = [0, 0, 255, 100] v = gl.GLVolumeItem(d2) v.translate(-50, -50, -100) w.addItem(v) ax = gl.GLAxisItem() w.addItem(ax) ## Start Qt event loop unless running in interactive mode. if sys.flags.interactive != 1: app.exec_()
def create_3D_brain_volume(self, show_axis=False, show_box=False, scale=1): if show_axis: # RGB orientation lines (optional) self.brain[:, 1, 1] = [255, 0, 0, 255] # R-x self.brain[1, :, 1] = [0, 255, 0, 255] # G-y self.brain[1, 1, :] = [0, 0, 255, 255] # B-z # Create a box at the extremity of the array if show_box: for i in (0, -1): self.brain[:, :, i] = [0, 255, 0, 20] self.brain[:, i, :] = [0, 255, 0, 20] self.brain[i, :, :] = [0, 255, 0, 20] v = gl.GLVolumeItem(self.brain, sliceDensity=5, smooth=True) v.translate(-self.brain.shape[0] / 2 * scale, -self.brain.shape[1] / 2 * scale, -self.brain.shape[2] / 2 * scale) v.scale(scale, scale, scale) self.shape_x = self.brain.shape[0] self.shape_y = self.brain.shape[1] self.shape_z = self.brain.shape[2] return v
d2[..., 2] = d2[..., 0] d2[..., 3] = d2[..., 0] d2[..., 3] = (d2[..., 3].astype(float) / 255.)**2 * 255 #d2[..., 3] = rh2 * 255 d2[:, 0, 0] = [255, 0, 0, 100] d2[0, :, 0] = [0, 255, 0, 100] d2[0, 0, :] = [0, 0, 255, 100] from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph.opengl as gl app = QtGui.QApplication([]) w = gl.GLViewWidget() w.opts['distance'] = Lx * 2 w.show() w.setWindowTitle('Logathmic density contrast') v = gl.GLVolumeItem(d2) v.translate(-int(Lx / 2), -int(Ly / 2), -int(Lz / 2)) w.addItem(v) ax = gl.GLAxisItem() w.addItem(ax) ## 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_()
edgeColor=(1, 0, 0, 1), shader='balloon') m5.rotate(90, 1, 0, 0) m5.rotate(-pargs.rotate, 0, 0, 1) if pargs.rotate > 45.: camX = offset[X] camY = offset[Y] * np.tan((90 - pargs.rotate) * np.pi / 180) else: camX = offset[X] * np.tan((pargs.rotate) * np.pi / 180) camY = offset[Y] m5.translate(camX, camY, 0) w.addItem(m5) #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, # show the scene v = gl.GLVolumeItem(scene) v.translate(-offset[0], -offset[1], -offset[2]) w.addItem(v) # add axis grate ax = gl.GLAxisItem() w.addItem(ax) # enable Ctrl-C to kill application import signal signal.signal(signal.SIGINT, signal.SIG_DFL) ## 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_()
colors[..., 3] = alpha.reshape( data.shape) #turns into a 1d array to copy values over ##adds axis to edge of box #colors[:, 0, 0] = [255,0,0,100] #xaxis = red #colors[49:51,0,0] = [255,255,0,255] #colors[99:101,0,0] = [255,255,0,255] #colors[149:151,0,0] = [255,255,0,255] #colors[199:201,0,0] = [255,255,0,255] # #colors[0, :, 0] = [0,255,0,100] #yaxis = green #colors[0, 0, :] = [0,0,255,100] #zaxis = blue ############################################################################### #creates 3d volume item v = gl.GLVolumeItem(data=colors, glOptions='translucent') #translucent or additive #brings 3d graph to the center translator = data.shape v.translate(-translator[0] // 2, -translator[1] // 2, -translator[2] // 2 - 8) # 95 ) ##empties lists to save memory #alpha = [] #data = [] #dataline = [] w.addItem(v) ax = gl.GLAxisItem() w.addItem(ax)
view.sizeHint = lambda: pg.QtCore.QSize(1700, 800) cb.sizeHint = lambda: pg.QtCore.QSize(100, 800) layout.setHorizontalSpacing(0) cm = gw.colorMap() start_time = time.time() volume_data = get_transmurality_data_colorbar(verts, mask_epi_3d, mask_endo_3d, cm) end_time = time.time() print('marching_cubes : ', end_time - start_time) slden = 20 # 20 volume_data = gl.GLVolumeItem(volume_data, sliceDensity=slden, smooth=False) volume_data.translate(-avgX, -avgY, -avgZ) view.addItem(volume_data) dst = 100 view.setCameraPosition(distance=dst) win.show() elif vis3D_method == 'glmeshitem': print(vis3D_method) applicationDefinition = QtWidgets.QApplication(sys.argv) win = QtWidgets.QWidget() layout = QtWidgets.QGridLayout()
def update(self): self.__n = self.__input_n.value() self.__l = self.__input_l.value() self.__m = self.__input_m.value() self.__Z = self.__input_Z.value() # print("Plotting", self.__n, self.__l, self.__m, self.__Z) if self.__n <= 0 or not 0 <= self.__l < self.__n or abs( self.__m) > self.__l: self.__infoLabel.setText("Invalid values") return self.__infoLabel.setText("Plotting") # Radial wavefunction sym_r = sympy.var("sym_r") self.radial = sympy.lambdify( sym_r, sympy.physics.hydrogen.R_nl(self.__n, self.__l, sym_r, self.__Z)) offset = self.__rdist / 2 # Compute psi for every point in the desired space for x in range(0, self.__rdist): for y in range(0, self.__rdist): for z in range(0, self.__rdist): self.__data[x, y, z] = self.psi_cartesian( self.__zoom * (x - offset), self.__zoom * (y - offset), self.__zoom * (z - offset)) self.__abs = np.abs(self.__data) self.__abs.astype(float) self.__abs = np.power(self.__abs, 2) # print(abs) # print(abs.max()) # print(abs.min()) # print(abs[0,:,:]) # clipped = np.log(np.clip(abs, 0, abs.max()) ** 2) # positive = np.log(np.clip(abs, 0, abs.max()) ** 2) # negative = np.log(np.clip(-abs, 0, -abs.min()) ** 2) # d2 array has the form x, y, z, RGBA # http://www.pyqtgraph.org/documentation/3dgraphics/glvolumeitem.html d2 = np.zeros(self.__abs.shape + (4, ), dtype=np.ubyte) # R d2[..., 0] = self.__abs * (255. / self.__abs.max()) # G d2[..., 1] = d2[..., 0] # B d2[..., 2] = d2[..., 0] # A d2[..., 3] = d2[..., 0] d2[..., 3] = ((d2[..., 3] / 255.)**2) * 255 d2[:, 0, 0] = [255, 0, 0, 100] d2[0, :, 0] = [0, 255, 0, 100] d2[0, 0, :] = [0, 0, 255, 100] # plt.imshow(abs[0,:,:]) # plt.show() if self.__first: self.__first = False self.__volume = gl.GLVolumeItem(d2) self.__volume.translate(-offset, -offset, -offset) self.__widget.addItem(self.__volume) else: self.__volume.setData(d2) self.__infoLabel.setText("Ready")
def main(args): alpha = args.alpha N = args.N k = 4 print 'alpha:', alpha print 'N:', N print 'k:', k print M = np.array(list(multinomstate.gen_states(N, k)), dtype=int) T = multinomstate.get_inverse_map(M) R_mut = wrightcore.create_mutation(M, T) R_drift = wrightcore.create_moran_drift_rate_k4(M, T) Q = alpha * R_mut + R_drift P = scipy.linalg.expm(Q) v = MatrixUtil.get_stationary_distribution(P) # # Define the volumetric data using the stationary distribution. max_prob = np.max(v) d2 = np.zeros((N + 1, N + 1, N + 1, 4), dtype=float) U = np.array([ [0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0], ], dtype=int) for p, state in zip(v, M): x, y, z = np.dot(state, U).tolist() # r, g, b, alpha d2[x, y, z] = np.array( [ 255 * (p / max_prob), 0, 0, 255 * (p / max_prob), #100, ], dtype=float) #d2[x, y, z, 0] = 255 * (p / max_prob) #d2[x, y, z, 1] = 0 #d2[x, y, z, 2] = 0 #d2[x, y, z, 3] = 100 # fill the empty states for x in range(N + 1): for y in range(N + 1): for z in range(N + 1): if (x + y + z) % 2 == 1: p_accum = np.zeros(4, dtype=float) n_accum = 0 for dx in (-1, 1): if 0 <= x + dx <= N: p_accum += d2[x + dx, y, z] n_accum += 1 for dy in (-1, 1): if 0 <= y + dy <= N: p_accum += d2[x, y + dy, z] n_accum += 1 for dz in (-1, 1): if 0 <= z + dz <= N: p_accum += d2[x, y, z + dz] n_accum += 1 d2[x, y, z] = p_accum / n_accum # # Do things that the example application does. app = QtGui.QApplication([]) w = gl.GLViewWidget() w.opts['distance'] = 2 * N w.show() # # a visual grid or something #g = gl.GLGridItem() #g.scale(10, 10, 1) #w.addItem(g) # # Do some more things that the example application does. vol = gl.GLVolumeItem(d2, sliceDensity=1, smooth=True) #vol.translate(-5,-5,-10) vol.translate(-0.5 * N, -0.5 * N, -0.5 * N) w.addItem(vol) # # add an axis thingy #ax = gl.GLAxisItem() #w.addItem(ax) if sys.flags.interactive != 1: app.exec_()
from os.path import expanduser, join from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph.opengl as gl import numpy as np filePath = join(expanduser("~/Desktop"), 'array_4D_data.npy') data = np.load(filePath) print(data.shape) data = data.reshape((152, 357, 3, 256)) # create qtgui app = QtGui.QApplication([]) w = gl.GLViewWidget() w.orbit(256, 256) w.setCameraPosition(0, 0, 0) w.opts['distance'] = 200 w.show() w.setWindowTitle('pyqtgraph example: GLVolumeItem') g = gl.GLGridItem() g.scale(20, 20, 1) w.addItem(g) v = gl.GLVolumeItem(data, sliceDensity=1, smooth=False, glOptions='translucent') #v.translate(-data.shape[0]/2, -data.shape[1]/2, -150) w.addItem(v)
def manualCorrectionGUI(): """ Main function to manually correct the connections. The actual implementation of the GUI is defined in `manualCorrectionGUIDetail.py` """ start_time = timeit.default_timer() baseFolder = os.path.abspath(os.path.dirname(__file__)) app = pg.QtGui.QApplication([]) # w = gl.GLViewWidget() # w.opts['distance'] = 800 # w.setGeometry(0, 110, 1920, 1080) ex = Vessel() w = ex.plotwidget elapsed = timeit.default_timer() - start_time print('Elapsed: {} sec'.format(elapsed)) directory = baseFolder vesselVolumeFilePath = os.path.join(baseFolder, 'vesselVolumeMask.nii.gz') vesselImg = nib.load(vesselVolumeFilePath) vessel = vesselImg.get_data() skeletonFilePath = os.path.join(baseFolder, 'skeleton.nii.gz') skeletonImg = nib.load(skeletonFilePath) skeleton = skeletonImg.get_data() shape = skeleton.shape offset = np.array(shape) / (-2.0) affineTransform = np.sign(np.diag(skeletonImg.affine)[:3]) graphFilePath = os.path.join(baseFolder, 'graphRepresentation.graphml') G = nx.read_graphml(graphFilePath, node_type=make_tuple) plotItemCounter = 0 ##### skeletonCoords = np.array(np.where(skeleton != 0), dtype=np.int16).T ##### d2 = np.empty(vessel.shape + (4,), dtype=np.ubyte) d2[..., 0] = vessel * (255./(vessel.max()/1)) d2[..., 1] = d2[..., 0] d2[..., 2] = d2[..., 0] d2[..., 3] = d2[..., 0] d2[..., 3] = 10#(d2[..., 3].astype(float) / 255.)**2 * 255 glOptions = 'additive' v = gl.GLVolumeItem(d2, sliceDensity=1, smooth=True, glOptions=glOptions) v.translate(-d2.shape[0]/2, -d2.shape[1]/2, -d2.shape[2]/2) w.addItem(v) plotItemCounter += 1 skeletonColor = np.full((len(skeletonCoords), 4), 1) skeletonColor[:, 1:3] = 0 skeletonScatterPlot = gl.GLScatterPlotItem(pos=skeletonCoords, size=6, color=skeletonColor) skeletonScatterPlot.translate(-shape[0]/2, -shape[1]/2, -shape[2]/2) w.addItem(skeletonScatterPlot) skeletonNodesStartIndex = plotItemCounter plotItemCounter += 1 segmentListFilePath = os.path.join(baseFolder, 'segmentList.npz') segmentList = np.load(segmentListFilePath) segmentList = list(segmentList['segmentList']) segmentStartIndex = plotItemCounter plotItemCounter += 1 segmentCounter = 0 indexVolume = np.full(shape, -1) segmentListDict = {} for segment in segmentList: segmentCoords = np.array(segment) aa = gl.GLLinePlotItem(pos=segmentCoords, color=pg.glColor('r'), width=3) aa.translate(-shape[0]/2, -shape[1]/2, -shape[2]/2) w.addItem(aa) indexVolume[tuple(segmentCoords.T)] = segmentCounter G.add_path(segment, segmentIndex=segmentCounter) segmentListDict[tuple(segment)] = segmentCounter w.segmentIndexUsed.append(segmentCounter) segmentCounter += 1 plotItemCounter += 1 print('There are {} segments'.format(len(segmentList))) eventListFilePath = os.path.join(baseFolder, 'eventList.pkl') removeListFilePath = os.path.join(baseFolder, 'removeList.npy') removeListAutoFilePath = os.path.join(baseFolder, 'removeListAuto.npy') if os.path.exists(eventListFilePath): with open(eventListFilePath, 'rb') as f: eventList = pickle.load(f) print('eventList loaded with {} events'.format(len(eventList))) elif os.path.exists(removeListFilePath): removeList = list(np.load(removeListFilePath)) removeList = np.unique(removeList).tolist() print('removeList loaded with {} segments'.format(len(removeList))) elif os.path.exists(removeListAutoFilePath): removeList = list(np.load(removeListAutoFilePath)) removeList = np.unique(removeList).tolist() print('removeListAuto loaded with {} segments'.format(len(removeList))) else: removeList = w.removeList print('Using empty removeList') cycle2SegmentDict = {} segment2CycleDict = {} w.show() w.addExtraInfo(skeletonNodesStartIndex=skeletonNodesStartIndex, segmentStartIndex=segmentStartIndex, indexVolume=indexVolume, affineTransform=affineTransform, offset=offset, cycle2SegmentDict=cycle2SegmentDict, segment2CycleDict=segment2CycleDict, segmentList=segmentList, G=G, segmentListDict=segmentListDict, resultFolder=directory) w.checkCycle() try: eventList except NameError: eventList = [] for segmentIndex in removeList: event = {'type': 'remove', 'nodeIndex': 0, 'segmentIndex': segmentIndex} eventList.append(event) finally: for eventIndex, event in enumerate(eventList): print(eventIndex) success, event = w.processEvent(event) if success: w.eventList.append(event) # for segmentIndex in removeList: # event = {'type': 'remove', 'nodeIndex': 0, 'segmentIndex': segmentIndex} # success, event = w.processEvent(event) # if success: # w.eventList.append(event) w.checkCycle() w.onLoading = False # w.reportCycleInfo() elapsed = timeit.default_timer() - start_time print('Elapsed: {} sec'.format(elapsed)) pg.QtGui.QApplication.exec_() removeList = w.removeList removeListFilePath = os.path.join(baseFolder, 'removeList.npy') np.save(removeListFilePath, removeList) print('removeList saved with {} segments marked for deletion (ID = {})'.format(len(removeList), removeList)) elapsed = timeit.default_timer() - start_time print('Elapsed: {} sec'.format(elapsed))
# prepare voxel array voxel = np.empty(data.shape + (4, ), dtype=np.ubyte) voxel[..., 0] = ctable[data, 0] # red voxel[..., 1] = ctable[data, 1] # green voxel[..., 2] = ctable[data, 2] # blue voxel[..., 3] = ctable[data, 3] # transparency # initialize GLViewWidget() app = QtGui.QApplication([]) w = gl.GLViewWidget() w.show() w.setWindowTitle(name) w.setCameraPosition(distance=100, elevation=90, azimuth=-90) # view from top # display grid in (x,y)-plane g = gl.GLGridItem() g.scale(1 / dx, 1 / dy, 1 / dz) w.addItem(g) # add coordinate axes object ax = gl.GLAxisItem() ax.setSize(10, 10, 10) w.addItem(ax) v = gl.GLVolumeItem(voxel, sliceDensity=1, smooth=True) v.translate(-nx / 2, -ny / 2, -nz / 2) w.addItem(v) QtGui.QApplication.instance().exec_()
w.setWindowTitle('pyqtgraph example: GLVolumeItem') g = gl.GLGridItem() g.scale(10, 10, 1) w.addItem(g) ## A = linspace(0, 10, 101) L = linspace(0, 10, 101) t = linspace(0, 10, 101) c = [255, 0, 0, 100] A, L, t, c = ix_(A, L, t, c) G = A * exp(L + t) G = G / G.max() G1 = G * c print(G1) print(G1.shape) v = gl.GLVolumeItem(G1) #v.translate(-50,-50,-50) w.addItem(v) ax = gl.GLAxisItem() w.addItem(ax) if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
def __init__(self): # Gathers list of files fileMeas = sorted([x for x in [y for y in os.listdir("./")] if re.search("axion.m.[0-9]{5}$", x)]) # Filters the files so only those with an energy density map are listed fFiles = {} Lx = -1 Lz = -1 for cFile in fileMeas: fileHdf5 = h5py.File(cFile, "r") cTheta = 'energy/density/cTheta' in fileHdf5 if cTheta: Lx = fileHdf5["/energy/density/"].attrs.get("Size") Lz = fileHdf5["/energy/density/"].attrs.get("Depth") cHash = str(Lx)+str(Lz) if cHash in fFiles.keys(): fFiles[cHash].append(cFile) else: fFiles[cHash] = [] fFiles[cHash].append(cFile) fileHdf5.close() maxLen = 0 cKey = '' for key in fFiles.keys(): if len(fFiles[key]) > maxLen: maxLen = len(fFiles[key]) cKey = key self.allFiles = fFiles[key] self.nFiles = len(self.allFiles) aFHdf5 = h5py.File(self.allFiles[0], "r") self.Lx = aFHdf5["/energy/density/"].attrs.get("Size") self.Lz = aFHdf5["/energy/density/"].attrs.get("Depth") self.step = 1 self.tStep = 100 self.pause = False self.current = 0 self.timer = pg.QtCore.QTimer() pg.setConfigOptions(antialias=True) self.app = QtGui.QApplication([]) self.view = GLViewWithText() #gl.GLViewWidget() self.view.show() xGrid = gl.GLGridItem() yGrid = gl.GLGridItem() zGrid = gl.GLGridItem() self.view.addItem(xGrid) self.view.addItem(yGrid) self.view.addItem(zGrid) xGrid.rotate(90, 0, 1, 0) yGrid.rotate(90, 1, 0, 0) xGrid.translate(-1.0, 0, 0) yGrid.translate(0, -1.0, 0) zGrid.translate(0, 0, -1.0) xGrid.scale(0.1, 0.1, 0.1) yGrid.scale(0.1, 0.1, 0.1) zGrid.scale(0.1, 0.1, 0.1) conData = aFHdf5['/energy/density']['cTheta'].value.reshape(self.Lx,self.Lx,self.Lz) meanData = np.mean(conData) conData = conData/meanData self.data = np.zeros(conData.shape + (4,), dtype=np.ubyte) pData = np.clip(conData, 0, 10)**2 self.data[..., 0] = pData * (255./pData.max()) self.data[..., 1] = self.data[..., 0] self.data[..., 2] = self.data[..., 0] self.data[..., 3] = ((self.data[...,0].astype(float)/255.)**2)*255 self.z = aFHdf5['/'].attrs.get("z") self.view.updateZ(self.z) self.plt = gl.GLVolumeItem(self.data) self.view.addItem(self.plt) self.plt.scale(2./float(self.Lx), 2./float(self.Lx), 2./float(self.Lz)) self.plt.translate(-1.0,-1.0,-1.0) aFHdf5.close()