def plot_data(self, data, outPath="3-D_figure", marker='sphere', size=2, heatmap=None, inline=False, plot_type="scatter"): ipv.figure(width=400, height=500, lighting=True, controls=True) x, y, z = data[0], data[1], data[2] #TODO: marker control if heatmap == None: if plot_type == "scatter": ipv.quickscatter(x, y, z, marker=marker, size=size) #, size=10) if plot_type == "surface": ipv.plot_surface(x, y, z) else: from matplotlib import cm colormap = cm.coolwarm heatmap /= (heatmap - heatmap.min()) color = colormap(heatmap) if plot_type == "scatter": ipv.quickscatter(x, y, z, color=color[..., :3], marker=marker, size=size) #, size=10) if plot_type == "surface": ipv.plot_surface(x, y, z, color=color) #ipv.plot_surface(data[0], data[1], data[2], color="orange") #ipv.plot_wireframe(data[0], data[1], data[2], color="red") ipv.pylab.xlim(self.xlim[0], self.xlim[1]) ipv.pylab.ylim(self.ylim[0], self.ylim[1]) if self.zlim != [None, None]: ipv.pylab.zlim(self.zlim[0], self.zlim[1]) else: ipv.pylab.zlim(self.ylim[0], self.ylim[1]) #ipv.style.use(['seaborn-darkgrid', {'axes.x.color':'orange'}]) ipv.pylab.view(azimuth=-45, elevation=25, distance=5) ipv.pylab.xlabel("%s" % self.axis_labels[0]) ipv.pylab.ylabel("%s" % self.axis_labels[1]) ipv.pylab.zlabel("%s" % self.axis_labels[2]) if inline: ipv.show() else: ipv.pylab.save("%s.html" % outPath, title=r"%s" % (latex), offline=None, template_options=(('extra_script_head', ''), ('body_pre', ''), ('body_post', ''))) run_cmd('open %s.html' % (str(outPath)))
def update_cube(self, update_coordinates=True): # The dimensions to be sliced have been saved in slider_dims self.cube = self.data_array self.last_changed_slider_dim = None # Slice along dimensions with buttons who have no value, i.e. the # dimension is not used for any axis. This reduces the data volume to # a 3D cube. for dim, val in self.slider.items(): if self.buttons[dim].value is None: self.lab[dim].value = self.make_slider_label( self.slider_x[self.name][dim], val.value) self.cube = self.cube[dim, val.value] # The dimensions to be sliced have been saved in slider_dims button_dim = dict() vslices = dict() # Slice along dimensions with sliders who have a button value for dim, val in self.slider.items(): if self.buttons[dim].value is not None: s = self.buttons[dim].value.lower() button_dim[s] = dim self.lab[dim].value = self.make_slider_label( self.slider_x[self.name][dim], val.value) vslices[s] = { "slice": self.cube[dim, val.value], "loc": self.slider_x[self.name][dim].values[val.value] } # Now make 3 slices wframes = None meshes = None if update_coordinates: wframes = self.get_outlines() meshes = self.get_meshes() surf_args = dict.fromkeys(self.permutations) wfrm_args = dict.fromkeys(self.permutations) for key, val in sorted(vslices.items()): if update_coordinates: perm = self.permutations[key] surf_args[key] = np.ones_like(meshes[key][perm[0]]) * \ val["loc"] wfrm_args[key] = np.ones_like(wframes[key][perm[0]]) * \ val["loc"] for p in perm: surf_args[p] = meshes[key][p] wfrm_args[p] = wframes[key][p] self.wireframes[key] = ipv.plot_wireframe(**wfrm_args, color="red") self.wireframes[key].visible = False self.surfaces[key] = ipv.plot_surface(**surf_args) self.members["wireframes"][key] = \ self.wireframes[key] self.members["surfaces"][key] = self.surfaces[key] self.surfaces[key].color = self.scalar_map.to_rgba( self.check_transpose(val["slice"]).flatten()) return
def plot_mesh(value_mesh_list, w1_mesh, w2_mesh, save, show_box, show_axes): ipv.clear() figs = [] for mesh in value_mesh_list: fig = ipv.pylab.figure() fig.camera.up = (0, 0, 1) fig.camera.position = (-2, 1, -0.5) fig.camera_control = "trackball" if not show_axes: ipv.style.box_off() else: ipv.xlabel("w1") ipv.ylabel("w2") ipv.zlabel("f_lambda") if not show_box: ipv.pylab.style.axes_off() ipv.pylab.zlim(mesh.min(), mesh.max()) ptp = (mesh - mesh.min()).ptp() col = [] for m in mesh: znorm = (m - m.min()) / (m.max() - m.min() + 1e-8) color = np.asarray([[interpolate(darker(colors_alpha[0], 1.5 * x + 0.75), darker(colors_alpha[1], 1.5 * (1 - x) + 0.75), x) for x in y] for y in znorm]) col.append(color) color = np.array(col) surf = ipv.plot_surface(w1_mesh, w2_mesh, mesh, color=color[..., :3]) ipv.animation_control(surf, interval=400) figs.append(fig) ipv.show() if save: ipv.save(f'renders/{datetime.datetime.now().strftime("%m%d-%H%M")}.html', offline=True) return figs
def plot_cone(cone: geometry.Cone, n_steps=20, **kwargs): """ Draw a cone surface. cone: a Cone object n_steps: number of steps in the parametric range used for drawing (more gives a smoother surface, but may render more slowly) """ fig = ipv.plot_surface(*geometry.cone_surface(cone, n_steps=n_steps), **kwargs) return fig
def test_animation_control(): fig = ipv.figure() n_points = 3 n_frames = 4 ar = np.zeros(n_points) ar_frames = np.zeros((n_frames, n_points)) colors = np.zeros((n_points, 3)) colors_frames = np.zeros((n_frames, n_points, 3)) scalar = 2 s = ipv.scatter(x=scalar, y=scalar, z=scalar) with pytest.raises(ValueError): # no animation present slider = ipv.animation_control(s, add=False).children[1] s = ipv.scatter(x=ar, y=scalar, z=scalar) slider = ipv.animation_control(s, add=False).children[1] assert slider.max == n_points - 1 s = ipv.scatter(x=ar_frames, y=scalar, z=scalar) slider = ipv.animation_control(s, add=False).children[1] assert slider.max == n_frames - 1 s = ipv.scatter(x=scalar, y=scalar, z=scalar, color=colors_frames) slider = ipv.animation_control(s, add=False).children[1] assert slider.max == n_frames - 1 Nx, Ny = 10, 7 x = np.arange(Nx) y = np.arange(Ny) x, y = np.meshgrid(x, y) z = x + y m = ipv.plot_surface(x, y, z) with pytest.raises(ValueError): # no animation present slider = ipv.animation_control(m, add=False).children[1] z = [x + y * k for k in range(n_frames)] m = ipv.plot_surface(x, y, z) slider = ipv.animation_control(m, add=False).children[1] assert slider.max == n_frames - 1
def _create_Ploy3DCollection(self, line1, line2, line3, line4, i=None, side=None): x, y, z = zip(line1, line2, line3, line4) if not self._is_vector: # print(x) X = np.array([__ for __ in iterable_to_chunks(x, 2)]) Y = np.array([__ for __ in iterable_to_chunks(y, 2)]) Z = np.array([__ for __ in iterable_to_chunks(z, 2)]) return ipv.plot_surface(X, Y, Z, color=self._color) else: self._X[side, i] = np.array([__ for __ in iterable_to_chunks(x, 2)]) self._Y[side, i] = np.array([__ for __ in iterable_to_chunks(y, 2)]) self._Z[side, i] = np.array([__ for __ in iterable_to_chunks(z, 2)]) # on the last iteration we make the plot and return it if i >= self._vector_length - 1: return ipv.plot_surface(self._X[side], self._Y[side], self._Z[side], color=self._color)
def plot_plane(plane: geometry.Plane, x_lim=None, y_lim=None, z_lim=None, limit_all=True, **kwargs): """ Draw a plane. The limited coordinates are called x and z, corresponding to the first and third components of `p` and `n`. The final y coordinate is calculated based on the equation for a plane. plane: a Plane object x_lim [optional]: iterable of the two extrema in the x direction y_lim [optional]: same as x, but for y z_lim [optional]: same as x, but for z limit_all [optional]: make sure that the plane surface plot is bound within all given limits """ if x_lim is None: x_lim = ipv.pylab.gcf().xlim if y_lim is None: y_lim = ipv.pylab.gcf().ylim if z_lim is None: z_lim = ipv.pylab.gcf().zlim x, y, z = geometry.plane_surface(plane, x_lim=x_lim, y_lim=y_lim, z_lim=z_lim) fig = ipv.plot_surface(x, y, z, **kwargs) if limit_all: if np.any(x < x_lim[0]) or np.any(x > x_lim[1]): ipv.pylab.xlim(*x_lim) if np.any(y < y_lim[0]) or np.any(y > y_lim[1]): ipv.pylab.ylim(*y_lim) if np.any(z < z_lim[0]) or np.any(z > z_lim[1]): ipv.pylab.zlim(*z_lim) return fig
def plot_expr(self, Fn, outPath, color="orange", box_off=False, axes_off=False, offline=False): ipv.figure(width=500, height=500, lighting=True, controls=True) Fns = [i for i in Fn.split(";")] for Fn in Fns: f = parse_expr(Fn) f_ = f.as_expr() latex = sp.latex(f) # Generate combnations of x,y,z and pick the correct variables given #.. the user input. _symbols = sp.symbols('x,y,z') for var1, var2 in combinations(_symbols, 2): func = lambdify( [_symbols[0], _symbols[1]], f_, modules=['numpy', 'scipy', { 'erf': scipy.special.erf }]) if (str(var1) and str(var2)) in Fn: func = lambdify( [var1, var2], f_, modules=['numpy', 'scipy', { 'erf': scipy.special.erf }]) break X, Y = np.linspace(self.xlim[0], self.xlim[1]), np.linspace( self.ylim[0], self.ylim[1]) xplot, yplot = np.meshgrid(X, Y) #zplot1 = float(100/n)*func(xplot, yplot) # 100/n is a normalization const. zplot1 = func(xplot, yplot) # 100/n is a normalization const. # only x is a sequence of arrays x, y, z = xplot, yplot, zplot1 #TODO: marker control #s = ipv.scatter(x, y, z, marker='sphere', size=10) #p3.clear() #ipv.pylab.volshow(np.array([x,y,z]), lighting=False, data_min=None, # data_max=None, max_shape=256, tf=None, stereo=False, # ambient_coefficient=0.5, diffuse_coefficient=0.8, # specular_coefficient=0.5, specular_exponent=5, downscale=1, # level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1, # controls=True, max_opacity=0.2, memorder='C', extent=None) ipv.plot_surface(x, y, z, color=color) ipv.plot_wireframe(x, y, z, color="red") del X, Y, xplot, yplot, zplot1 ipv.pylab.xlim(self.xlim[0], self.xlim[1]) ipv.pylab.ylim(self.ylim[0], self.ylim[1]) if self.zlim != [None, None]: ipv.pylab.zlim(self.zlim[0], self.zlim[1]) else: ipv.pylab.zlim(self.ylim[0], self.ylim[1]) ipv.style.use(['seaborn-darkgrid', {'axes.x.color': 'orange'}]) if box_off: ipv.style.box_off() if axes_off: ipv.style.axes_off() #ipv.pylab.view(azimuth=-45, elevation=25, distance=4) ipv.pylab.view(azimuth=85, elevation=25, distance=5) ipv.pylab.xyzlabel(labelx=self.axis_labels[0], labely=self.axis_labels[1], labelz=self.axis_labels[2]) ipv.pylab.save("%s.html" % outPath, title=r"%s" % (latex), offline=offline, template_options=(('extra_script_head', ''), ('body_pre', ''), ('body_post', '')))
def instrument_view(filename, id_path="/entry/event_data/event_id", colormap="viridis", log=False, size=1): """ Make a 3D instrument view using ipyvolume """ try: import ipyvolume as ipv except ImportError: print("Instrument view makes use of the ipyvolume package which was " "not found on this system. Install using pip install ipyvolume.") with h5py.File(filename, "r") as f: ids = np.array(f[id_path][...], dtype=np.int32, copy=True) # tofs = np.array(f[tof_path][...], dtype=np.float64, copy=True) / 1.0e3 x = np.array(f["/entry/instrument/detector_1/x_pixel_offset"][...], dtype=np.float64, copy=True) y = np.array(f["/entry/instrument/detector_1/y_pixel_offset"][...], dtype=np.float64, copy=True) # location = float(f["/entry/instrument/detector_1/transformations/location"][...]) # loc_vec = np.array(f["/entry/instrument/detector_1/transformations/location"].attrs["vector"][...], dtype=np.float64, copy=True) # rotation = float(f["/entry/instrument/detector_1/transformations/orientation"][...]) # rot_vec = np.array(f["/entry/instrument/detector_1/transformations/orientation"].attrs["vector"][...], dtype=np.float64, copy=True) nx, ny = np.shape(x) a, edges = np.histogram(ids, bins=np.arange(nx * ny + 1)) a = a.reshape(nx, ny) if log: with np.errstate(divide="ignore", invalid="ignore"): a = np.log10(a) # x = x.flatten() # y = y.flatten() # a = a.flatten() z = np.zeros_like(x) # # Apply rotation # # TODO: this currently only works for rotation around y axis # # Need to generalise this with rotation matrix # rotation *= np.pi / 180.0 # x = x * np.cos(rotation) # z = x * np.sin(rotation) # # Apply translation # x += location * loc_vec[0] # y += location * loc_vec[1] # z += location * loc_vec[2] # x *= 100. # y *= 100. # z *= 100. norm = cm.colors.Normalize(vmax=a.max(), vmin=a.min()) colormap = cm.viridis color = colormap(norm(a.flatten())) # t = np.linspace(0.0, 7.2e4, nbins + 1) # z, xe, ye = np.histogram2d(ids, tofs, bins=[np.arange(nx * ny + 1), t]) # z = np.transpose(z.reshape(nx, ny, nbins), axes=[2, 1, 0]) # ipv.quickvolshow(z, # extent=[[x[0, 0]*100.0, x[0, -1]*100.0], # [y[0, 0]*100.0, y[-1, 0]*100.0], # [t[0], t[-1]]]) # ipv.pylab.xlabel("x [cm]") # ipv.pylab.ylabel("y [cm]") # ipv.pylab.zlabel("Tof [us]") # print(x) # print(y) # print(z) ipv.figure() x1, y1 = np.meshgrid([-1, 1], [-1, 1]) w1 = ipv.plot_wireframe(x1, y1, np.ones_like(x1) * (-1.0), color="black") w2 = ipv.plot_wireframe(x1, y1, np.ones_like(x1), color="black") surf = ipv.plot_surface(x, y, z, color=color[..., :3]) ipv.pylab.scatter([-1, -0.5], [-1, -0.5], [-1, -0.5], size=3, marker="sphere", color='r') ipv.show() return
def draw_hyperplane(self): tmp = np.linspace(0,5,30) # Genera 30 puntos entre -0 y 5 x,y = np.meshgrid(tmp,tmp) # Genera las coordenadas para dibujar X y Y del plano # apply_w_formula es la fórmula para determinar Z en base a los generados en la # anterior instrucción ipv.plot_surface(x, y, self.apply_w_formula(self.__clf,x, y), color="yellow")
def plot(self, **kwargs): """ plot the sphere :returns: :rtype: """ # u = np.linspace(0, 2 * np.pi, self._detail_level) # v = np.linspace(0, np.pi, self._detail_level) # x_unit = np.outer(np.cos(u), np.sin(v)) # y_unit = np.outer(np.sin(u), np.sin(v)) # z_unit = np.outer(np.ones(np.size(u)), np.cos(v)) u = np.linspace(0, 1, self._detail_level) v = np.linspace(0, 1, self._detail_level) u, v = np.meshgrid(u, v) phi = u * 2 * np.pi theta = v * np.pi x_unit = np.cos(phi) * np.sin(theta) y_unit = np.sin(theta) * np.sin(phi) z_unit = np.cos(theta) if self._transform_matrix is not None: xyz = np.array([x_unit, y_unit, z_unit]).T if self._time_dep_transform: # new_xyz = compute_multiple_rotation(xyz, self._transform_matrix, self._detail_level, self._n_steps) x_unit_rot = np.zeros( (self._n_steps, self._detail_level, self._detail_level)) y_unit_rot = np.zeros( (self._n_steps, self._detail_level, self._detail_level)) z_unit_rot = np.zeros( (self._n_steps, self._detail_level, self._detail_level)) for i in range(self._n_steps): this_xyz = compute_single_rotation( xyz, self._transform_matrix[i], self._detail_level) x_unit_rot[i] = this_xyz[0] y_unit_rot[i] = this_xyz[1] z_unit_rot[i] = this_xyz[2] else: xyz = compute_single_rotation(xyz, self._transform_matrix, self._detail_level) x_unit_rot = xyz[0] y_unit_rot = xyz[1] z_unit_rot = xyz[2] if np.atleast_1d(self._x).shape[0] == 1: if self._time_dep_transform: # if False: X = np.array([ self._x + self._radius * x_unit for _ in range(self._n_steps) ]) Y = np.array([ self._y + self._radius * y_unit for _ in range(self._n_steps) ]) Z = np.array([ self._z + self._radius * z_unit for _ in range(self._n_steps) ]) else: X = self._x + self._radius * x_unit Y = self._y + self._radius * y_unit Z = self._z + self._radius * z_unit else: X = np.array([x + self._radius * x_unit for x in self._x]) Y = np.array([y + self._radius * y_unit for y in self._y]) Z = np.array([z + self._radius * z_unit for z in self._z]) if self._image is None: return ipv.plot_surface(X, Y, Z, color=self._color, **kwargs) else: if self._transform_matrix is None: lon = np.arctan2(y_unit, x_unit) lat = np.arcsin(z_unit) else: lon = np.arctan2(y_unit_rot, x_unit_rot) lat = np.arcsin(z_unit_rot) u = 0.5 + lon / (2 * np.pi) v = 0.5 + lat / (np.pi) return ipv.plot_mesh(X, Y, Z, u=u, v=v, texture=self._image, wireframe=False)
def __init__(self, prn, data, signal_char, acq_char): # signal parameters self.fs = signal_char["fs"] self.fi = signal_char["fi"] # Generate the local code locBipolar = cacode(prn) # The code is bipolar format self.fc = 1.023e6 # Rate of the code Tc = 0.001 # Coherent integration time in ms self.Nc = int(Tc * self.fs) # Resample the code at the data sampling frequency self.locC = ac.ResampleCode(locBipolar, self.Nc, self.fs, 0, self.fc) # Output search space self.K = acq_char["K"] # Number of non-coherent integrations # Number of Doppler bins self.Nd = acq_char["Nd"] # Doppler step self.DopStep = acq_char["DopStep"] # Cross-Ambiguity Function (CAF) self.sspace = np.zeros( (self.Nd, self.Nc)) # Search space were the results will be stored # Store the input data self.data = data # Compute the CAF self.evaluate_caf(data) ############################### Graphic and interactive elements ############################# # Allocate an IPV figure self.figure = ipv.figure(width=800, height=500) self.codeDl = np.arange(0, self.Nc) / self.fs # Code delays self.Freq = (np.arange(0, self.Nd) - np.floor(self.Nd / 2)) * self.DopStep index = np.argmax(self.sspace) DopInd = int(index / self.sspace.shape[1]) codInd = np.mod(index, self.sspace.shape[1]) maxVal = self.sspace.max() # down-sampling factor (for the code) dsf = 40 # initial index in order not to miss the correlation peak pstart = codInd % dsf code_val, freq_val = np.meshgrid(self.codeDl[pstart::dsf], self.Freq) colormap = cm.coolwarm Z = self.sspace[:, pstart::dsf] / maxVal color = colormap(Z) self.caf = ipv.plot_surface(freq_val, Z, code_val * 1000, color=color[..., :3]) # ipv.ylabel("NCAF") # ipv.xlabel("Doppler [Hz]") # ipv.zlabel("Delay [ms]") ipv.show() # Add the widgets for interference mitigation Mitigation = ["None", "ANF08", "FDCS", "FDPB", "TDCS", "TDPB"] self.ui = widgets.interact( self.update, Th=widgets.FloatSlider(value=5, min=1, max=20.0, step=0.1, description='$T_h$', continuous_update=False), mtype=Mitigation, K=widgets.IntSlider(value=1, min=1, max=10, step=1, continuous_update=False))