def getAllTrajectories(): ''' Get all the 3D trajectories from the feature tracking of all specimens ''' src = "/Volumes/USB/" src = '/Volumes/USB/ANHIR/TargetTesting/' size = 2.5 specs = sorted(glob(src + "C*")) for s in specs: specName = s.split("/")[-1] print("\n---- " + specName + " ----") # get the raw features rawfeatsrc = s + "/" + str(size) + "/FeatureSections/rawSelectedFixFeatures.csv" smfeatsrc = s + "/" + str(size) + "/FeatureSections/smoothSelectedFixFeatures.csv" try: rawfeats = pd.read_csv(rawfeatsrc) smfeats = pd.read_csv(smfeatsrc) px.line_3d(rawfeats, "X", "Y", "Z", "ID", title=specName + " raw").show() px.line_3d(smfeats, "X", "Y", "Z", "ID", title=specName + " smooth").show() except: print(" " + specName + " failed")
def build_graph(column_chosen): #global fig, fig2, fig3 if column_chosen == 'World wide suicide': fig = px.bar(sr, title="Worldwide suicide by year") fig2 = px.pie(sr_gender, values='total_suicide', names='sex', title="World wide suicide by Gender ") fig3 = px.bar(sr_age, title="World wide suicide by age", color_discrete_sequence=['green']*3) return fig, fig2, fig3 elif column_chosen == "Country wise suicide": fig = px.bar(cr_total, title="Top 10 Countries with the highest suicide rates", orientation='h') fig2 = px.choropleth(cr_map, locations="country", locationmode='country names', color="total_suicide", # lifeExp is a column of gapminder hover_name="country", # column to add to hover information color_continuous_scale=px.colors.sequential.Plasma, title="Map with total suicides in Different Countries") fig3 = px.pie(data_pop, values='population', names='age', title="Population by age 1985-2015") return fig, fig2, fig3 elif column_chosen == 'GDP wise suicide': fig = px.line_3d(gdp_country, y='gdp_per_capita ($)', x='total_suicide', z='year', color='country', title="GDP wise suicide 1985 - 2015") fig2 = px.bar( gdp_year, title="GDP wise suicide:Correlation between suicide and GDP according to each year") fig3 = px.pie(gdp_gender, values='total_suicide', names='country', title="GDP wise suicide by countries 1985 -2016") return fig, fig2, fig3
def plot_3d(n_clicks, peakLabel, options): if (n_clicks is None) or (mint.rt_projections is None) or (peakLabel is None): raise PreventUpdate data = mint.rt_projections[peakLabel] samples = [] for i, key in enumerate(list(data.keys())): sample = data[key].to_frame().reset_index() sample.columns = ['retentionTime', 'intensity'] sample['peakArea'] = sample.intensity.sum() sample['FileName'] = basename(key) samples.append(sample) samples = pd.concat(samples) fig = px.line_3d(samples, x='retentionTime', y='peakArea', z='intensity', color='FileName') fig.update_layout({'height': 800}) if 'legend_horizontal' in options: fig.update_layout(legend_orientation="h") if not 'legend' in options: fig.update_layout(showlegend=False) fig.update_layout({'title': peakLabel}) return fig
def fit_beta_gamma_mh(self, region, sample, confirmed, law_s=None, law_c=None, weight_c=None, method='naive', **kvarg): if law_s is None: law_s = self.law_s if law_c is None: law_c = self.law_c if weight_c is None: weight_c = self.weight_c def func(x): dynamic = SIRQ(*x) epidemic = dynamic.estimate(region, max(confirmed.t[-1], sample.t[-1])) like = likelihood(epidemic, sample, law_s, confirmed, law_c, weight_c) return like def func2(x): dynamic = SIRQ(*np.exp(x)) epidemic = dynamic.estimate(region, max(confirmed.t[-1], sample.t[-1])) return likelihood(epidemic, sample, law_s, confirmed, law_c, weight_c) * np.prod(np.exp(x)) if method == 'naive': x, walker, like = mh([0.5, 0.1, 0.1], func, [[0.01, 1], [0.01, 1], [0.01, 1]], **kvarg) elif method == 'mirror': x, walker, like = mh([0.5, 0.1, 0.1], func, [[0.01, 1], [0.01, 1], [0.01, 1]], ascdes=(np.log, np.exp), **kvarg) elif method == 'repar': x, walker, like = mh(np.log([0.5, 0.1, 0.1]), func2, np.log([[0.01, 1], [0.01, 1], [0.01, 1]]), **kvarg) x = np.exp(x) walker = np.exp(walker) like /= np.prod(walker, axis=1) self.beta, self.gamma, self.theta = x self.loglikely = np.log(func(x)) self.walker = walker self.like = like fig = px.line_3d(x=self.walker[:, 0], y=self.walker[:, 1], z=self.walker[:, 2], log_x=True, log_y=True, log_z=True) fig.show()
def plot_wellpath(wellpath, add_well=None, names=None): """ Plot a 3D Wellpath. :param wellpath: a wellpath object with 3D position, :param add_well: include a new well or list of wells :param names: set name or list of names for wells included in the plot :return: 3D Plot - plotly.graph_objects.Figure """ units = wellpath.units well1 = pd.DataFrame(list(zip(wellpath.tvd, wellpath.north, wellpath.east)), columns=['tvd', 'north', 'east']) well1["well"] = 1 result = well1 if add_well is not None: wells = [] if type(add_well) is not list: add_well = [add_well] well_no = 2 for x in add_well: new_well = pd.DataFrame(list(zip(x.tvd, x.north, x.east)), columns=['tvd', 'north', 'east']) new_well["well"] = well_no wells.append(new_well) well_no += 1 all_wells = well1.append(wells) result = all_wells if names is not None: if type(names) is not list: names = [names] well_no = 1 for x in names: result.replace({'well': {well_no: x}}, inplace=True) well_no += 1 fig = px.line_3d(result, x="east", y="north", z="tvd", color='well') if units == 'metric': fig.update_layout(scene=dict( xaxis_title='East, m', yaxis_title='North, m', zaxis_title='TVD, m', aspectmode='manual')) else: fig.update_layout(scene=dict( xaxis_title='East, ft', yaxis_title='North, ft', zaxis_title='TVD, ft', aspectmode='cube')) fig.update_scenes(zaxis_autorange="reversed") return fig
def plot_output3D(output_csv, output_folder, board): """creates plot from csv file""" # store coordinates of nets x_df = [] y_df = [] z_df = [] nets_df = [] # open output file with open(f"{output_folder}/{output_csv}") as file: for i, line in enumerate(csv.reader(file)): # only read rows with coordinates if line[0][0] == '(': # convert list as string to list coordinates = ast.literal_eval(line[1]) # if no coordinates skip row if not coordinates: continue # add coordinates for x, y, z in coordinates: x_df.append(x) y_df.append(y) z_df.append(z) nets_df.append(i) # create dataframe df = pd.DataFrame(dict(X=x_df, Y=y_df, Z=z_df, nets=nets_df)) # plot nets fig = px.line_3d(df, x='X', y='Y', z='Z', color="nets") # add gates to plot fig.add_scatter3d(x=[board.gates[gate].loc[0] for gate in board.gates], y=[board.gates[gate].loc[1] for gate in board.gates], z=[board.gates[gate].loc[2] for gate in board.gates], mode="markers+text", marker_symbol="square", marker_color="red", marker_size=12, text=list(range(1, len(board.gates) + 1)), textposition="middle center", name="gates") # set grid steps fig.update_layout(scene=dict( xaxis=dict(dtick=1), yaxis=dict(dtick=1), zaxis=dict(dtick=1))) # change font size fig.layout.font.size = 10 # show plot fig.show()
def graph_ficticious_play_for_payoff_table(payoff_table: PayoffTable, save_path: str): generations = [] policy_indexes = [] policy_selection_probs = [] policy_keys = [] policy_classes = [] policy_configs = [] policy_tags = [] payoff_matrix = payoff_table.get_payoff_matrix() for i, l in enumerate(range(2, len(payoff_matrix) + 1)): p = payoff_matrix[:l, :l] avgs, exps = fictitious_play(iters=2000, payoffs=p) scores = avgs[-1] for policy_idx, alpha_rank_score in enumerate(scores): policy_spec = payoff_table.get_policy_for_index(policy_idx) generations.append(i) policy_indexes.append(policy_idx) policy_keys.append(policy_spec.key) policy_classes.append(policy_spec.class_name) policy_configs.append(policy_spec.config_key) policy_tags.append(policy_spec.tags) policy_selection_probs.append(alpha_rank_score) alpha_rank_df = pd.DataFrame({ "generation": generations, "policy": policy_indexes, "policy_selection_probs": policy_selection_probs, "policy_keys": policy_keys, "policy_configs": policy_configs, "policy_classes": policy_classes, # "policy_tags": ['\n'.join(tags) for tags in policy_tags], }) fig = px.line_3d(alpha_rank_df, x="policy", y="generation", z="policy_selection_probs", color="generation", color_discrete_sequence=px.colors.sequential.Plotly3, template='plotly_dark', title=f"Population Selection Probs (Fictitious Play) over Generations (reload page to refresh)", hover_data=["policy_selection_probs", "policy_classes"], ) fig.update_layout( width=900, height=900, autosize=True) fig.update_layout({ 'plot_bgcolor': 'rgba(34, 34, 34, 1)', 'paper_bgcolor': 'rgba(0, 0, 0, 0)', }) fig.update_layout(showlegend=False) fig.layout.scene.xaxis.autorange = 'reversed' # fig.show() plotly.offline.plot(fig, filename=save_path, auto_open=False)
def compareSmoothvsRaw(): ''' This function takes a raw and smoothed data frame and plots both of them showing their differences NOTE only run this while featShaper() is running so the right variables are loaded ''' # insert different types so that dashed and full lines can be plotted dfSelectR.insert(4, "Type", 0) dfSelectSMFix2.insert(4, "Type", 1) # rename the raw feature Z axis dfSelectRNew = dfSelectR.rename(columns={'Zs': 'Z'}) a = pd.concat([dfSelectRNew, dfSelectSMFix2]) dfSelectRNew dfSelectSMFix2 px.line_3d(a, x="X", y="Y", z="Z", color="ID", line_dash="Type", title = "Smooth vs Raw").show()
def plot(self, backend='plotly'): if backend == 'matplotlib': import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection="3d") for i in range(0, len(self.stellarator.coils)): ax = self.stellarator.coils[i].plot(ax=ax, show=False, color=["b", "g", "r", "c", "m", "y"][i%len(self.stellarator._base_coils)]) self.ma.plot(ax=ax, show=False, closed_loop=False) ax.view_init(elev=90., azim=0) ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) ax.set_zlim(-1, 1) plt.show() elif backend == 'plotly': stellarator = self.stellarator coils = stellarator.coils ma = self.ma gamma = coils[0].gamma N = gamma.shape[0] l = len(stellarator.coils) data = np.zeros((l*(N+1), 4)) labels = [None for i in range(l*(N+1))] for i in range(l): data[(i*(N+1)):((i+1)*(N+1)-1),:-1] = stellarator.coils[i].gamma data[((i+1)*(N+1)-1),:-1] = stellarator.coils[i].gamma[0, :] data[(i*(N+1)):((i+1)*(N+1)),-1] = i for j in range(i*(N+1), (i+1)*(N+1)): labels[j] = 'Coil %i ' % stellarator.map[i] N = ma.gamma.shape[0] ma_ = np.zeros((ma.nfp*N+1, 4)) ma0 = ma.gamma.copy() theta = 2*np.pi/ma.nfp rotmat = np.asarray([ [cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]]).T for i in range(ma.nfp): ma_[(i*N):(((i+1)*N)), :-1] = ma0 ma0 = ma0 @ rotmat ma_[-1, :-1] = ma.gamma[0,:] ma_[:, -1] = -1 data = np.vstack((data, ma_)) for i in range(ma_.shape[0]): labels.append('Magnetic Axis') import plotly.express as px fig = px.line_3d(x=data[:,0], y=data[:,1], z=data[:,2], color=labels, line_group=data[:,3].astype(np.int)) fig.show() else: raise NotImplementedError('backend must be either matplotlib or plotly')
def graph_errors(startEPS, stopEPS, stepEPS, startSample, stopSample, fromDate, toDate, whatToGraph): data = get_error_frame_from_file(startEPS, stopEPS, stepEPS, startSample, stopSample, fromDate, toDate) if whatToGraph not in data.columns: whatToGraph = 'R2 ENTRIES' r2_graph = px.line_3d( data, x='EPS', y='MIN_SAMPLES', z=whatToGraph, title='DBSCAN Parameter Analysis: {}'.format(whatToGraph)) r2_graph.show()
def view( title: str, points: List[Tuple[float, float, float]], first_t: float, last_t: float, inc: float, ) -> None: # print(f"view: points={points}") fig = px.line_3d( title=title, x=[x for x, _, _ in points], y=[y for _, y, _ in points], z=[z for _, _, z in points], ) fig.layout.scene.camera.projection.type = "orthographic" fig.show()
def plot_streamlines_plotly(output): seeds, positions = output # Conver to a list of streamlines streamlines = OutputToStreamlines(output) colors = [] i = 0 for sl in streamlines: colors.extend([i for x in range(len(sl))]) i += 1 colors = np.array(colors) coords = np.reshape(streamlines, (-1, 3)) fig = px.line_3d(x=coords[:, 0], y=coords[:, 1], z=coords[:, 2], color=colors) fig.show()
def plot_stellarator(stellarator, axis=None, extra_data=None): coils = stellarator.coils gamma = coils[0].gamma N = gamma.shape[0] l = len(stellarator.coils) data = np.zeros((l*(N+1), 3)) labels = [None for i in range(l*(N+1))] groups = [None for i in range(l*(N+1))] for i in range(l): data[(i*(N+1)):((i+1)*(N+1)-1), :] = stellarator.coils[i].gamma data[((i+1)*(N+1)-1), :] = stellarator.coils[i].gamma[0, :] for j in range(i*(N+1), (i+1)*(N+1)): labels[j] = 'Coil %i ' % stellarator.map[i] groups[j] = i+1 if axis is not None: N = axis.gamma.shape[0] ma_ = np.zeros((axis.nfp*N+1, 3)) ma0 = axis.gamma.copy() theta = 2*np.pi/axis.nfp rotmat = np.asarray([ [cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]]).T for i in range(axis.nfp): ma_[(i*N):(((i+1)*N)), :] = ma0 ma0 = ma0 @ rotmat ma_[-1, :] = axis.gamma[0, :] data = np.vstack((data, ma_)) for i in range(ma_.shape[0]): labels.append('Magnetic Axis') groups.append(0) if extra_data is not None: for i, extra in enumerate(extra_data): labels += ['Extra %i' % i ] * extra.shape[0] groups += [-1-i] * extra.shape[0] data = np.vstack((data, extra)) import plotly.express as px fig = px.line_3d(x=data[:,0], y=data[:,1], z=data[:,2], color=labels, line_group=groups) fig.show()
def get_plotly_html(bs, graph_id_str, bf_ids, fpath, graph_opt): div = None # Make binary structure from the selected BinStruct cbs = CustomBinStruct() bfs = BinField.objects.filter(bs=bs) for bf in bfs: cbs.append_binfield(bf.label, bf.bits) cbs.make_binstruct() # Read the selected file data = cbs.read_bin_to_dict(fpath) df = pd.DataFrame.from_dict(data) # Get field fields from the bf_ids fls = [] for bf_id in bf_ids: fls.append(get_binfield_label(bf_id)) # Plot fig = None if graph_id_str == SelectGraphForm.SCATTER: fig = px.scatter(data_frame=df, x=fls[0], y=fls[1]) elif graph_id_str == SelectGraphForm.SCATTER_3D: d = go.Scatter3d(x=data[fls[0]], y=data[fls[1]], z=data[fls[2]], mode='markers', marker=dict(size=2)) fig = go.Figure(d) fig.update_layout(scene=dict( xaxis_title=fls[0], yaxis_title=fls[1], zaxis_title=fls[2])) elif graph_id_str == SelectGraphForm.LINE: fig = px.line(data_frame=df, x=fls[0], y=fls[1]) elif graph_id_str == SelectGraphForm.LINE_3D: fig = px.line_3d(data_frame=df, x=fls[0], y=fls[1], z=fls[2]) if fig: fig.update_layout(width=graph_opt.get('width'), height=graph_opt.get('height')) div = fig.to_html(full_html=False) return div
def update_figure(S, R, B): def lorenz(x, y, z, s=S, r=R, b=B): #s=10, r=28, b=2.667): # """ # Given: # x, y, z: a point of interest in three dimensional space # s, r, b: parameters defining the lorenz attractor # Returns: # x_dot, y_dot, z_dot: values of the lorenz attractor's partial # derivatives at the point x, y, z # """ x_dot = s * (y - x) y_dot = r * x - y - x * z z_dot = x * y - b * z return x_dot, y_dot, z_dot dt = 0.001 num_steps = 10000 # Need one more for the initial values xs = np.empty(num_steps + 1) ys = np.empty(num_steps + 1) zs = np.empty(num_steps + 1) # Set initial values xs[0], ys[0], zs[0] = (0., 1., 1.05) # Step through "time", calculating the partial derivatives at the current point # and using them to estimate the next point for i in range(num_steps): x_dot, y_dot, z_dot = lorenz(xs[i], ys[i], zs[i]) xs[i + 1] = xs[i] + (x_dot * dt) ys[i + 1] = ys[i] + (y_dot * dt) zs[i + 1] = zs[i] + (z_dot * dt) df = pd.DataFrame({'x': xs, 'y': ys, 'z': zs}) fig = px.line_3d(df, x="x", y="y", z="z") return fig
# DEV: #DDataFrame = pd.concat(vectors, axis=1) # Arrange flight data in dataframe FlightPath = pd.DataFrame(index=times) FlightPath['lat'] = lat FlightPath['lon'] = lng FlightPath['alt'] = alt traceFlightPath = go.Scatter3d(x=FlightPath['lat'], y=FlightPath['lon'], z=FlightPath['alt'], mode='lines', line=dict(color='black', width=5), text=FlightPath.index, name='Flight Path') data.append(traceFlightPath) # Plot data #plotly.offline.plot(data, filename='NewPlot.html') # dev: #DDataFrame['index'] = DDataFrame.index fig = px.line_3d(DDataFrame, x='lat', y='lng', z='alt', line_group='ID', animation_frame='Time') plotly.offline.plot(fig, filename='dev.html')
locals()["df_" + str(i)]) #adjustment, the coef is obtained locals()["prm_" + str(i)] = parameters( locals()["coef_" + str(i)]) #parameters, the prm is obtained locals()["fig_" + str(i)], locals()["v_" + str(i)], locals()["df_" + str(i)] = graph( locals()["df_" + str(i)], locals()["coef_" + str(i)], i, locals()["prm_" + str(i)]) st.pyplot(locals()["fig_" + str(i)]) st.markdown(get_image_download_link(locals()["fig_" + str(i)]), unsafe_allow_html=True) df_united = pd.concat((df_united, locals()["df_" + str(i)]), axis=0, ignore_index=True) st.markdown(get_table_download_link(locals()["v_" + str(i)]), unsafe_allow_html=True) df_prm = pd.DataFrame( locals()["prm_" + str(i)], index=['Xc', 'Yc', 'Major radius', 'Minor radius', 'Angle'], columns=['parameters']) if st.checkbox("Parameters of " + str(i + 1) + '° XY-Plane projection'): st.table(df_prm) st.header('\n**3D View**\n') fig = px.line_3d(df_united, x="X", y="Y", z="Z", color='section') st.write(fig)
subplot_titles=[ 'Color corresponds to z', 'Color corresponds to distance to origin' ], ) fig.add_trace(go.Surface(x=x, y=y, z=z, colorbar_x=-0.07), 1, 1) fig.add_trace(go.Surface(x=x, y=y, z=z, surfacecolor=x**2 + y**2 + z**2), 1, 2) fig.update_layout(title_text="Ring cyclide") fig.show() # In[ ]: import plotly.express as px import plotly.express as px df = px.data.gapminder().query("country=='Brazil'") fig = px.line_3d(df, x="gdpPercap", y="pop", z="year") fig.show() # In[ ]: import plotly.express as px import plotly.express as px df = px.data.gapminder().query("continent=='Europe'") fig = px.line_3d(df, x="gdpPercap", y="pop", z="year", color='country') fig.show() # In[ ]: import plotly.graph_objects as go import pandas as pd import numpy as np
barra = st.slider("Seleccione el Valor", 0, 3000, 1500, step=100) l1 = list(range(-barra, 0)) l1 = reversed(l1) l2 = [0] * barra l3 = [0] * barra data2 = {"Lista 1": l1, "Lista 2": l2, "Lista 3": l3} df2 = pd.DataFrame(data2) st.write(df2) columnas = df2.columns columnsbox = st.selectbox("Seleccione la Columna", columnas) fig = px.line_3d(df2, x="Lista 3", y=columnsbox, z="Lista 1") st.write(fig) radio = st.radio("Seleccione la Potencia", ("Cuadrado", "Cúbico", "Cuarta")) radio2 = st.radio("Seleccione el Valor", (1, 2, 3)) if radio == "Cuadrado": resultado = radio2**2 st.write("Resultado es:", resultado) if radio == "Cúbico": resultado = radio2**3 st.write("Resultado es:", resultado) if radio == "Cuarta":
def update_graph(n): global X global Y Z = 0 # For real-time plot # new_X = str(tail()).split(',')[1] # new_Y = str(tail()).split(',')[2] # For simulated real-time plot if not file=="": new_X = file.readline().split(',')[1] new_Y = file.readline().split(',')[2] else: file.seek(0,0) # print(new_X, new_Y) if not (X==new_X and Y==new_Y): X.append(new_X) Y.append(new_Y) # Add trace data = go.Scatter( x = list(X), y = list(Y), # z = Z, name = 'Scatter', # mode = 'lines+markers' mode = 'lines' ) # Layout the map # x_range = [-10, 65] # y_range = [-30, 65] # layout = go.Layout(xaxis=dict(range=x_range), # yaxis=dict(range=y_range), # height=500, # showlegend=False, # uirevision='graph-update', # paper_bgcolor='rgba(0,0,0,0)', # plot_bgcolor='rgba(0,0,0,0)' # ) # # Create figure # fig = go.Figure( # data = [data], # layout=layout # ) # Add images # fig.add_layout_image( # go.layout.Image( # source=img, # xref="x", # yref="y", # x=x_range[0], # y=y_range[1], # sizex=75, # sizey=85, # sizing="stretch", # opacity=1, # layer="below") # ) # Set templates # fig.update_layout(template="plotly_white") # fig.update_xaxes(showticklabels=False, zeroline=False) # fig.update_yaxes(showticklabels=False, zeroline=False) # fig.update_layout(xaxis_showgrid=False, yaxis_showgrid=False) fig = px.line_3d(x=list(X), y=list(Y), z=list(Y)) return fig
import pandas as pd import plotly.express as px import plotly.graph_objects as go df = pd.read_csv( '/Users/simonvermeir/Documents/industrial-engineering/SchoolCurrent/MasterProef/Master-Thesis-SSP/data/log.csv' ) #fig = px.line(df, x = 'Time', y = 'Accepted', z='Temperature', title='SSP') fig = px.line_3d(df, x='Time', y='Temperature', z='Accepted', title='SSP', template="plotly_dark") #fig = go.Figure(data=[go.Surface(z=df.Accepted, x=df.Time, y=df.Temperature)]) fig.show()
fig.update_layout(scene_aspectmode='cube', scene=dict(xaxis=dict(range=[0, 144]), yaxis=dict(range=[0, 144]), zaxis=dict(range=[0, 144])), scene_camera=camera) fig.show() colors = [] i = 0 for sl in streamlines: colors.extend([i for x in range(len(sl))]) i += 1 colors = np.array(colors) fig = px.line_3d(x=coords[:, 0], y=coords[:, 1], z=coords[:, 2], color=colors, range_x=[0, 144], range_y=[0, 144], range_z=[0, 144]) fig.update_layout(scene_aspectmode='cube', scene=dict(xaxis=dict(range=[0, 144]), yaxis=dict(range=[0, 144]), zaxis=dict(range=[0, 144])), scene_camera=camera) fig.show() #tractogram = #print(tom.shape)
def main(): # reading in the data column_names = [ "sepal_length", "sepal_width", "petal_length", "petal_width", "class", ] iris_df = pd.read_csv( "C:/Users/KRATI PATIDAR/Desktop/BDA696_MLE/iris.data", names=column_names ) print(iris_df.head()) # summary statistics iris_arr = iris_df.to_numpy() print(iris_arr) print("Mean = ", np.mean(iris_df)) print("Minimum = ", np.min(iris_df)) print("Maximum = ", np.max(iris_df)) print("First quantile = ", np.quantile(iris_arr[:, :-1], q=0.25, axis=0)) print("Second quantile = ", np.quantile(iris_arr[:, :-1], q=0.50, axis=0)) print("Third quantile = ", np.quantile(iris_arr[:, :-1], q=0.75, axis=0)) print("Fourth quantile = ", np.quantile(iris_arr[:, :-1], q=1, axis=0)) print(iris_df["class"].unique()) # making plots plot_1 = px.scatter( iris_df, x="sepal_width", y="sepal_length", size="petal_length", hover_data=["petal_width"], color="class", title="Scatter Plot for all variables for different classes", ) plot_1.show() plot_2 = px.line( iris_df, x="petal_width", y="petal_length", color="class", title="Line Plot for Petal Width and Petal Length for all classes", ) plot_2.show() plot_3 = px.violin( iris_df, x="sepal_width", y="sepal_length", color="class", title="Violin Plot for sepal length and sepal width for all classes", ) plot_3.show() plot_4 = px.scatter_3d( iris_df, x="sepal_length", y="sepal_width", z="petal_length", color="class", title="3-D Scatter Plot for sepal length, sepal width and petal length", ) plot_4.show() plot_5 = px.line_3d( iris_df, x="petal_width", y="petal_length", z="sepal_width", hover_data=["sepal_length"], color="class", title="3-D Line Plot for all variables of all classes ", ) plot_5.show() # normalization, random forest and decision tree classifiers x = iris_arr[:, 0:-1] y = iris_df["class"].values # pipeline_1 for random forest classifier pipeline_1 = Pipeline( [ ("normalize", Normalizer()), ("randomforest", RandomForestClassifier(random_state=1234)), ] ) print(pipeline_1.fit(x, y)) # pipeline_2 for decision tree classifier pipeline_2 = Pipeline( [ ("normalize", Normalizer()), ("decisiontree", DecisionTreeClassifier()), ] ) print(pipeline_2.fit(x, y)) if __name__ == "__main__": sys.exit(main())
def plot_wellpath(well, add_well=None, names=None, style=None): """ Plot a 3D Wellpath. Arguments: well: a well object with 3D position, add_well: include a new well or list of wells names: set name or list of names for wells included in the plot style: {'darkMode': bool, # activate dark mode. default = False 'color': str, # color by specific property. e.g. 'dls'|'dl'|'tvd'|'md'|'inc'|'azi'. default = None 'size': num, # marker size. default = 2 } Returns: 3D Plot - plotly.graph_objects.Figure """ units = well.info['units'] well1 = pd.DataFrame(well.trajectory) well1["well"] = 1 result = well1 if add_well is not None: wells = [] if type(add_well) is not list: add_well = [add_well] well_no = 2 for x in add_well: new_well = pd.DataFrame(x.trajectory) new_well["well"] = well_no wells.append(new_well) well_no += 1 all_wells = well1.append(wells) result = all_wells if names is not None: if type(names) is not list: names = [names] well_no = 1 for x in names: result.replace({'well': {well_no: x}}, inplace=True) well_no += 1 set_style = {'darkMode': False, 'color': None, 'size': 2} if style is not None: for key in style.keys(): set_style[key] = style[key] template = None if set_style['darkMode']: template = 'plotly_dark' if len(result.well.unique()) > 1 or set_style['color'] is None: color = 'well' fig = px.line_3d(result, x="east", y="north", z="tvd", color=color) else: fig = go.Figure(data=[ go.Scatter3d( x=result['east'], y=result['north'], z=result['tvd'], mode='markers', marker=dict( size=set_style['size'], color=result[set_style[ 'color']], # set color to an array/list of desired values showscale=True, opacity=0.8), legendgroup=True, ) ]) if units == 'metric': fig.update_layout(scene=dict(xaxis_title='East, m', yaxis_title='North, m', zaxis_title='TVD, m', aspectmode='manual')) else: fig.update_layout(scene=dict(xaxis_title='East, ft', yaxis_title='North, ft', zaxis_title='TVD, ft', aspectmode='manual')) fig.update_scenes(zaxis_autorange="reversed") fig.layout.template = template return fig
import plotly.express as px import plotly.express as px #X year #Y Tons #each line is a year gapminder = px.data.gapminder().query("continent=='Europe'") fig = px.line_3d(gapminder, x="gdpPercap", y="pop", z="year", color='country') fig.show()
# Define the data and run the simulation if __name__ == "__main__": bodies = [ body(vector(0, 0, 0), vector(0, 0, 0), 2e30, 'Sun'), #body(vector(0,-7.78e11,0),vector(-13000,0,0),2e30,'Sun2'), body(vector(0, 1.5e11, 0), vector(30000, 0, 0), 6e24, 'Earth'), body(vector(0, 1.6e11, 0), vector(38500, 0, 0), 1e3, 'Probe'), body(vector(7.78e11, 0, 0), vector(0, -13000, 0), 1.898e27, 'Jupiter'), #body(vector(0,(1.5e11-3.85e8),0),vector(31000,0,0),7.34e22,'Moon') ] solution_data = compute_n_body_problem(bodies, 100, 600000, 10000) #fig = px.scatter_3d(x=solution_data[0],y=solution_data[1],z=solution_data[2],color=solution_data[3],animation_frame=solution_data[4]) fig = px.line_3d(x=solution_data[0], y=solution_data[1], z=solution_data[2], color=solution_data[3]) fig.update_layout(scene=dict( xaxis=dict(nticks=4, range=[min(solution_data[0]), max(solution_data[0])], autorange=False), yaxis=dict(nticks=4, range=[min(solution_data[1]), max(solution_data[1])], autorange=False), zaxis=dict(nticks=4, range=[min(solution_data[2]), max(solution_data[2])], autorange=False), ),
BASE = "/Users/simonvermeir/Documents/industrial-engineering/SchoolCurrent/MasterProef/Master-Thesis-SSP" LOGFILE = "/Users/simonvermeir/Documents/industrial-engineering/SchoolCurrent/MasterProef/Master-Thesis-SSP/data" \ "/instances/catanzaro/cat_10_10_4_1/log_ran_swap-2job_full_sd_sw_v1_none.csv" # app = dash.Dash(__name__) app = dash.Dash( __name__, meta_tags=[{"name": "viewport", "content": "width=device-width"}] ) server = app.server #DATA df = pd.read_csv(LOGFILE) fig = px.line_3d(df, x = 'T_RUN', y = 'TEMP', z='ACCEPT', title='SSP') #fig.update_xaxes(autorange='reversed') fig1 = px.line(df, x = 'T_RUN', y = 'SW') #fig1.update_xaxes(autorange="reversed") fig2 = px.line(df, x = 'T_RUN', y = 'IMPROVE') #fig2.update_xaxes(autorange="reversed") fig3 = px.line(df, x = 'T_RUN', y = 'TEMP') #fig3.update_xaxes(autorange="reversed") fig4 = px.line(df, x = 'T_RUN', y = 'ACCEPT') #fig4.update_xaxes(autorange="reversed")$ app.layout = html.Div( style={"height": "100%"}, children=[
'Tipo_Vivienda': '1 cuarto', 'population': pd.to_numeric(obj['vph_1cuart'], errors='coerce') }, ignore_index=True) DF1 = DF1.append( { 'Entidad': obj['nom_ent'], 'Tipo_Vivienda': '2 cuartos', 'population': pd.to_numeric(obj['vph_2cuart'], errors='coerce') }, ignore_index=True) DF1 = DF1.append( { 'Entidad': obj['nom_ent'], 'Tipo_Vivienda': '3 o más cuartos', 'population': pd.to_numeric(obj['vph_3ymasc'], errors='coerce') }, ignore_index=True) # Replace NaN with 0 DF1.fillna(0, inplace=True) # Define random surface df = px.data.election() fig = px.line_3d(DF1, x="Tipo_Vivienda", y="Entidad", z="population", color="Tipo_Vivienda", line_dash="Tipo_Vivienda") fig.show()
hover_name="district", symbol="result", color_discrete_map={ "Joly": "blue", "Bergeron": "green", "Coderre": "red" }, ) fig.write_html(os.path.join(dir_name, "scatter_3d.html")) import plotly.express as px election = px.data.election() fig = px.line_3d(election, x="Joly", y="Coderre", z="Bergeron", color="winner", line_dash="winner") fig.write_html(os.path.join(dir_name, "line_3d.html")) # #### Polar Coordinates import plotly.express as px wind = px.data.wind() fig = px.scatter_polar( wind, r="frequency", theta="direction", color="strength", symbol="strength",
def analyzeGpx(name): fileName = 'hikes/%s/%s.gpx' % (name, name) gpx_file = open(fileName, 'r') projName = os.path.splitext(os.path.basename(fileName))[0] dirName = os.path.dirname(fileName) gpx = gpxpy.parse(gpx_file) nameRecording = gpx.name if (nameRecording == None): nameRecording = projName data = gpx.tracks[0].segments[0].points for i in range(1, len(gpx.tracks[0].segments)): data.extend(gpx.tracks[0].segments[i].points) # Start Position start = data[0] # End Position finish = data[-1] df = pd.DataFrame(columns=['lon', 'lat', 'alt', 'time']) for point in data: df = df.append( { 'lon': point.longitude, 'lat': point.latitude, 'alt': point.elevation * M_TO_FT, 'time': point.time }, ignore_index=True) alt_dif = [0] time_dif = [0] dist_hav = [0] dist_hav_no_alt = [0] dist_dif_hav_2d = [0] alt_inc = 0 alt_dec = 0 # elevation moving average over 50 points alt_inc50 = 0 alt_dec50 = 0 dist500 = 0 for index in range(len(data)): if index == 0: pass else: start = data[index - 1] stop = data[index] distance_hav_2d = haversine.haversine( (start.latitude, start.longitude), (stop.latitude, stop.longitude)) * 1000 dist_dif_hav_2d.append(distance_hav_2d) dist_hav_no_alt.append(dist_hav_no_alt[-1] + distance_hav_2d) alt_d = (start.elevation - stop.elevation) * M_TO_FT if (alt_d > 0): alt_inc = alt_inc + alt_d else: alt_dec = alt_dec - alt_d alt_dif.append(alt_d) distance_hav_3d = sqrt(distance_hav_2d**2 + (alt_d)**2) * M_TO_FT * FT_TO_MI time_delta = (stop.time - start.time).total_seconds() time_dif.append(time_delta) dist_hav.append(dist_hav[-1] + distance_hav_3d) if (index % 50 == 0): startel = data[index - 50].elevation dif_elev = (stop.elevation - startel) * M_TO_FT if (dif_elev > 0): alt_inc50 = alt_inc50 + dif_elev else: alt_dec50 = alt_dec50 - dif_elev if (index % 500 == 0): dist500 = dist500 + (dist_hav[index] - dist_hav[index - 500]) increase = gpx.get_uphill_downhill()[0] * M_TO_FT decrease = gpx.get_uphill_downhill()[1] * M_TO_FT length = gpx.length_2d() * M_TO_FT * FT_TO_MI ratioCorrection = 0.55 dist500 = length * ratioCorrection ratioCorrection2 = dist500 / dist_hav[-1] df['dist_hav_2d'] = dist_hav_no_alt df['dis_hav_3d'] = np.asarray(dist_hav) * ratioCorrection2 df['alt_dif'] = alt_dif df['time_dif'] = time_dif df['dis_dif_hav_2d'] = dist_dif_hav_2d #df['spd'] = (df['dis_dif_hav_2d'] / df['time_dif']) * 3.6 * 0.621371 # speed in mph timeTot = "%i hours, %i minutes" % (floor( sum(time_dif) / 60 / 60), floor(sum(time_dif) / 60 % 60)) fig = px.line_3d(df, x='lon', y='lat', z='alt', labels={ 'lon': 'Longitude', 'lat': 'Latitude', 'alt': 'Elevation (feet)' }) fig.write_html("%s/3d.html" % dirName) fig2 = px.line(df, x='dis_hav_3d', y='alt', labels={ 'dis_hav_3d': 'Distance (miles)', 'alt': 'Altitude (feet)' }) fig2.write_html("%s/elev.html" % dirName) return [ name, nameRecording, timeTot, data[0].time, data[-1].time, "%.2f" % dist500, "%.0f" % alt_inc50, "%.0f" % alt_dec50, sum(time_dif) ]