def plot_isosurface(grid, V, dims_plot, s): if len(dims_plot) != 3: raise Exception('dims_plot length should be equal to 3\n') else: dim1, dim2, dim3 = dims_plot[0], dims_plot[1], dims_plot[2] complex_x = complex(0, grid.pts_each_dim[dim1]) complex_y = complex(0, grid.pts_each_dim[dim2]) complex_z = complex(0, grid.pts_each_dim[dim3]) mg_X, mg_Y, mg_Z = np.mgrid[grid.min[dim1]:grid.max[dim1]:complex_x, grid.min[dim2]:grid.max[dim2]:complex_y, grid.min[dim3]:grid.max[dim3]:complex_z] # graph value table while keeping speed constant V = V[:, :, s, :] print("Plotting beautiful plots. Please wait\n") fig = go.Figure( data=go.Isosurface(x=mg_X.flatten(), y=mg_Y.flatten(), z=mg_Z.flatten(), value=V.flatten(), colorscale='jet', isomin=0, surface_count=1, isomax=0, caps=dict(x_show=True, y_show=True))) fig.show() print("Please check the plot on your browser.")
def get_cubes_traces(cubes, spacing, origin, iso, colorscale, opacity): x, y, z = np.mgrid[:cubes[0].shape[0], :cubes[0].shape[1], :cubes[0]. shape[2]] x_r = x * spacing[0] + origin[0] y_r = y * spacing[1] + origin[1] z_r = z * spacing[2] + origin[2] traces = [] for i, cube in enumerate(cubes): value = cube.flatten() trace = go.Isosurface(x=x_r.flatten(), y=y_r.flatten(), z=z_r.flatten(), value=cube.flatten(), surface_count=2, colorscale=colorscale, visible=False, showscale=False, isomin=-1 * iso, isomax=1 * iso, flatshading=False, lighting=surface_materials["matte"], caps=dict(x_show=False, y_show=False, z_show=False), opacity=opacity) traces.append(trace) return traces
def get_volume(cube, spacing, origin, iso, opacity, color): x, y, z = np.mgrid[:cube.shape[0], :cube.shape[1], :cube.shape[2]] x_r = x * spacing[0] + origin[0] y_r = y * spacing[1] + origin[1] z_r = z * spacing[2] + origin[2] mesh = go.Isosurface(x = x_r.flatten(), y = y_r.flatten(), z = z_r.flatten(), value = molecule.cube.flatten(), surface_count = 2, colorscale = color, showscale=False, isomin=-1 * iso, isomax= 1 * iso, opacity = opacity) max_range_x = np.max(x_r) max_range_y = np.max(y_r) max_range_z = np.max(z_r) min_range_x = np.min(x_r) min_range_y = np.min(y_r) min_range_z = np.min(z_r) max_range = max(max_range_x, max_range_y, max_range_z) min_range = min(min_range_x, min_range_y, min_range_z) return mesh, min_range, max_range
def get_cube_trace(cube, spacing, origin, iso, colorscale, opacity, visible=True): x,y,z = np.mgrid[:cube.shape[0], :cube.shape[1], :cube.shape[2]] x_r = x * spacing[0] + origin[0] y_r = y * spacing[1] + origin[1] z_r = z * spacing[2] + origin[2] #value = cube.flatten() trace = go.Isosurface( x = x_r.flatten(), y = y_r.flatten(), z = z_r.flatten(), value = cube.flatten(), surface_count = 2, colorscale = colorscale, visible = visible, showscale = False, isomin= -1 * iso, isomax= 1 * iso, flatshading = False, lighting = surface_materials["matte"], caps=dict(x_show=False, y_show=False, z_show=False), opacity=opacity) max_range_x = np.max(x_r) max_range_y = np.max(y_r) max_range_z = np.max(z_r) min_range_x = np.min(x_r) min_range_y = np.min(y_r) min_range_z = np.min(z_r) max_range = max(max_range_x, max_range_y, max_range_z) min_range = min(min_range_x, min_range_y, min_range_z) return trace, min_range, max_range
def render_pointillist_with_nodes( xs_pt: List[float], ys_pt: List[float], zs_pt: List[float], vals_pt: List[float], xs_iso: List[float], ys_iso: List[float], zs_iso: List[float], vals_iso: List[float], ) -> None: fig = go.Figure() # type: ignore fig.add_trace( go.Isosurface( # type: ignore x=xs_iso, y=ys_iso, z=zs_iso, # This alleviates numerical instability by amplifying any deviations from zero. # However, this does result in crinkly surfaces. value=tuple(map(lambda v: copysign(sqrt(abs(v)), v), vals_iso)), caps=dict(x_show=False, y_show=False, z_show=False), flatshading=False, opacity=0.075, isomin=0, isomax=0, surface_count=1, colorscale="greens", colorbar=dict(showticklabels=False), )) fig = render_pointillist_into_fig(fig, xs_pt, ys_pt, zs_pt, vals_pt) fig.show() # type: ignore
def plot_isosurface(grid, V, dims_plot): if len(dims_plot) != 3: raise Exception('dims_plot length should be equal to 3\n') else: dim1, dim2, dim3 = dims_plot[0], dims_plot[1], dims_plot[2] complex_x = complex(0, grid.pts_each_dim[dim1]) complex_y = complex(0, grid.pts_each_dim[dim2]) complex_z = complex(0, grid.pts_each_dim[dim3]) mg_X, mg_Y, mg_Z = np.mgrid[grid.min[dim1]:grid.max[dim1]: complex_x, grid.min[dim2]:grid.max[dim2]: complex_y, grid.min[dim3]:grid.max[dim3]: complex_z] # Hardcode this number for now # V = V[:, :, 49, :] # DubinsCar4D # V = V[:, :, :, 0, 0] # RelDyn5D V = V[:, :, :, 34, 0] # RelDyn5D # V = V[:, :, :, 34, 17] # RelDyn5D # V = V[:, :, :, 34, 34] # RelDyn5D print("Plotting beautiful plots. Please wait\n") fig = go.Figure(data=go.Isosurface( x=mg_X.flatten(), y=mg_Y.flatten(), z=mg_Z.flatten(), value=V.flatten(), colorscale='jet', isomin=0, surface_count=1, isomax=0, caps=dict(x_show=True, y_show=True) )) fig.update_layout( title="t = 2.0s, v_human = 17m/s, v_robot = 17m/s, a_human in [-5, 3], w_human in [-pi/6, pi/6]" # legend_title="Legend Title", # font=dict( # family="Courier New, monospace", # size=18, # color="RebeccaPurple" # ) ) fig.show() # fig.write_image("/Users/anjianli/Desktop/robotics/project/prediction-reachability/reachable-set/t5_vh_8.5_vr_8.5_ah_-5_-2_wh_-0.1_0.1.png") print("Please check the plot on your browser.")
def plot_3d_iso(X, Y, Z, values, c, eps): fig = go.Figure(data=go.Isosurface( x=X.flatten(), y=Y.flatten(), z=Z.flatten(), lighting=dict(roughness=0.3, specular=.9, diffuse=1, ambient=0.1), lightposition=dict(x=45, y=15, z=25), value=values.flatten(), isomin=c, isomax=c + eps, colorscale='Jet', opacity=1., caps=dict(x_show=True, y_show=True, z_show=True))) fig.update_layout( scene=dict( xaxis=dict( backgroundcolor="rgba(0, 0,0,0.1)", gridcolor="white", showbackground=True, zerolinecolor="white", ), yaxis=dict(backgroundcolor="rgba(0, 0,0,0.1)", gridcolor="white", showbackground=True, zerolinecolor="white"), zaxis=dict( backgroundcolor="rgba(0, 0,0,0.2)", gridcolor="white", showbackground=True, zerolinecolor="white", ), ), width=700, margin=dict(r=10, l=10, b=10, t=10), ) fig['layout'].update(scene=dict(camera=dict(up=dict(x=0, y=0, z=1), center=dict(x=0, y=0, z=0), eye=dict(x=1.5, y=2, z=0.6)))) fig.show()
def plot_isosurface(grid, V, plot_option): # pdb.set_trace() dims_plot = plot_option.dims_plot idx = [slice(None)] * grid.dims slice_idx = 0 dims_list = list(range(0, grid.dims)) for i in dims_list: if i not in dims_plot: idx[i] = plot_option.slices[slice_idx] slice_idx += 1 if len(dims_plot) != 3: raise Exception('dims_plot length should be equal to 3\n') else: dim1, dim2, dim3 = dims_plot[0], dims_plot[1], dims_plot[2] complex_x = complex(0, grid.pts_each_dim[dim1]) complex_y = complex(0, grid.pts_each_dim[dim2]) complex_z = complex(0, grid.pts_each_dim[dim3]) mg_X, mg_Y, mg_Z = np.mgrid[grid.min[dim1]:grid.max[dim1]:complex_x, grid.min[dim2]:grid.max[dim2]:complex_y, grid.min[dim3]:grid.max[dim3]:complex_z] # graph value table while keeping speed constant # if V.ndim == 4: # V = V[:, :, s, :] my_V = V[tuple(idx)] print("Plotting beautiful plots. Please wait\n") fig = go.Figure( data=go.Isosurface(x=mg_X.flatten(), y=mg_Y.flatten(), z=mg_Z.flatten(), value=my_V.flatten(), colorscale='jet', isomin=0, surface_count=1, isomax=0, caps=dict(x_show=True, y_show=True))) fig.show() print("Please check the plot on your browser.")
def plot_isosurface(grid, V, plot_option): dims_plot = plot_option.dims_plot idx = [slice(None)] * grid.dims slice_idx = 0 dims_list = list(range(grid.dims)) for i in dims_list: if i not in dims_plot: idx[i] = plot_option.slices[slice_idx] slice_idx += 1 if len(dims_plot) != 3: raise Exception('dims_plot length should be equal to 3\n') else: dim1, dim2, dim3 = dims_plot[0], dims_plot[1], dims_plot[2] complex_x = complex(0, grid.pts_each_dim[dim1]) complex_y = complex(0, grid.pts_each_dim[dim2]) complex_z = complex(0, grid.pts_each_dim[dim3]) mg_X, mg_Y, mg_Z = np.mgrid[grid.min[dim1]:grid.max[dim1]:complex_x, grid.min[dim2]:grid.max[dim2]:complex_y, grid.min[dim3]:grid.max[dim3]:complex_z] my_V = V[tuple(idx)] if (V > 0.0).all() or (V < 0.0).all(): print( "Implicit surface will not be shown since all values have the same sign " ) print("Plotting beautiful plots. Please wait\n") fig = go.Figure( data=go.Isosurface(x=mg_X.flatten(), y=mg_Y.flatten(), z=mg_Z.flatten(), value=my_V.flatten(), colorscale='jet', isomin=plot_option.min_isosurface, surface_count=1, isomax=plot_option.max_isosurface, caps=dict(x_show=True, y_show=True))) fig.show() print("Please check the plot on your browser.")
def plot_iso_surface_plotly(x_min, x_max, func): n_points = 100 grid1D = torch.linspace(x_min, x_max, n_points) grid_x, grid_y, grid_z = torch.meshgrid(grid1D, grid1D, grid1D) grid = torch.cat( [grid_x.reshape(-1, 1), grid_y.reshape(-1, 1), grid_z.reshape(-1, 1)], dim=1) data = func(grid).reshape(n_points, n_points, n_points).detach() max_val = float(torch.max(data).numpy()) print(max_val) fig = go.Figure(data=go.Isosurface(x=grid_x.flatten(), y=grid_y.flatten(), z=grid_z.flatten(), value=data.flatten(), isomax=max_val / 2, caps={ "x_show": False, "y_show": False, "z_show": False })) fig.show()
# Dropping the quad like a falling leaf. state = [8., -1., np.pi / 2, 2.] fig, ani = animate_optimal_trajectory(np.array([0, 0] + state)) ani.save("planar_quad_3.mp4", writer="ffmpeg") plt.show() # Too much negative vertical velocity to recover before hitting the floor. state = [8., -3., np.pi / 2, 2.] fig, ani = animate_optimal_trajectory(np.array([0, 0] + state)) ani.save("planar_quad_4.mp4", writer="ffmpeg") plt.show() # Examining an isosurface (exercise part (d)). import plotly.graph_objects as go i_y = 18 fig = go.Figure( data=go.Isosurface(x=grid.states[i_y, ..., 1].ravel(), y=grid.states[i_y, ..., 2].ravel(), z=grid.states[i_y, ..., 3].ravel(), value=values[i_y].ravel(), colorscale="jet", isomin=0, surface_count=1, isomax=0), layout_title=f"Zero isosurface, y = {grid.coordinate_vectors[0][i_y]:7.4f}", layout_scene_xaxis_title="v_y", layout_scene_yaxis_title="phi", layout_scene_zaxis_title="omega") fig.show()
sizemode="absolute", sizeref=40)) fig.update_layout(scene=dict(aspectratio=dict(x=1, y=1, z=0.8), camera_eye=dict(x=1.2, y=1.2, z=0.6))) fig.show() # In[2]: import plotly.graph_objects as go fig = go.Figure(data=go.Isosurface( x=[0, 0, 0, 0, 1, 1, 1, 1], y=[1, 0, 1, 0, 1, 0, 1, 0], z=[1, 1, 0, 0, 1, 1, 0, 0], value=[1, 2, 3, 4, 5, 6, 7, 8], isomin=2, isomax=6, )) fig.show() # In[ ]: import plotly.graph_objects as go import numpy as np X, Y, Z = np.mgrid[-5:5:40j, -5:5:40j, -5:5:40j] # ellipsoid values = X * X * 0.5 + Y * Y + Z * Z * 2
def plotly_isosurfaces(d1, d2, d3, E, fname=None, \ cmap='viridis', xlabel="Drug 1", ylabel="Drug 2", \ zlabel="Drug 3", \ vmin=None, vmax=None, auto_open=False, opacity=0.6, \ logscale=True, isomin=None, isomax=None, \ center_on_zero=False, surface_count=10, \ figsize=(1000,800), fontsize=18, title=None): d1 = np.asarray(d1) d2 = np.asarray(d2) d3 = np.asarray(d3) if (len(d1.shape) > 1): d1 = d1.flatten() d2 = d2.flatten() d3 = d3.flatten() E = E.flatten() sorted_indices = np.lexsort((d1, d2, d3)) d1 = d1[sorted_indices] d2 = d2[sorted_indices] d3 = d3[sorted_indices] E = E[sorted_indices] if logscale: d1 = utils.remove_zeros(d1) d2 = utils.remove_zeros(d2) d3 = utils.remove_zeros(d3) d1 = np.log10(d1) d2 = np.log10(d2) d3 = np.log10(d3) E_range = np.nanmax(E[~np.isinf(E)]) - np.nanmin(E[~np.isinf(E)]) if isomin is None: isomin = np.nanmin(E[~np.isinf(E)]) + 0.1 * E_range if isomax is None: isomax = np.nanmin(E[~np.isinf(E)]) + 0.9 * E_range if center_on_zero: if vmin is None or vmax is None: zmax = max(abs(np.nanmin(E[~np.isinf(E)])), abs(np.nanmax(E[~np.isinf(E)]))) vmin = -zmax vmax = zmax else: zmax = max(abs(vmin), abs(vmax)) vmin = -zmax vmax = zmax fig = go.Figure(data=go.Isosurface( x=d1, y=d2, z=d3, value=E, isomin=isomin, isomax=isomax, cmin=vmin, cmax=vmax, opacity=0.6, colorscale=cmap, surface_count= surface_count, # number of isosurfaces, 2 by default: only min and max colorbar_nticks= surface_count, # colorbar ticks correspond to isosurface values caps=dict(x_show=False, y_show=False, z_show=True))) if title is None: if fname is not None: title = fname else: title = "" fig.update_layout(title=title, autosize=False, scene_camera_eye=dict(x=1.87, y=0.88, z=0.64), width=figsize[0], height=figsize[1], margin=dict(l=100, r=100, b=90, t=90), scene=dict(xaxis_title=xlabel, yaxis_title=ylabel, zaxis_title=zlabel, aspectmode="cube"), font=dict(size=fontsize)) if fname is not None: offline.plot(fig, filename=fname, auto_open=auto_open) else: fig.show()
# Grids X, Y, Z = np.meshgrid(x, y, z) #KSX, KSY, KSZ = np.meshgrid(ks, ks, ks) KX, KY, KZ = np.meshgrid(k, k, k) ### Look at unfiltered data sd = np.reshape(subdata[:, 0], (n, n, n)) M = np.amax(np.abs(sd)) vol = np.abs(sd) / M ### Isosurface plot at 50% fig = go.Figure(data=go.Isosurface( x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=vol.flatten(), isomin=0.5, isomax=1, )) fig.show() ### Average spectrum and determine center frequency # Form seven step averages avg_spec = np.zeros((n, n, n, 7)) + 0j for i in range(7): for j in range(7): Unt = np.fft.fftn(np.reshape(subdata[:, 7 * i + j], (n, n, n))) avg_spec[:, :, :, i] += Unt / 7 # Center frequency = mean of where spectral density exceeds threshold (60% max)
def main(): ################### PARSING ARGUMENTS FROM USERS ##################### parser = ArgumentParser() parser.add_argument("-p", "--plot", default=False, type=bool) args = parser.parse_args() hcl.init() hcl.config.init_dtype = hcl.Float() ################## DATA SHAPE PREPARATION FOR GRAPH FORMATION #################### V_f = hcl.placeholder(tuple(g.pts_each_dim), name="V_f", dtype=hcl.Float()) V_init = hcl.placeholder(tuple(g.pts_each_dim), name="V_init", dtype=hcl.Float()) x = hcl.placeholder((4, g.pts_each_dim[0]), name="x", dtype=hcl.Float()) t = hcl.placeholder((1, ), name="t", dtype=hcl.Float()) # Deriv diff tensor deriv_diff1 = hcl.Tensor((tuple(g.pts_each_dim)), name="deriv_diff1") deriv_diff2 = hcl.Tensor((tuple(g.pts_each_dim)), name="deriv_diff2") deriv_diff3 = hcl.Tensor((tuple(g.pts_each_dim)), name="deriv_diff3") deriv_diff4 = hcl.Tensor((tuple(g.pts_each_dim)), name="deriv_diff4") ################# INITIALIZE DATA TO BE INPUT INTO GRAPH ########################## V_0 = hcl.asarray(my_shape) V_1 = hcl.asarray(np.zeros(tuple(g.pts_each_dim))) t_minh = hcl.asarray(np.zeros(1)) x = np.zeros(4, g.pts_each_dim[0]) for i in range(0, 4): for j in range(0, g.pts_each_dim[i]): x[i, j] = g.xs[i][j] # Convert x to hcl array type x = hcl.asarray(x) ##################### CREATE SCHEDULE############## # Create schedule s = hcl.create_schedule([V_f, V_init, x, t], graph_4D) # Inspect the LLVM code print(hcl.lower(s)) ##################### CODE OPTIMIZATION HERE ########################### # Accessing the hamiltonian stage s_H = graph_4D.Hamiltonian # ################ GET EXECUTABLE AND USE THE EXECUTABLE ############ # Get executable solve_pde = hcl.build(s) # Variables used for timing execution_time = 0 lookback_time = 0 while lookback_time <= lookback_length: # Start timing start = time.time() # Printing some info #print("Look back time is (s): {:.5f}".format(lookback_time)) # Run the execution and pass input into graph solve_pde(V_1, V_0, list_theta, t_minh) if lookback_time != 0: # Exclude first time of the computation execution_time += time.time() - start lookback_time += np.asscalar(t_minh.asnumpy()) # Some information printing #print(t_minh) print( "Computational time to integrate (s): {:.5f}".format(time.time() - start)) V_1 = V_1.asnumpy() V_1 = np.swapaxes(V_1, 0, 2) #V = np.swapaxes(V, 1,2) #probe = probe.asnumpy() #probe = np.swapaxes(probe, 0, 2) #probe = np.swapaxes(probe, 1, 2) #print(V) #V_1 = V_1.asnumpy() # Time info printing print("Total kernel time (s): {:.5f}".format(execution_time)) print("Finished solving\n") ##################### PLOTTING ##################### if args.plot: print("Plotting beautiful plots. Please wait\n") fig = go.Figure( data=go.Isosurface(x=g.mg_X.flatten(), y=g.mg_Y.flatten(), z=g.mg_T.flatten(), value=V_1.flatten(), colorscale='jet', isomin=0, surface_count=1, isomax=0, caps=dict(x_show=True, y_show=True))) fig.show() print("Please check the plot on your browser.")
def main(): hcl.init() hcl.config.init_dtype = hcl.Float() V_f = hcl.placeholder(tuple(g.pts_each_dim), name="V_f", dtype=hcl.Float()) V_init = hcl.placeholder(tuple(g.pts_each_dim), name="V_init", dtype=hcl.Float()) thetas = hcl.placeholder((g.pts_each_dim[2], ), name="thetas", dtype=hcl.Float()) t = hcl.placeholder((1, ), name="t", dtype=hcl.Float()) # Create schedule s = hcl.create_schedule([V_f, V_init, thetas, t], HJ_PDE_solver) # Here comes the optimization # Accessing the hamiltonian stage s_H = HJ_PDE_solver.Hamiltonian # Split the loops k_out, k_in = s[s_H].split(s_H.k, 10) # These numbers are experimental, changable j_out, j_in = s[s_H].split(s_H.j, 10) i_out, i_in = s[s_H].split(s_H.i, 10) # Reorder the loops s[s_H].reorder(j_out, k_in) s[s_H].reorder(i_out, k_in) s[s_H].reorder(k_in, j_in) # FPGA Back end - parallel specs s[s_H].pipeline(k_in) s[s_H].unroll(i_out, 5) # If CPU option s[s_H].parallel(k_out) # Inspect IR #print(hcl.lower(s)) # Build the code solve_pde = hcl.build(s) #print(f) # Prepare numpy array for graph computation V_0 = hcl.asarray(shape) V_1 = hcl.asarray(np.zeros(tuple(g.pts_each_dim))) t_minh = hcl.asarray(np.zeros(1)) # List thetas list_theta = np.reshape(g.vs[2], g.pts_each_dim[2]) list_theta = hcl.asarray(list_theta) # Variables used for timing execution_time = 0 lookback_time = 0 print("I'm here\n") # Test the executable from heteroCL: while lookback_time <= lookback_length: # Start timing start = time.time() # Printing some info #print("Look back time is (s): {:.5f}".format(lookback_time)) # Run the execution and pass input into graph solve_pde(V_1, V_0, list_theta, t_minh) if lookback_time != 0: # Exclude first time of the computation execution_time += time.time() - start lookback_time += np.asscalar(t_minh.asnumpy()) # Some information printing #print(t_minh) print( "Computational time to integrate (s): {:.5f}".format(time.time() - start)) #V = V_1.asnumpy() #V = np.swapaxes(V, 0,2) #V = np.swapaxes(V, 1,2) #probe = probe.asnumpy() #probe = np.swapaxes(probe, 0, 2) #probe = np.swapaxes(probe, 1, 2) #print(V) #V_1 = V_1.asnumpy() # Time info printing print("Total kernel time (s): {:.5f}".format(execution_time)) print("Finished solving\n") # Plotting print("Plotting beautiful plots. Please wait\n") fig = go.Figure(data=go.Isosurface(x=g.mg_X.flatten(), y=g.mg_Y.flatten(), z=g.mg_T.flatten(), value=V_1.asnumpy().flatten(), colorscale='jet', isomin=0, surface_count=1, isomax=0, caps=dict(x_show=True, y_show=True))) fig.show() print("Please check the plot on your browser.")
def main(): ################### PARSING ARGUMENTS FROM USERS ##################### parser = ArgumentParser() parser.add_argument("-p", "--plot", default=False, type=bool) # Print out LLVM option only parser.add_argument("-l", "--llvm", default=False, type=bool) args = parser.parse_args() hcl.init() hcl.config.init_dtype = hcl.Float() ################## DATA SHAPE PREPARATION FOR GRAPH FORMATION #################### V_f = hcl.placeholder(tuple(g.pts_each_dim), name="V_f", dtype=hcl.Float()) V_init = hcl.placeholder(tuple(g.pts_each_dim), name="V_init", dtype=hcl.Float()) l0 = hcl.placeholder(tuple(g.pts_each_dim), name="l0", dtype=hcl.Float()) #x = hcl.placeholder((6, g.pts_each_dim[0]), name="x", dtype=hcl.Float()) t = hcl.placeholder((2, ), name="t", dtype=hcl.Float()) # Deriv diff tensor deriv_diff1 = hcl.placeholder((tuple(g.pts_each_dim)), name="deriv_diff1") deriv_diff2 = hcl.placeholder((tuple(g.pts_each_dim)), name="deriv_diff2") deriv_diff3 = hcl.placeholder((tuple(g.pts_each_dim)), name="deriv_diff3") deriv_diff4 = hcl.placeholder((tuple(g.pts_each_dim)), name="deriv_diff4") deriv_diff5 = hcl.placeholder((tuple(g.pts_each_dim)), name="deriv_diff5") deriv_diff6 = hcl.placeholder((tuple(g.pts_each_dim)), name="deriv_diff6") # Positions vector x1 = hcl.placeholder((g.pts_each_dim[0], ), name="x1", dtype=hcl.Float()) x2 = hcl.placeholder((g.pts_each_dim[1], ), name="x2", dtype=hcl.Float()) x3 = hcl.placeholder((g.pts_each_dim[2], ), name="x3", dtype=hcl.Float()) x4 = hcl.placeholder((g.pts_each_dim[3], ), name="x4", dtype=hcl.Float()) x5 = hcl.placeholder((g.pts_each_dim[4], ), name="x5", dtype=hcl.Float()) x6 = hcl.placeholder((g.pts_each_dim[5], ), name="x6", dtype=hcl.Float()) # Obstacle placeholder obstacle = hcl.placeholder((tuple(g.pts_each_dim)), name="obstacle") ##################### CREATE SCHEDULE############## # Create schedule s = hcl.create_schedule([ V_f, V_init, deriv_diff1, deriv_diff2, deriv_diff3, deriv_diff4, deriv_diff5, deriv_diff6, x1, x2, x3, x4, x5, x6, t, l0, obstacle ], graph_6D) # Inspect the LLVM code print(hcl.lower(s)) ################# INITIALIZE DATA TO BE INPUT INTO GRAPH ########################## print("Initializing\n") V_0 = hcl.asarray(my_shape) V_1 = hcl.asarray(np.zeros(tuple(g.pts_each_dim))) l0 = hcl.asarray(my_shape) obstacle = hcl.asarray(cstraint_values) list_x1 = np.reshape(g.vs[0], g.pts_each_dim[0]) list_x2 = np.reshape(g.vs[1], g.pts_each_dim[1]) list_x3 = np.reshape(g.vs[2], g.pts_each_dim[2]) list_x4 = np.reshape(g.vs[3], g.pts_each_dim[3]) list_x5 = np.reshape(g.vs[4], g.pts_each_dim[4]) list_x6 = np.reshape(g.vs[5], g.pts_each_dim[5]) # Convert to hcl array type list_x1 = hcl.asarray(list_x1) list_x2 = hcl.asarray(list_x2) list_x3 = hcl.asarray(list_x3) list_x4 = hcl.asarray(list_x4) list_x5 = hcl.asarray(list_x5) list_x6 = hcl.asarray(list_x6) # Initialize deriv diff tensor deriv_diff1 = hcl.asarray(np.zeros(tuple(g.pts_each_dim))) deriv_diff2 = hcl.asarray(np.zeros(tuple(g.pts_each_dim))) deriv_diff3 = hcl.asarray(np.zeros(tuple(g.pts_each_dim))) deriv_diff4 = hcl.asarray(np.zeros(tuple(g.pts_each_dim))) deriv_diff5 = hcl.asarray(np.zeros(tuple(g.pts_each_dim))) deriv_diff6 = hcl.asarray(np.zeros(tuple(g.pts_each_dim))) ##################### CODE OPTIMIZATION HERE ########################### print("Optimizing\n") # Accessing the hamiltonian stage s_H = graph_6D.Hamiltonian s_D = graph_6D.Dissipation # s[s_H].parallel(s_H.i) s[s_D].parallel(s_D.i) # Inspect IR #if args.llvm: # print(hcl.lower(s)) ################ GET EXECUTABLE AND USE THE EXECUTABLE ############ print("Running\n") # Get executable solve_pde = hcl.build(s) # Variables used for timing execution_time = 0 lookback_time = 0 tNow = tau[0] for i in range(1, len(tau)): #tNow = tau[i-1] t_minh = hcl.asarray(np.array((tNow, tau[i]))) while tNow <= tau[i] - 1e-4: # Start timing start = time.time() # Run the execution and pass input into graph solve_pde(V_1, V_0, deriv_diff1, deriv_diff2, deriv_diff3, deriv_diff4, deriv_diff5, deriv_diff6, list_x1, list_x2, list_x3, list_x4, list_x5, list_x6, t_minh, l0, obstacle) tNow = np.asscalar((t_minh.asnumpy())[0]) if lookback_time != 0: # Exclude first time of the computation execution_time += time.time() - start # Some information printing print(t_minh) print("Computational time to integrate (s): {:.5f}".format( time.time() - start)) # Saving data into disk if tNow >= tau[i] - 1e-4: print("Saving files\n") sio.savemat( '/local-scratch/Humannoid/humannoid_v_{:d}.mat'.format(i), {'V_array': V_1.asnumpy()}) #print(V_1.asnumpy()) # # V_1 = V_1.asnumpy() # # V_1 = np.swapaxes(V_1, 0,2) # #V = np.swapaxes(V, 1,2) # #probe = probe.asnumpy() # #probe = np.swapaxes(probe, 0, 2) # #probe = np.swapaxes(probe, 1, 2) # #print(V) # #V_1 = V_1.asnumpy() # # # Time info printing print("Total kernel time (s): {:.5f}".format(execution_time)) print("Finished solving\n") ##################### PLOTTING ##################### if args.plot: print("Plotting beautiful plots. Please wait\n") fig = go.Figure( data=go.Isosurface(x=g.mg_X.flatten(), y=g.mg_Y.flatten(), z=g.mg_T.flatten(), value=V_1.flatten(), colorscale='jet', isomin=0, surface_count=1, isomax=0, caps=dict(x_show=True, y_show=True))) fig.show() print("Please check the plot on your browser.")
if __name__ == "__main__": print("Generating Mesh") XYZList, XList, YList, ZList = MeshGen() print(len(XList)) print("reading values") MeshValues = MeshFileReader("MeshInterpolatedValues5") print(len(MeshValues)) print("making figure") fig2 = go.Isosurface( x=XList, y=YList, z=ZList, value=MeshValues, opacity=0.15, colorscale='solar', isomin=25, isomax=25, surface_count=5, # number of isosurfaces, 2 by default: only min and max colorbar_nticks=5, # colorbar ticks correspond to isosurface values ) Xg, Yg, Zg = np.mgrid[-6400:6400:100j, -6400:6400:100j, -6400:6400:100j] values = Xg * Xg + Yg * Yg + Zg * Zg fig1 = go.Isosurface( x=Xg.flatten(), y=Yg.flatten(), z=Zg.flatten(), value=values.flatten(), colorscale=[[0, 'rgb(0,0,0)'], [1, 'rgb(0,0,0)']], showscale=False,
def plot(self, cube_file, iso=0.03, cube_type="density", colorscale="Blues", size=1, plot_geometry=True, plot_bonds=True): atoms_colors = blobs.get_colors() cube, meta = cube_to_array(cube_file) self.meta = meta X, Y, Z = np.mgrid[:cube.shape[0], :cube.shape[1], :cube.shape[2]] data = [] vol_data = go.Isosurface(x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=cube.flatten(), showscale=False, surface_count=2, isomax=iso, isomin=iso, opacity=0.2, colorscale=colorscale) data.append(vol_data) if cube_type == "orbital": vol_data_neg = go.Isosurface(x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=cube.flatten(), showscale=False, isomin=-1 * iso, isomax=-1 * iso, opacity=0.2, colorscale="Reds") data.append(vol_data_neg) if plot_geometry == True: geo_data = go.Scatter3d(x=self.info["x"], y=self.info["y"], z=self.info["z"], mode="markers", marker={ "showscale": False, "color": self.info["color"], "size": self.info["size"] * size / 1.0, "showscale": False, "opacity": 1.0, "line": { "width": 10, "color": "black" } }) data.append(geo_data) fig = go.Figure(data=data) if plot_bonds == True: bonds = build_bond_list(self.geometry.geometry().np) for i in range(len(bonds)): midx = (self.info["x"][bonds[i][0]] + self.info["x"][bonds[i][1]]) / 2 midy = (self.info["y"][bonds[i][0]] + self.info["y"][bonds[i][1]]) / 2 midz = (self.info["z"][bonds[i][0]] + self.info["z"][bonds[i][1]]) / 2 bond_color_1= atoms_colors[self.info["sym"][bonds[i][0]]][0] bond_color_2= atoms_colors[self.info["sym"][bonds[i][1]]][0] bond_x_1 = [self.info["x"][bonds[i][0]], midx] bond_y_1 = [self.info["y"][bonds[i][0]], midy] bond_z_1 = [self.info["z"][bonds[i][0]], midz] bond_x_2 = [self.info["x"][bonds[i][1]], midx] bond_y_2 = [self.info["y"][bonds[i][1]], midy] bond_z_2 = [self.info["z"][bonds[i][1]], midz] fig.add_trace( go.Scatter3d( x=bond_x_1, y=bond_y_1, z=bond_z_1, mode="lines", line={ "color": bond_color_1, "width": 7 * size }, )) fig.add_trace( go.Scatter3d( x=bond_x_2, y=bond_y_2, z=bond_z_2, mode="lines", line={ "color": bond_color_2, "width": 7 * size }, )) layout = go.layout.Template(layout=go.Layout(title_font=dict(family="Rockwell", size=24))) fig.update_layout(scene_xaxis_showticklabels=False, scene_yaxis_showticklabels=False, scene_zaxis_showticklabels=False, dragmode="orbit", width=size * 500, height=size * 500, template="plotly_white", autosize=True, showlegend=False, hovermode=False, xaxis=dict(autorange=True, showgrid=False, ticks='', showticklabels=False), yaxis=dict(autorange=True, showgrid=False, ticks='', showticklabels=False), scene={ "xaxis": { "autorange": True, "showgrid": False, "zeroline": False, "showline": False, "title": "", "ticks": '', "showticklabels": False, "showbackground": False, "showspikes" : False }, "yaxis": { "autorange": True, "showgrid": False, "zeroline": False, "showline": False, "title": "", "ticks": '', "showticklabels": False, "showbackground": False, "showspikes": False }, "zaxis": { "autorange": True, "showgrid": False, "zeroline": False, "showline": False, "title": "", "ticks": '', "showbackground": False, "showticklabels": False, "showspikes": False } }) fig.show(config={'scrollZoom': False})
import plotly.graph_objects as go import numpy as np X, Y, Z = np.mgrid[-5:5:40j, -5:5:40j, -5:5:40j] # ellipsoid values = X * X * 0.5 + Y * Y + Z * Z * 2 fig = go.Figure(data=go.Isosurface(x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=values.flatten(), isomin=10, isomax=40, caps=dict(x_show=False, y_show=False))) fig.show()
}, valueformat=".0f", )) fig.show() # 3D Isosurface plots https://plotly.com/python/3d-isosurface-plots/ X, Y, Z = np.mgrid[-5:5:40j, -5:5:40j, -5:5:40j] # ellipsoid values = X * X * 0.5 + Y * Y + Z * Z * 2 fig = go.Figure(data=go.Isosurface(x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=values.flatten(), colorscale='BlueRed', isomin=10, isomax=50, surface_count=3, caps=dict(x_show=False, y_show=False))) fig.show() # Notice how surface_count = 3 gets translated to surface = {'count': 3} # This is called "Magic Underscore Notation" and is a "plotly specific" feature # Happens almost every time there is an underscore in parameter name print(f"Observe 'surface_count=3'\n{fig=}") # Challenge 7: Find another example of "Magic Underscore Notation" we have used # Solution 7: Look at Solution 2 # marker_line_width=1 is equivalent to marker={"line": {"width": 1}}
def plot3d_Volume(): import chart_studio.plotly as py import plotly.graph_objects as go import plotly.tools as tls import plotly.express as px X, Y, Z = np.mgrid[-5:5:40j, -5:5:40j, -5:5:40j] # ellipsoid values = X * X * 0.75 + Y * Y + Z * Z * 3 values /= np.max(values) fig = go.Figure(data=go.Isosurface(x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=values.flatten(), isomin=.05, showscale=False, colorscale='blues', isomax=.2, surface_count=1, caps=dict(x_show=False, y_show=False))) X2, Y2, Z2 = np.mgrid[-5:5:40j, -5:5:40j, -5:5:40j] values2 = X2 * X2 * 0.75 + Y2 * Y2 + Z2 * Z2 * 3 values2 /= np.max(values2) fig.add_trace( go.Isosurface(x=X2.flatten() - 3, y=Y2.flatten() - 9, z=Z2.flatten(), value=values2.flatten(), isomin=.05, colorscale='reds', showscale=False, isomax=.15, surface_count=1, caps=dict(x_show=False, y_show=False))) fig.add_trace(go.Scatter3d(x=[0], y=[20], z=[0], mode='markers')) x = np.linspace(-2, 10, 100) y = np.linspace(-9, 0, 100) z = np.zeros(len(y)) fig.add_trace( go.Scatter3d(x=x, y=y, z=z, mode='lines', line=dict(color='white'))) x = np.linspace(-2, -12, 100) fig.add_trace( go.Scatter3d(x=x, y=y, z=z, mode='lines', line=dict(color='white'))) x = np.linspace(10, 0, 100) y = np.linspace(0, 20, 100) z = np.zeros(len(y)) fig.add_trace( go.Scatter3d(x=x, y=y, z=z, mode='lines', line=dict(color='white'))) x = np.linspace(-12, 0, 100) fig.add_trace( go.Scatter3d(x=x, y=y, z=z, mode='lines', line=dict(color='white'))) layout = dict( width=800, height=700, autosize=False, title='SN Requiem', #plot_bgcolor='#000000', scene=dict( xaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(0, 0, 0)', #title='Age (Observer Days)', #titlefont=dict(size=18,color='rgb(255,255,255)'), #autorange='reversed' ), yaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(0, 0, 0)', #title='F105W-F160W Color', #titlefont=dict(size=18,color='rgb(255,255,255)'), autorange='reversed'), zaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(0, 0, 0)', #title='F160W AB Magnitude', #titlefont=dict(size=18,color='rgb(255,255,255)'), autorange='reversed'), camera=dict( up=dict(x=0, y=0, z=1), #eye=dict( # x=-1.7428, # y=1.0707, # z=0.7100, #) ), aspectratio=dict(x=1, y=1, z=0.7), aspectmode='manual'), ) fig['layout'] = layout return (fig)