def visual_structure_entropy(sequence, shape_list=None, si=-0.6, sm=1.8, md=None, figsize=(15, 6)): """ Plot the shannon entropy and the pairing probability sequence -- Sequence shape_list -- Shape list """ import Structure, Figures import matplotlib.pyplot as plt if shape_list: assert len(sequence) == len(shape_list) Len = len(sequence) probList = Structure.partition(sequence, shape_list=shape_list, si=si, sm=sm, md=md, return_pfs=False) shannon = Structure.calcShannon(probList, Len) # Plot figure fig, axs = plt.subplots(2, 1, figsize=figsize) axs[0].bar(range(1, Len + 1), shannon, width=1) axs[0].set_ylim(0, 0.4) axs[0].set_xlim(1, Len) axs[0].set_ylabel("Shannon Entropy") Figures.rainbowPlot(probList, axs[1], length=Len, lw=1) return fig, axs
def update_figure_polar(value_main_tab, value_analysis, gene_name): if gene_name is None: raise Exception() else: if value_main_tab == 'main-tab-2' and value_analysis == 'temporal': array_gene_time = np.concatenate( (gene_data[gene_name]['rep1'], gene_data[gene_name]['rep2'], gene_data[gene_name]['rep3'][:, [0, 2]]), axis=1) l_time_reg = [] for x in range(8): l_time_reg.append( LinearRegression.make_time_regression( array_gene_time[x, :], simple=False, predict=True)) l_time_reg_simple = [] for x in range(8): l_time_reg_simple.append( LinearRegression.make_time_regression( array_gene_time[x, :], simple=True, predict=False)) figure_polar = Figures.compute_figure_polar_tab_3(l_time_reg) figure_mean = Figures.compute_figure_mean_tab_3( l_time_reg) #, yaxis_type, yaxis_scale) return figure_polar, figure_mean else: raise PreventUpdate
def draw_barfigure(self,fig,axis,data,title): import numpy as np from matplotlib.widgets import RadioButtons,Button import matplotlib.pyplot as plt import Figures as Fig if self.static: fig.patch.set_facecolor("white") #write the plot in the axis self._draw_barplot(axis,data[0],self.vals,title=title,nokey=self.nokey) #add the lines useful for a strong scaling test if self.strong_scaling: self._strong_scaling_lines(data,axis) #if self.vals == 'Percent': axis.set_yticks(np.arange(0,100,10)) #then add buttons to the plot if self.radio is None and not self.static: self.radio = RadioButtons(plt.axes([0.0, 0.75, 0.08, 0.11], axisbg='lightgoldenrodyellow'), ('Seconds', 'Percent'), active=1 if self.vals=='Percent' else 0) self.radio.on_clicked(self.replot) tt=axis.get_xticks() routics=[Fig.axis_from_data(fig,axis,(tic-0.45*self.barwidth,self.barwidth)) for tic in tt] unbtics=[Fig.axis_from_data(fig,axis,(tic+0.15*self.barwidth,self.barwidth)) for tic in tt] self.routine_buttons=[] from functools import partial for i,t in enumerate(routics): if self.routines[i] is None: continue but=Button(plt.axes([t[0], 0.0, 0.15*t[1], 0.05]), 'R') but.on_clicked(partial(self.routines_plot,i)) self.routine_buttons.append(but) for i,t in enumerate(unbtics): if not self.unbalancings[i]: continue but=Button(plt.axes([t[0], 0.0, 0.15*t[1], 0.05]), 'U') but.on_clicked(partial(self.workload_plot,i)) self.routine_buttons.append(but) #fig.canvas.mpl_connect('pick_event',self._onclick_ev) fig.canvas.mpl_connect('button_press_event', partial(self._onclick_ev,fig,axis)) fig.canvas.draw()
def update_figure_time( gene_name): #, yaxis_type, yaxis_scale, data_type, value_tab ): if gene_name is None: raise Exception() else: fig_space = Figures.compute_figure_space(gene_data[gene_name]) fig_time = Figures.compute_figure_time(gene_data[gene_name]) fig_3D = Figures.compute_figure_3D(gene_data[gene_name]) data = gene_data[gene_name] array_gene = data['rep1'] array_gene_std = data['rep1_std'] array_gene_2 = data['rep2'] array_gene_std_2 = data['rep2_std'] array_gene_3 = data['rep3'] array_gene_std_3 = data['rep3_std'] l_tr = [[Styled_th(' ', {'background-color': colorscale[5]})] + [Styled_th('x = ' + str(x)) for x in range(8)]] for idx, i in enumerate(range(0, 24, 6)): l_th = [ Styled_th('t = ' + str(i) + 'h', {'background-color': colorscale[5]}) ] for j in range(0, 8, 1): if i == 0 or i == 12: l_th.append( Styled_th(format(round(array_gene[j][idx], 2)) + ', ' + format(round(array_gene_2[j][idx], 2)) + ', ' + format(round(array_gene_3[j][idx], 2)), small=True)) else: l_th.append( Styled_th(format(round(array_gene[j][idx], 2)) + ', ' + format(round(array_gene_2[j][idx], 2)), small=True)) l_tr.append(l_th) table = html.Table([ html.Tr(l, style={'background-color': colorscale[5]}) if m == 0 else html.Tr(l) for m, l in enumerate(l_tr) ], style={ 'border-collapse': 'collapse', 'width': '100%' }) return fig_space, fig_time, fig_3D, table
def test_figure(filename, leny, robot): """Read a figure from a file and apply transformation so that it can be printed on the robot Parameters: -filename: The file in ST format -lenx: Scale the figure so that the width is equal to lenx -robot: The robot""" #-- Read the figure from a file f = fig.fromfile(filename) #-- Center the figure at origin (0,0) f.center() #-- Set the space resolution #f = f.divide(5) #-- Flip the y axis f.flipy() #-- Scale the figure so that it fits the robot printing area f.scale_fity(leny) #-- Translate the figure to the robot printing origin f.translate(robot.center) return f
def test_pol(): pol = [(32.324879, 901.84946), (210.111729, 106.06604), (-110.106629, 51.5178), (17.17259, 125.2589), (-142.43151, 4.0406), (-22.22335, -227.28434)] poly = fig.Figure(pol) poly.plot()
def draw(self, figure, ares=0): """Make the RoboDraw Draw the figure determined by the list of points""" #-- Transform the cartesian points into the angular space #-- by means of the inverse kinematics la = [(self.inverse_kin(p[0], p[1], 1)) for p in figure.lp] #-- Perform the sampling in the angular space angular_fig = fig.Figure(la).divide(ares) #-- Move the pencil up self.pen_up() time.sleep(0.400) #-- Move to the first position self.pose(angular_fig.lp[0][0], angular_fig.lp[0][1]) #-- Move down the pencil self.pen_down() time.sleep(0.400) #-- Send the positions to the robot! for alpha, beta in angular_fig.lp: self.pose(alpha, beta) #time.sleep(0.1) #-- extra time #-- Move the pencil up self.pen_up()
def test_save_st(filename): """Save a figure to the st format. Read it and display to test if the save_st method works""" #-- Create a box a = fig.box(40, 20).translate(r.center) #-- Subdivide into smaller points a = a.divide(5) a.plot() #--- Save the figure as a file a.save_st(filename) #-- Read the file b = fig.fromfile(filename) b.plot(True)
def test_save_st(filename): """Save a figure to the st format. Read it and display to test if the save_st method works""" #-- Create a box a = fig.box(40,20).translate(r.center) #-- Subdivide into smaller points a = a.divide(5) a.plot() #--- Save the figure as a file a.save_st(filename) #-- Read the file b = fig.fromfile(filename) b.plot(True)
def display_draw(self, figure, decimals=1, ares=0, display_points=False): """Draw the figure. It is drawn by means of the virtual robot (applying inverse kinematics to the points, and then the direct kinematics""" #-- Transform the cartesian points into the angular space #-- by means of the inverse kinematics la = [(self.inverse_kin(p[0], p[1], decimals)) for p in figure.lp] #-- Perform the sampling in the angular space angular_fig = fig.Figure(la).divide(ares) #-- Transform the angular space into cartesian again, by means #-- of the direct kinematics lc = [(self.kinematics(a[0], a[1])) for a in angular_fig.lp] #-- Create a new figure new_fig = fig.Figure(lc) #-- Plot! new_fig.plot(display_points)
def recursive_cube(r): rc = [] for l in range(40, 2, -1): a = fig.box(l, l).divide(2).translate(r.center) r.draw(a, ares=1.0) a.plot() #rc.extend(a.lp) #test = fig.Figure(rc) #test = test.divide(2) #test.plot() #test.save_c("rcube.h",r,"data","//-- Recursive cube") return
def recursive_cube(r): rc = [] for l in range(40,2,-1): a=fig.box(l,l).divide(2).translate(r.center) r.draw(a, ares=1.0) a.plot() #rc.extend(a.lp) #test = fig.Figure(rc) #test = test.divide(2) #test.plot() #test.save_c("rcube.h",r,"data","//-- Recursive cube") return
def test_save_c(filename, r, tablename="data",comments="//-- Figure (ext. degrees)"): """Save the figure as a c-table for including into the arduino files""" #-- Create a box a = fig.box(40,20).translate(r.center) #-- Subdivide into smaller points #a = a.divide(5) #a.plot(True) #--- Save the figure as a file a.save_c(filename,r,"data","//-- a Box. Resolution 5", ares=0.01)
def __init__(self,*filenames,**kwargs): """ Class to analyze the timing from a Futile run ------ Arguments filenames: list of the files which have to be treated plottype: Decide the default yscale for the plotting May be "Percent" or "Seconds" static: Show the plot statically for screenshot use fontsize: Determine fontsize of the bar chart plot nokey: Remove the visualization of the key from the main plot counter: retrieve as reference value the counter provided only_last: retrieve only the last document in the time.yaml """ #here a try-catch section should be added for multiple documents #if (len(filename) > 1 import Figures as Fig only_last = kwargs.get('only_last',False) self.log=[] for filename in filenames: import YamlIO as Yaml tmplogs=Yaml.load(filename,doc_lists=True) if only_last: self.log+=[[ a for a in tmplogs][-1]] else: self.log+=tmplogs #try: # self.log+=[yaml.load(open(filename, "r").read(), Loader = yaml.CLoader)] #except: # self.log+=yaml.load_all(open(filename, "r").read(), Loader = yaml.CLoader) #create the figure environemnt self.figures=Fig.FigureSet(title='Profiling',QuitButton=True,twinaxes=True) #self.barfig = None #self.axbars = None #self.newfigs =[] self.radio = None self.toggle_unbalancing = False self.quitButton = None self.lined=[] self.plot_start=kwargs.get('plottype','Seconds') self.static = kwargs.get('static',False) self.fontsize=kwargs.get('fontsize',15) self.nokey=kwargs.get('nokey',False) self.strong_scaling=kwargs.get('strong_scaling',True) counter=kwargs.get('counter','WFN_OPT') #the default value, to be customized if counter in self.counters(): self.inspect_counter(counter) else: print "Warning: counter not initialized, check the available counters"
def test_save_c(filename, r, tablename="data", comments="//-- Figure (ext. degrees)"): """Save the figure as a c-table for including into the arduino files""" #-- Create a box a = fig.box(40, 20).translate(r.center) #-- Subdivide into smaller points #a = a.divide(5) #a.plot(True) #--- Save the figure as a file a.save_c(filename, r, "data", "//-- a Box. Resolution 5", ares=0.01)
def make_graph(value_main_tab, value_analysis, gene_name): #, yaxis_type, yaxis_scale, data_type, value_tab): if gene_name is None or gene_name not in gene_data_atg: raise Exception() else: if value_main_tab == 'main-tab-2' and value_analysis == 'validation': data_atg = gene_data_atg[gene_name] data_itz = gene_data[gene_name] array_atg = np.nanmean(data_atg, axis=1) array_itz = np.nanmean(np.nanmean( [data_itz['rep1'], data_itz['rep2'], data_itz['rep3']], axis=0), axis=0) return Figures.compute_figure_polar_comparison( array_atg, array_itz) else: raise PreventUpdate
def check_for_pawn(self, x_from, y_from, x_to, y_to): if self.board.board[y_to][x_to] is None: end_figure = Figures.Figure("none") else: end_figure = self.board.board[y_to][x_to] if isinstance(self.board.board[y_from][x_from], Figures.Pawn): if self.board.board[y_from][x_from].color == "white": return self.white_pawn_first_move(x_from, y_from, x_to, y_to, end_figure) or \ self.white_pawn_common_move(x_from, y_from, x_to, y_to, end_figure) or \ self.white_pawn_en_passant(y_from, x_to) or \ self.check_for_pawn_strike(x_from, y_from, x_to, y_to) elif self.board.board[y_from][ x_from].color == "black": # same as white return self.black_pawn_first_move(x_from, y_from, x_to, y_to, end_figure) or \ self.black_pawn_common_move(x_from, y_from, x_to, y_to, end_figure) or \ self.black_pawn_en_passant(y_from, x_to) or \ self.check_for_pawn_strike(x_from, y_from, x_to, y_to) else: return False
def check_and_move(self, start, end): # does rule checking and figure movement x_from, y_from = start x_to, y_to = end if self.board.board[y_to][x_to] is None: end_figure = Figures.Figure( "none" ) # у NoneType нет атрибута color, поэтому создаем виртуальный else: end_figure = self.board.board[y_to][x_to] if self.board.board[y_from][x_from] is not None: #figures color checking if (self.board.board[y_from][x_from].color == self.turn) and \ (end_figure.color != self.board.board[y_from][x_from].color): #rules checking if self.is_able_to_go(x_from, y_from, x_to, y_to) or self.check_for_king( x_from, y_from, x_to, y_to): #movement checking for castle self.detect_first_move(x_from, y_from) start_figure = self.board.board[y_from][x_from] end_figure = self.board.board[y_to][x_to] #actual moving self.board.move_figure( self.board.convert_position_backwards(start), self.board.convert_position_backwards(end)) #acquiring new stricken cells self.find_hit_cells() #checking if king is in check, and if so, returning back to previous board state if self.is_current_king_in_check(): self.board.move_figure( self.board.convert_position_backwards(end), self.board.convert_position_backwards(start)) else: # check for pawns in last line and switch active player self.find_pawn_for_replace() if self.pawn_to_replace is not None: self.ask_for_figure() self.history.add_turn((x_from, y_from, x_to, y_to, start_figure, end_figure)) self.change_turn() self.find_hit_cells()
def vgrid_test(r): a = fig.vgrid(60, 20, 10).divide(2.0).translate(r.center) r.display_draw(a, ares=5.0, display_points=True) r.draw(a, ares=5.0)
show["figure1"]["show"] = dict() show["figure1"]["show"]["ff01"] = dict() show["figure1"]["show"]["ff01"]["data"] = [0] show["figure1"]["show"]["ff02"] = dict() show["figure1"]["show"]["ff02"]["data"] = [0] show["figure2"] = dict() show["figure2"]["xmax"] = 1000 show["figure2"]["show"] = dict() show["figure2"]["show"]["ff01"] = dict() show["figure2"]["show"]["ff01"]["data"] = [0] show["figure2"]["show"]["ff02"] = dict() show["figure2"]["show"]["ff02"]["data"] = [0] show_instance = Figures.FiguresInit("show", show) cnt = 0 def calc_rate(): global cnt show["figure1"]["show"]["ff01"]["data"].append(math.sin(cnt)) show["figure1"]["show"]["ff02"]["data"].append(math.cos(cnt)) show["figure2"]["show"]["ff01"]["data"].append(math.cos(cnt)) show["figure2"]["show"]["ff02"]["data"].append(math.sin(cnt)) cnt += 0.02 #print("*") rate_timer = threading.Timer(0.02, calc_rate) rate_timer.start()
def cube_test(r): """Draw a test cube""" a = fig.box(40, 25).divide(5.0).translate(r.center) r.display_draw(a, ares=5.0, display_points=True) r.draw(a, ares=5.0)
def run(self, weedings=[0,3,6,9]): """ Parameters ---------- weedings : TYPE, optional DESCRIPTION. The default time for weeding is [0,3,6,9] months. Returns ------- bal : TYPE DESCRIPTION Carbon balance for the run """ #************Read parametrs and create parameters instance******************* p=para.cParameters(pfile=self.parafile') nsteps = int((p.Gen['Lrotat'][0]*12 / p.Gen['dt'][0] +1) *p.Gen['Nrotat'][0]) # numbre of time steps in the simulation #***********Overwrite parameters if given in function call, can be disabled *********************************************** print (p.Gen['SI']) p.Gen['SI'][0]=self.si # overwrite site index if given in function call p.Gen['Mrate'][0]=self.Mrate p.Dec['peatRhoInit'][0]=self.rhoIni p.Dec['peatRhoFinal'][0]=self.rhoIni + p.Gen['Lrotat'][0]*p.Gen['Nrotat'][0]*3. #************Growth and yield************************** gy = gr.cGrowthAndYield(p.GY, p.Gen, p.Bi, p.Thin) # initialize growth and yoiel instance gy.weedings=weedings # overwrite weedings gy.calibrateBA = 1.0 rowGe = [0,0,0,0,0,0] # row in "General" sheet where the parameters are picked for # each rotation in simulation [0,1,2] would imply first rotation from first row, secon from secon row... rowGr = [0,0,0,0,0,0] # row in "Growth and yiueld" sheet where the parameters are picked for gy.fComputeGrowthAndYield(rowGe=rowGe, rowGr=rowGr) # calculation #************Hydrology and water tables *********************************** if self.optStripHy: dfStriphy=run_striphy(gy.Hdom, # domainat height array gy.LAI+gy.weedLAI, # total leaf area int(p.Gen['Lrotat'][0]), # length of roation, years optFig=self.DrawOpt) # option to draw hydrology figures #**********Decomposition of organic matter******************************************************* de = dec.DecomCWD(p.Gen, # initialize decomposition instance with parameters and growth and yield instance p.Dec, gy, p.N, p.P, p.K) # run coarse woody debris function de.decomCWD(gy.CWD, # CWD input gy.rowGe, # parameters dbh = gy.WMeanDiam.copy(), # mean stem diameter as time series rot = gy.rotationArr) # number of rotations in the simulation # initialize Romul: decomposition of stand and weed litter ro = dec.Romul(p.Dec, # parameters gy, # growth and yield instance with litter input de, # CWD instance p.N, # nutrient contents and other nutrient parameters p.P, p.K, test=False) # option to test the Romul model ro.decomRomul() # run Romul if self.optStripHy: # peat decomposition if hydrology is calculated pe = dec.DecomPeat(len(gy.CWD), # number of timesteps 1, # dt, time step lenth in months dwtArr=dfStriphy['gwl'].values*100.0) # array of water tables in cm pe.decomposePeat(p.Dec, # run peat decomposition, parameters gy, # litter inputs de, # CWD instance ro, # Romul instance optH=False, optCWD = True, optSine = False) # options else: # peat decomposition if water tables are exogeneous input dwtArr = np.random.normal(self.meanDwt, self.dwtAmp,nsteps) # generate monthly WTs pe = dec.DecomPeat(len(gy.CWD), # number of timesteps 1, # dt, length of timestep in months gwl=self.meanDwt, # given mean WT dwtAmp=self.dwtAmp, # given amplitude for WT dwtArr=dwtArr, # WT as array peatdatafile=self.peatdatafile) # datafile for peat hydraulic characteristics pe.decomposePeat(p.Dec, gy, de, ro, optH=False, optCWD = True, optSine = False) #********************************************************************************************************************************** if self.optNut == True: # calclucate nutrient balance print ('**********************') print ('NUTRIENT BALANCE') N = nut.cNutrient("Nitrogen", # initialize nutrient for nitrogen p.N, # N parameters p.Gen, # general parameters p.Fer, # fertilization ro) # litter (Romul) instance N.nutDemand(gy) # calculate N demand N.nutSupply(gy, de, pe) # calculate N supply P = nut.cNutrient("Phosphorus", p.P, p.Gen, p.Fer, ro) P.nutDemand(gy) P.nutSupply(gy, de, pe) K = nut.cNutrient("Potassium", p.K, p.Gen, p.Fer, ro) K.nutDemand(gy) K.nutSupply(gy, de, pe) #*****************Outputs************************************************************************* if self.DrawOpt== True: plt.close('all') if self.optNut == True: fgs.fDrawNutrient(N, gy, de) fgs.fDrawNutrient(P, gy, de) fgs.fDrawNutrient(K, gy, de) fgs.fDrawTreeNutBal(N,P,K, gy,de) fgs.fDrawDecomposition(gy, de, ro, pe) fgs.fDrawGrowth(gy) fgs.fDrawMAICAI(gy) fgs.drawCderivative(gy, de, ro, pe) if self.optNut==True: res.save_nbal(gy,pe,N,P,K,fold=self.fold) res.save_results(gy,de,ro,pe,N,P,K,fold=self.fold) _, bal, _ = res.C_balance(gy, de, ro, pe) above_stand = gy.BiBark + gy.BiBranch + gy.BiFoliage + gy.BiStem print ('********** Nutrients and biomass ************************') print (' Biom stand above', above_stand[-1], 'kg ha-1') print (' Biom weeds above', max(gy.weedAbove), 'kg ha-1') print (' Stand above N', (N.barkSto+N.branchSto+N.foliageSto+N.stemSto + N.rootSto)[-1]) print (' Stand above P', (P.barkSto+P.branchSto+P.foliageSto+P.stemSto + P.rootSto)[-1]) print (' Stand above K', (K.barkSto+K.branchSto+K.foliageSto+K.stemSto + K.rootSto)[-1]) print ('*********Litter inputs kg **************************************') print (' Root Litter', sum(gy.FineRLitL + gy.RootLitD)) print (' AG Litter', sum(gy.BrLitD + gy.BrLitL + gy.BaLitD + gy.BaLitL + gy.FoLitD + gy.FoLitL)) print (' Stemlitter', sum(gy.CWD)) print (' Weed litter', sum(gy.weedALitD + gy.weedALitL + gy.weedBLitD + gy.weedBLitL)) print ('********** Stand nutrient uptake kg ************************') print (' net N', sum(N.barkNet+N.branchNet+N.foliageNet+N.stemNet + N.rootNet)) print (' net P', sum(P.barkNet+P.branchNet+P.foliageNet+P.stemNet + P.rootNet)) print (' net K', sum(K.barkNet+K.branchNet+K.foliageNet+K.stemNet + K.rootNet)) print (' gross N', sum(N.barkGro+N.branchGro+N.foliageGro+N.stemGro + N.rootGro)) print (' gross P', sum(P.barkGro+P.branchGro+P.foliageGro+P.stemGro + P.rootGro)) print (' gross K', sum(K.barkGro+K.branchGro+K.foliageGro+K.stemGro + K.rootGro)) print ('********** Weed nutrient uptake kg ************************') print (' gross N', sum(N.weedAboveGro + N.weedBelowGro)) print (' gross P', sum(P.weedAboveGro + P.weedBelowGro)) print (' gross K', sum(K.weedAboveGro + K.weedBelowGro)) bals = res.C_balance(gy, de, ro, pe) sim_time_yrs = p.Gen['Lrotat'][0] * p.Gen['Nrotat'][0] print ('************ C balances kg ha-1 yr-1 **********************************') print (' Soil', bals[0]/sim_time_yrs ) print (' Stand without stems ', bals[1]/sim_time_yrs ) print (' Total', bals[2]/sim_time_yrs) print ('*********** Nutrient supply, N, P, K *********************') print (' Deposition', sum(N.deposition), sum(P.deposition), sum(K.deposition)) print (' Weathering', sum(N.weathering), sum(P.weathering),sum(K.weathering)) print (' Mic fixing', sum(N.fixing), sum(P.fixing),sum(K.fixing)) print (' Retranslocation', sum(N.retranslocation), sum(P.retranslocation),sum(K.retranslocation)) print (' Retranslocation weeds', sum(N.retranslocationWeeds), sum(P.retranslocationWeeds),sum(K.retranslocationWeeds)) print (' Release CWD', sum(N.releaseCwd), sum(P.releaseCwd),sum(K.releaseCwd)) print (' Release Peat', sum(N.releasePeat), sum(P.releasePeat),sum(K.releasePeat)) print (' Release Litter', sum(N.releaseLitter), sum(P.releaseLitter),sum(K.releaseLitter)) print (' Release fertilizers', sum(N.ferRel), sum(P.ferRel),sum(K.ferRel)) return bal
yc += y alp.append((xc, yc)) #-- Add the first point #alp.append(alp[0]) #-- Create the robot and set the connection r = Robot.Robot(l1 = 73.0, l2 = 97.0) r.test() r.connect("/dev/ttyUSB0") time.sleep(2) r.speed(100) #--- Create the figure with the absolute points! f = fig.Figure(alp) #-- Center the figure at origin (0,0) f.center() #-- Flip the y axis f.flipy() #f = f.divide(2) #-- Scale the figure so that it fits the robot printing area f.scale_fity(30) #-- Translate the figure to the robot printing origin f.translate(r.center)
def update_figure_fits(value_main_tab, value_analysis, gene_name): #, yaxis_type, yaxis_scale, value_tab ): if gene_name is None: raise Exception() else: if value_main_tab == 'main-tab-2' and value_analysis == 'spatiotemporal': array_gene_time = np.concatenate( (gene_data[gene_name]['rep1'], gene_data[gene_name]['rep2'], gene_data[gene_name]['rep3'][:, [0, 2]]), axis=1) fig_3D = Figures.compute_figure_3D_tab_3( dic_reg[gene_name], array_gene_time) #, yaxis_type, yaxis_scale) selected = dic_reg[gene_name][0] pv = dic_reg[gene_name][6] set_selected = set(selected) if len(selected) == 1: str_param = dash_katex.DashKatex( expression='\\text{ } \mu_0\\text{. }') str_param2 = 'This corresponds to the flat model.' else: str_param = dash_katex.DashKatex( expression='\\text{ }' + return_str_list_param(selected) + '\\text{. }') if set_selected == set( ['mu0', 'a0', 'b0']) or set_selected == set( ['mu0', 'a0']) or set_selected == set(['mu0', 'b0']): str_param2 = "This corresponds to the rhythmic model." elif 'a0' not in selected and 'a1' not in selected and 'a2' not in selected and 'b0' not in selected and 'b1' not in selected and 'b2' not in selected: if 'mu1' in selected or 'mu2' in selected: str_param2 = "This corresponds to the zonated model." else: str_param2 = "This corresponds to the rhythmic-zonated model." l_time_reg = [] for x in range(8): l_time_reg.append( LinearRegression.make_time_regression( array_gene_time[x, :], simple=False, predict=True)) fig_polar = Figures.compute_figure_polar_fit_tab_3( dic_reg[gene_name], l_time_reg) if fig_polar != None: return [ html.Div(children=[ html.P("Retained parameters: "), str_param, html.P(str_param2) ], style={ 'display': 'flex', 'justify-content': 'center' }), html.Div( children=[ dcc.Graph(id='graph-polar-fit', figure=fig_polar, config={ 'displayModeBar': False, 'modeBarButtonsToRemove': [], 'displaylogo': False }, style={'width': '25vw'}), dcc.Graph(id='graph-fit-3D', figure=fig_3D, config={ 'modeBarButtonsToRemove': [ 'sendDataToCloud', 'resetCameraLastSave3d', 'hoverClosest3d', 'zoom3d', 'toImage' ], 'displaylogo': False }, style={ 'border-width': '1px', 'border-style': 'solid', 'border-color': '#e8e8e8', 'width': '45vw' }) ], style={ 'display': 'flex', 'flex-direction': 'row', 'justify-content': 'space-between', 'height': '500px' }, ), ] else: return [ html.Div(children=[ html.P("Retained parameters: "), str_param, html.P(str_param2) ], style={ 'display': 'flex', 'justify-content': 'center' }), html.Div(children=[ dcc.Graph(id='graph-fit-3D', figure=fig_3D, config={ 'modeBarButtonsToRemove': [ 'sendDataToCloud', 'resetCameraLastSave3d', 'hoverClosest3d', 'zoom3d', 'toImage' ], 'displaylogo': False }, style={ 'border-width': '1px', 'border-style': 'solid', 'border-color': '#e8e8e8', 'width': '60vw' }) ], style={ 'display': 'flex', 'flex-direction': 'row', 'justify-content': 'space-around' }), ] else: raise PreventUpdate
total_words = sum(word_counts) chart_labels = [f'{name} ({msgs/total_words * 100: .1f}%)' for name, msgs in zip(names, word_counts)] chart_title = f'{total_words} Words Typed' Figures.create_pie_chart(chart_labels, message_counts, title=chart_title, fname="total_words_pie.pdf") # Create a pie chart of total characters sent logging.info('Creating a pie chart for the total characters sent in the group chat') char_counts = [person.char_count for person in PERSON_CONTAINER.persons.values()] total_chars = sum(char_counts) chart_labels = [f'{name} ({msgs/total_chars * 100: .1f}%)' for name, msgs in zip(names, char_counts)] chart_title = f'{total_chars} Characters Typed' Figures.create_pie_chart(chart_labels, message_counts, title=chart_title, fname="total_chars_pie.pdf") """ keywords = ['f**k', 'shit', 'damn', 'bitch', 'c**t', 'f*g', 'gay'] category = Figures.WordCategory('Swears', keywords) Figures.create_table(PERSON_CONTAINER, category) """ # Create a pie chart for swear words keywords = ['f**k', 'shit', 'damn', 'bitch', 'c**t', 'f*g', 'gay'] category = Figures.WordCategory('Swears', keywords) Figures.create_table() # Figures.create_word_category_charts(PERSON_CONTAINER, category) # Create a pie chart for racist words keywords = ['n***a', 'chink', 'spic', 'nigger', 'cracker', 'wetback', 'white', 'black'] category = Figures.WordCategory('Racist Words', keywords) Figures.create_word_category_charts(PERSON_CONTAINER, category) # Create a pie chart for weird words
def update_figure_polar(value, value_main_tab, value_analysis, gene_name): if gene_name is None: raise Exception() else: if value_main_tab == 'main-tab-2' and value_analysis == 'temporal': array_gene_time = np.concatenate( (gene_data[gene_name]['rep1'], gene_data[gene_name]['rep2'], gene_data[gene_name]['rep3'][:, [0, 2]]), axis=1) l_time_reg = [] for x in range(8): l_time_reg.append( LinearRegression.make_time_regression( array_gene_time[x, :], simple=False, predict=True)) l_time_reg_simple = [] for x in range(8): l_time_reg_simple.append( LinearRegression.make_time_regression( array_gene_time[x, :], simple=True, predict=False)) #correct value value = int(value) - 1 B, SE, adj_r2, aic, bic, pv, X_pred, Y_pred = l_time_reg[value] [mu_1, a_1, b_1] = B.flatten() [std_mu_1, std_a_1, std_b_1] = np.diagonal(SE) bic_1 = bic aic_1 = aic r2_1 = adj_r2 B_simple, SE_simple, adj_r2_simple, aic_simple, bic_simple, pv_simple = l_time_reg_simple[ value] [mu_2] = B_simple.flatten() [std_mu_2] = np.diagonal(SE_simple) bic_2 = bic_simple aic_2 = aic_simple r2_2 = adj_r2_simple table_model_1 = html.Table([ html.Tr([ Styled_th('Parameter'), Styled_th('Mean'), Styled_th('SE') ], style={'background-color': colorscale[5]}), html.Tr([ Styled_th(dash_katex.DashKatex(expression='\mu'), {'background-color': colorscale[5]}), Styled_th('{:.2e}'.format(mu_1)), Styled_th('{:.2e}'.format(std_mu_1)) ]), html.Tr([ Styled_th(dash_katex.DashKatex(expression='a'), {'background-color': colorscale[5]}), Styled_th('{:.2e}'.format(a_1)), Styled_th('{:.2e}'.format(std_a_1)) ]), html.Tr([ Styled_th(dash_katex.DashKatex(expression='b'), {'background-color': colorscale[5]}), Styled_th('{:.2e}'.format(b_1)), Styled_th('{:.2e}'.format(std_b_1)) ]) ]) table_model_2 = html.Table([ html.Tr([ Styled_th('Parameter'), Styled_th('Mean'), Styled_th('SE') ], style={'background-color': colorscale[5]}), html.Tr([ Styled_th(dash_katex.DashKatex(expression='\mu'), {'background-color': colorscale[5]}), Styled_th('{:.2e}'.format(mu_2)), Styled_th('{:.2e}'.format(std_mu_2)) ]) ]) table_comparison = html.Table([ html.Tr([ Styled_th('Model'), Styled_th('BIC'), Styled_th('AIC'), Styled_th( dash_katex.DashKatex(expression='\\text{Adj. } R^2')) ], style={'background-color': colorscale[5]}), html.Tr([ Styled_th('Intercept-only', {'background-color': colorscale[5]}), Styled_th('{:.2e}'.format(bic_2)), Styled_th('{:.2e}'.format(aic_2)), Styled_th('{:.2e}'.format(r2_2)) ]), html.Tr([ Styled_th('Oscillatory', {'background-color': colorscale[5]}), Styled_th('{:.2e}'.format(bic_1)), Styled_th('{:.2e}'.format(aic_1)), Styled_th('{:.2e}'.format(r2_1)) ]) ]) time_domain = np.concatenate( (np.linspace(0, 24, 4, endpoint=False), np.linspace(0, 24, 4, endpoint=False), np.linspace(0, 24, 2, endpoint=False))) x = int(value) B, SE, adj_r2, aic, bic, pv, X_pred, Y_pred = l_time_reg[x] figure = Figures.compute_figure_time_tab_3( time_domain, array_gene_time[x, :], X_pred, Y_pred) #, yaxis_type, yaxis_scale) return [ html.Div(children=[ html.Div(children=[ html.H6('Intercept-only model', style={'textAlign': 'center'}), table_model_2 ]), html.Div(children=[ html.H6('Oscillatory model', style={'textAlign': 'center'}), table_model_1 ]), html.Div(children=[ html.H6('Models comparison', style={'textAlign': 'center'}), table_comparison, html. P('P-value associated with the oscillatory model (ANOVA): ' + str(pv)) ], style={ 'display': 'flex', 'flex-direction': 'column' }), ], style={ 'display': 'flex', 'flex-direction': 'row', 'justify-content': 'space-around', 'flex-wrap': 'wrap', 'flex-align': 'baseline' }), dcc.Graph(id='graph-stat-time', figure=figure, config={ 'displayModeBar': False, 'modeBarButtonsToRemove': [], 'displaylogo': False }, style={'width': '60vw'}) ] else: raise PreventUpdate
def cube_test(r): """Draw a test cube""" a=fig.box(40,25).divide(5.0).translate(r.center) r.display_draw(a, ares=5.0, display_points=True) r.draw(a,ares=5.0)
def update_figure_fits(value, value_main_tab, value_analysis, gene_name): #yaxis_type, yaxis_scale, value_tab ): if gene_name is None: raise Exception() else: if value_main_tab == 'main-tab-2' and value_analysis == 'spatial': #correct value value = int(value) - 1 t = int(value) array_gene_space = np.concatenate( (gene_data[gene_name]['rep1'], gene_data[gene_name]['rep2'], gene_data[gene_name]['rep3']), axis=0) if t == 0 or t == 2: selected, B, SE, adj_r2, aic, bic, pv, X_pred, Y_pred = LinearRegression.make_space_regression( array_gene_space[:, t], predict=True) else: selected, B, SE, adj_r2, aic, bic, pv, X_pred, Y_pred = LinearRegression.make_space_regression( array_gene_space[:16, t], predict=True) if len(selected) == 1: str_param = dash_katex.DashKatex(id='katex_a0', expression=' \mu_0') else: str_param = dash_katex.DashKatex( id='katex_other_parameters', expression=return_str_list_param(selected)) space_domain = np.concatenate( (np.linspace(0, 8, 8, endpoint=False), np.linspace(0, 8, 8, endpoint=False), np.linspace(0, 8, 8, endpoint=False))) if t == 0 or t == 2: figure = Figures.compute_figure_space_tab_3( space_domain, array_gene_space[:, t], X_pred, Y_pred) #, yaxis_type, yaxis_scale) else: figure = Figures.compute_figure_space_tab_3( space_domain[:16], array_gene_space[:16, t], X_pred, Y_pred) #, yaxis_type, yaxis_scale) return [ html.Div(children=[ html.P('Retained parameters: '), html.Div(style={'width': '5px'}), str_param ], style={ 'display': 'flex', 'justify-content': 'center' }), dcc.Graph(id='graph-stat-space', figure=figure, config={ 'displayModeBar': False, 'modeBarButtonsToRemove': [], 'displaylogo': False }, style={'width': '60vw'}) ] else: raise PreventUpdate
def vgrid_test(r): a = fig.vgrid(60,20,10).divide(2.0).translate(r.center) r.display_draw(a, ares=5.0, display_points=True) r.draw(a,ares=5.0)
def __init__(self, *args): if args == (): self['a2'] = Figures.Pawn("white") self['b2'] = Figures.Pawn("white") self['c2'] = Figures.Pawn("white") self['d2'] = Figures.Pawn("white") self['e2'] = Figures.Pawn("white") self['f2'] = Figures.Pawn("white") self['g2'] = Figures.Pawn("white") self['h2'] = Figures.Pawn("white") self['a1'] = Figures.Tower("white") self['b1'] = Figures.Knight("white") self['c1'] = Figures.Bishop("white") self['d1'] = Figures.Queen("white") self['e1'] = Figures.King("white") self['f1'] = Figures.Bishop("white") self['g1'] = Figures.Knight("white") self['h1'] = Figures.Tower("white") self['a8'] = Figures.Tower("black") self['b8'] = Figures.Knight("black") self['c8'] = Figures.Bishop("black") self['d8'] = Figures.Queen("black") self['e8'] = Figures.King("black") self['f8'] = Figures.Bishop("black") self['g8'] = Figures.Knight("black") self['h8'] = Figures.Tower("black") self['a7'] = Figures.Pawn("black") self['b7'] = Figures.Pawn("black") self['c7'] = Figures.Pawn("black") self['d7'] = Figures.Pawn("black") self['e7'] = Figures.Pawn("black") self['f7'] = Figures.Pawn("black") self['g7'] = Figures.Pawn("black") self['h7'] = Figures.Pawn("black")