def reDraw(self): self.delete("all") self.create_rectangle(self.border, self.border, GAME_SIZE - self.border, GAME_SIZE - self.border, fill='misty rose', outline='misty rose') if self.victory: self['bg'] = 'pale green' else: self['bg'] = 'gray90' for key, stick in self.sticks.items(): val = stick[2] stick_col_rgb = utils.shift_hue(BASE_COL, BASE_DELTA * (val - 1)) stick_col_hex = utils.rgb_to_hex(stick_col_rgb) if key in self.collided: col = 'black' elif self._tag == key: stick_col_rgb = utils.scale_brightness(stick_col_rgb, BASE_SCALE) col = utils.rgb_to_hex(stick_col_rgb) else: col = stick_col_hex self.drawStick(stick, key, col=col)
def plot_line(self, line): """ Decides, for each line, how we're going to plot, normal or with intensities """ if line.plot_line: if not WorldState.Instance().session_dict['normalised']: if not line.intense_plot: self.axes.plot(line.original_time, line.original_results, label=line.species, color=rgb_to_hex(line.rgb_tuple), alpha=1, lw=line.thickness) else: for (sub_plot, new_colour) in line.sub_plot_tuples: self.axes.plot(line.interpolated_time, sub_plot, color=new_colour, lw=line.thickness) else: if not line.intense_plot: self.axes.plot(line.original_time, line.normalised_results, label=line.species, color=rgb_to_hex(line.rgb_tuple), alpha=1, lw=line.thickness) else: for (sub_plot, new_colour) in line.normalised_sub_plots: self.axes.plot(line.interpolated_time, sub_plot, color=new_colour, lw=line.thickness)
def by_hex(color_name) -> 'html': # extract RGB r, g, b = utils.hex_to_rgb(color_name) # msg = 'Color: #{}; RGB({}, {}, {}); '.format(color_name, r, g, b) # make a sorted array cp_colors = copy.copy(tikkurila_colors.COLORS) for clr in cp_colors: clr[4] = abs(clr[0] - r) + abs(clr[1] - g) + abs(clr[2] - b) # sort from operator import itemgetter cp_colors.sort(key=itemgetter(4)) # hsl h, l, s = colorsys.rgb_to_hls(r, g, b) msg += 'HLS: {0:.3f}, {1:.3f}, {2:.3f}.'.format(h, l, s) # result return render_template( 'color_by_hex.html', the_title=TITLE, the_note='', the_result='', the_name_color0=msg, the_color0=utils.rgb_to_hex(r, g, b), the_color1=utils.rgb_to_hex(cp_colors[0][0], cp_colors[0][1], cp_colors[0][2]), the_color2=utils.rgb_to_hex(cp_colors[1][0], cp_colors[1][1], cp_colors[1][2]), the_color3=utils.rgb_to_hex(cp_colors[2][0], cp_colors[2][1], cp_colors[2][2]), the_name_color1=cp_colors[0][3], the_name_color2=cp_colors[1][3], the_name_color3=cp_colors[2][3], )
def __init__(self, results, time, csv, key, colour, graph_width, graph_height, xmin, xmax, ymin, ymax): self.results = results self.original_results = results self.interpolated_results = [] self.normalised_results = [] self.original_time = time self.interpolated_time = [] self.horizontal_scale = float(xmax - xmin) / graph_width self.vertical_scale = float(ymax - ymin) / graph_height self.length = self.calc_line_length(self.results, time) self.guide_points = 1000 self.min = 0 self.max = 0 self.species = key self.plot_line = True self.intense_plot = False self.interpolated_results, self.interpolated_time = self.interpolate( self.results, time) self.interval = len(self.interpolated_results) / 100 self.rgb_tuple = colour self.flat_colour = rgb_to_hex(colour) self.thickness = 2 self.colour_change_points = [] self.seg_colour = None self.sub_plot_tuples = self.plot_sub_plots(self.interpolated_results, self.interval) self.past_points = [] self.counter = 0 self.normalised_sub_plots = [] self.normalise() self.sub_lists = self.slice_lists(self.interpolated_results) self.debug_name = "Begin"
def __init__(self, results, time, csv, key, colour, graph_width, graph_height, xmin, xmax, ymin, ymax): self.results = results self.original_results = results self.interpolated_results = [] self.normalised_results = [] self.original_time = time self.interpolated_time = [] self.horizontal_scale = float(xmax - xmin) / graph_width self.vertical_scale = float(ymax - ymin) / graph_height self.length = self.calc_line_length(self.results, time) self.guide_points = 1000 self.min = 0 self.max = 0 self.species = key self.plot_line = True self.intense_plot = False self.interpolated_results, self.interpolated_time = self.interpolate(self.results, time) self.interval = len(self.interpolated_results)/100 self.rgb_tuple = colour self.flat_colour = rgb_to_hex(colour) self.thickness = 2 self.colour_change_points = [] self.seg_colour = None self.sub_plot_tuples = self.plot_sub_plots(self.interpolated_results, self.interval) self.past_points = [] self.counter = 0 self.normalised_sub_plots = [] self.normalise() self.sub_lists = self.slice_lists(self.interpolated_results) self.debug_name = "Begin"
def plot_sub_plots(self, results, interval, debug=False): """ Plots the sub plots and works out what colour the line should be this is for colour intensity plot """ sub_plots = self.build_colour_plot_arrays(results, interval) sub_plot_tuples = [] self.colour_change_points = [] for sub_plot in sub_plots: count = 0 current = 0 while True: if (sub_plot[count] is not None): current = sub_plot[count] break count += 1 intensity = (( (current - self.min) / float(1 + self.max - self.min)) * (_MAX_INTENSITY - _MIN_INTENSITY)) + _MIN_INTENSITY alpha = intensity / 255 new_colour = rgb_to_hex(rgba_to_rgb(self.rgb_tuple, alpha)) self.colour_change_points.append((count, new_colour)) sub_plot_tuples.append((sub_plot, new_colour)) self.seg_colour = self.colour_change_points[0][1] return sub_plot_tuples
def choose_background_color(self): color = colorchooser.askcolor() if color[1]: State.background_color = color[1] State.linenumbering_color = rgb_to_hex( [int(abs(i - 30)) for i in color[0]]) self.frame_color.body_color_label.config( text=f'Background color: {State.background_color}')
def draw_stuff(stuff, fill): outline = outline_color if not (outline_color_delta is None or fill is None): outline = gr.offset_color(fill, outline_color_delta) if not fill is None: fill = u.rgb_to_hex(*fill) if not outline is None: outline = u.rgb_to_hex(*outline) if isinstance(stuff, gr.Polygon): canvas.draw_polygon(stuff, fill, outline) if do_svg: svg_canvas.draw_polygon(stuff, fill=fill, stroke=outline) elif isinstance(stuff, gr.Circle): canvas.draw_circle(stuff, fill, outline) if do_svg: svg_canvas.draw_circle(stuff, fill=fill, stroke=outline)
async def role_info(self, ctx: utils.CustomContext, *roles: Role): """Get information on a given role.""" embed_list = [] for role in roles: role_perms = [] permissions_dict = { "kick_members": "Kick Members", "ban_members": "Ban Members", "administrator": "Administrator", "manage_channels": "Manage Channels", "manage_guild": "Manage Server", "manage_messages": "Manage Messages", "mention_everyone": "Mention Everyone", "mute_members": "Mute Members (VC)", "deafen_members": "Deafen Members (VC)", "move_members": "Move Members (VC)", "manage_nicknames": "Manage Nicknames", "manage_roles": "Manage Roles" } permissions = dict(role.permissions) for permission, true_false in permissions.items(): if true_false is True: if (perm := permissions_dict.get(str(permission))) is not None: role_perms.append(f"✅ {perm}") repr_permissions = '\n'.join(role_perms) created_at_str = f"{role.created_at.day}/{role.created_at.month}/{role.created_at.year} {role.created_at.hour}:{role.created_at.minute}:{role.created_at.second}" role_colour = (role.colour.r, role.colour.g, role.colour.b) fields = [ ["Name", role.name, True], ["Mention", f"`{role.mention}`", True], ["Created At", created_at_str, True], ["Role Position", role.position, True], ["Hoisted", role.hoist, True], ["Mentionable", role.mentionable, True], ["Colour", utils.rgb_to_hex(role_colour), True], ["Members", sum(1 for member in role.members), True], [ "Permissions", f"```\n{repr_permissions or 'Nothing special.'}```", False ], ] embed = self.bot.embed(ctx, colour=discord.Color.from_rgb(*role_colour)) [embed.add_field(name=n, value=v, inline=i) for n, v, i in fields] embed_list.append(embed)
def plot_subtitle(ax, text, fs, cfg): """ Add a title. """ color = utils.rgb_to_hex(cfg['highlight_colour']) x = 1.0 if cfg['sidelabel'] == 'right' else 0.0 ax.text(x, -0.15, text, size=fs, ha=cfg['sidelabel'], va='top', color=color, ) ax.axis('off') return ax
def by_name(color_name) -> 'html': color = tikkurila_colors.color_by_name(color_name) if color: msg = 'Name "{}"; HEX: {}; RGB({}, {}, {})'.format( color[3], utils.rgb_to_hex(color[0], color[1], color[2]), color[0], color[1], color[2]) return render_template( 'color_by_name.html', the_title=TITLE, the_note='', the_result='', the_name_color0=msg, the_color0=utils.rgb_to_hex(color[0], color[1], color[2]), ) else: msg = 'Color "{}" not found.'.format(color_name.upper()) return render_template( 'color.html', the_title=TITLE, the_note=color, the_result=msg, )
def plot_title(ax, text, fs, cfg): """ Add a title. """ x = 1.0 if cfg['sidelabel'] == 'right' else 0.0 color = utils.rgb_to_hex(cfg['highlight_colour']) ax.text( x, 0.0, text, size=fs, ha=cfg['sidelabel'], va='bottom', color=color, ) ax.axis('off') return ax
def hueNormalizer(pathwaydict): #Input: #Processes: #Output: #Initialize variables: #Variables initialized. huesToBeNormalized = [] l = pathwaydict.keys() keysToBeNormalized = fnmatch.filter(l, "*normalizedavg") print("The keys being looked at are: ", keysToBeNormalized) for keys in range(len(keysToBeNormalized)): huesToBeNormalized.append(pathwaydict[keysToBeNormalized[keys]]) print("The huesToBeNormalized are: ", huesToBeNormalized) largestavg = max(huesToBeNormalized) smallestavg = min(huesToBeNormalized) print("The largest hue avg is: ", largestavg, " and the smallest is: ", smallestavg) for entry in range(len(huesToBeNormalized)): print( "The node being looked at is: ", keysToBeNormalized[entry].replace("normalizedavg", "normalizedhueavg")) print("The huesToBeNormalizedp[entry] is: ", huesToBeNormalized[entry]) pathwaydict[keysToBeNormalized[entry].replace( "normalizedavg", "normalizedhueavg")] = (huesToBeNormalized[entry] - smallestavg) / (largestavg - smallestavg) #print("The hue pre-processing values are: ", pathwaydict[keysToBeNormalized[entry].replace("normalizedavg","normalizedhueavg")], "and ints they are: ", int(255-(255*pathwaydict[keysToBeNormalized[entry].replace("normalizedavg","normalizedhueavg")]))) #DB pathwaydict[keysToBeNormalized[entry].replace( "normalizedavg", "huevalue")] = rgb_to_hex( 255, int(255 - (255 * pathwaydict[keysToBeNormalized[entry].replace( "normalizedavg", "normalizedhueavg")])), int(255 - (255 * pathwaydict[keysToBeNormalized[entry].replace( "normalizedavg", "normalizedhueavg")]))) return pathwaydict
def on_ok(self, e): """ Update the line to values from ui elements """ self.line.plot_line = self.cb_show_hide.GetValue() self.line.intense_plot = self.cb_intense.GetValue() self.line.thickness = self.thick_spin.GetValue() try: (r, g, b) = self.colour_picker.GetColour().Get() self.line.rgb_tuple = (r, g, b) self.line.flat_colour = rgb_to_hex((r, g, b)) self.line.sub_plot_tuples = self.line.plot_sub_plots(self.line.interpolated_results, self.line.interval, debug=False) self.line.normalise() self.line.debug_name = "Finish" except: print "No colour change" WorldState.Instance().lamport_clock += 1 WorldState.Instance().push_state() WorldState.Instance().reorder(WorldState.Instance().lamport_clock) WorldState.Instance().refresh_animation() self.Close()
def plot_sub_plots(self, results, interval, debug=False): """ Plots the sub plots and works out what colour the line should be this is for colour intensity plot """ sub_plots = self.build_colour_plot_arrays(results, interval) sub_plot_tuples = [] self.colour_change_points = [] for sub_plot in sub_plots: count = 0 current = 0 while True: if (sub_plot[count] is not None): current = sub_plot[count] break count += 1 intensity = (((current - self.min) / float(1 + self.max - self.min)) * (_MAX_INTENSITY - _MIN_INTENSITY)) + _MIN_INTENSITY alpha = intensity/255 new_colour = rgb_to_hex(rgba_to_rgb(self.rgb_tuple, alpha)) self.colour_change_points.append((count, new_colour)) sub_plot_tuples.append((sub_plot, new_colour)) self.seg_colour = self.colour_change_points[0][1] return sub_plot_tuples
def main(target, cfg): """ Puts everything together. """ t0 = time.time() ##################################################################### # # READ SEGY # ##################################################################### if cfg['segy_library'].lower() == 'obspy': s = Seismic.from_segy_with_obspy(target, params={'ndim': cfg['ndim']}) else: s = Seismic.from_segy(target, params={'ndim': cfg['ndim']}) # Set the line and/or xline number. try: n, xl = cfg['number'] except: n, xl = cfg['number'], 0.5 # Set the direction. if (s.ndim) == 2: direction = ['inline'] elif cfg['direction'].lower()[0] == 'i': direction = ['inline'] elif cfg['direction'].lower()[0] in ['x', 'c']: # Allow 'crossline' too. direction = ['xline'] elif cfg['direction'].lower()[0] == 't': direction = ['tslice'] else: direction = ['xline', 'inline'] # Get the data. try: ss = [ Seismic.from_seismic(s, n=n, direction=d) for n, d in zip((n, xl), direction) ] except IndexError: # Perhaps misinterpreted 2D as 3D s = Seismic.from_segy(target, params={'ndim': 2}) direction = ['inline'] ss = [ Seismic.from_seismic(s, n=n, direction=d) for n, d in zip((n, xl), direction) ] clip_val = np.percentile(s.data, cfg['percentile']) if clip_val < 10: fstr = '{:.3f}' elif clip_val < 100: fstr = '{:.2f}' elif clip_val < 1000: fstr = '{:.1f}' else: fstr = '{:.0f}' # Notify user of parameters. Notice.info("n_traces {}".format(s.ntraces)) Notice.info("n_samples {}".format(s.nsamples)) Notice.info("dt {}".format(s.dt)) Notice.info("t_start {}".format(s.tstart)) Notice.info("t_end {}".format(s.tend)) Notice.info("max_val " + fstr.format(np.amax(s.data))) Notice.info("min_val " + fstr.format(np.amin(s.data))) Notice.info("clip_val " + fstr.format(clip_val)) t1 = time.time() Notice.ok("Read data in {:.1f} s".format(t1 - t0)) ##################################################################### # # MAKE PLOT # ##################################################################### Notice.hr_header("Plotting") # Plot size parameters. wsl = 6 # Width of sidelabel, inches mih = 11 # Minimum plot height, inches fhh = 5 # File header box height, inches m = 0.75 # basic unit of margins, inches # Margins, CSS like: top, right, bottom, left. mt, mr, mb, ml = m, 1.5 * m, m, 1.5 * m mm = 2 * m # padded margin between seismic and label # Determine plot dimensions. Kind of laborious and repetitive (see below). if cfg['plot_width']: seismic_width = cfg['plot_width'] - wsl - mm - ml - mr tpi = max([s.ntraces for s in ss]) / seismic_width else: tpi = cfg['tpi'] if cfg['plot_height']: seismic_height = max( mih, cfg['plot_height']) - mb - 0.75 * (len(ss) - 1) - mt seismic_height_raw = seismic_height / len(ss) ips = seismic_height_raw / (s.tbasis[-1] - s.tbasis[0]) else: ips = cfg['ips'] # Width is determined by seismic width, plus sidelabel, plus margins. # Height is given by ips, but with a minimum of mih inches. if 'tslice' in direction: seismic_width = [s.ntraces / tpi for s in ss] seismic_height_raw = max([s.nxlines for s in ss]) / tpi else: seismic_width = [s.ntraces / tpi for s in ss] seismic_height_raw = ips * (s.tbasis[-1] - s.tbasis[0]) w = ml + max(seismic_width) + mm + wsl + mr # inches seismic_height = len(ss) * seismic_height_raw h_reqd = mb + seismic_height + 0.75 * (len(ss) - 1) + mt # inches h = max(mih, h_reqd) # Calculate where to start sidelabel and seismic data. # Depends on whether sidelabel is on the left or right. if cfg['sidelabel'] == 'right': ssl = (ml + max(seismic_width) + mm) / w # Start of side label (ratio) seismic_left = ml / w else: ssl = ml / w seismic_left = (ml + wsl + mm) / w adj = max(0, h - h_reqd) / 2 seismic_bottom = (mb / h) + adj / h seismic_width_fraction = [sw / w for sw in seismic_width] seismic_height_fraction = seismic_height_raw / h # Publish some notices so user knows plot size. Notice.info("plot width {:.2f} in".format(w)) Notice.info("plot height {:.2f} in".format(h)) # Make the figure. fig = plt.figure(figsize=(w, h), facecolor='w') # Set the tickformat. tickfmt = mtick.FormatStrFormatter('%.0f') # Could definitely do better for default fontsize than 10. # Ideally would be adaptive to plot size. cfg['fontsize'] = cfg['fontsize'] or 10 # Plot title. if cfg['title']: # Deal with Windows paths: \1 gets interpreted as a group by regex. newt = re.sub(r'\\', '@@@@@', target) temp = re.sub(r'_filename', newt, cfg['title']) title = re.sub(r'@@@', r'\\', temp) title_ax = fig.add_axes([ssl, 1 - mt / h, wsl / w, mt / h]) title_ax = plotter.plot_title(title_ax, title, fs=1.4 * cfg['fontsize'], cfg=cfg) # Plot title. if cfg['subtitle']: date = str(datetime.date.today()) subtitle = re.sub(r'_date', date, cfg['subtitle']) subtitle_ax = fig.add_axes([ssl, 1 - mt / h, wsl / w, mt / h], label='subtitle') title_ax = plotter.plot_subtitle(subtitle_ax, subtitle, fs=0.75 * cfg['fontsize'], cfg=cfg) # Plot text header. start = (h - 1.5 * mt - fhh) / h head_ax = fig.add_axes([ssl, start, wsl / w, fhh / h]) head_ax = plotter.plot_header(head_ax, s.header, fs=9, cfg=cfg, version=__version__) # Plot histogram. # Params for histogram plot. pady = 0.75 / h # 0.75 inch padx = 0.75 / w # 0.75 inch cstrip = 0.3 / h # color_strip height = 0.3 in charth = 1.25 / h # height of charts = 1.25 in chartw = wsl / w - mr / w - padx # or ml/w for left-hand sidelabel; same thing chartx = (ssl + padx) histy = 1.5 * mb / h + charth + pady # Plot colourbar under histogram. clrbar_ax = fig.add_axes([chartx, histy - cstrip, chartw, cstrip]) clrbar_ax = plotter.plot_colourbar(clrbar_ax, cmap=cfg['cmap']) # Plot histogram itself. hist_ax = fig.add_axes([chartx, histy, chartw, charth]) hist_ax = plotter.plot_histogram(hist_ax, s.data, tickfmt, cfg) # Plot spectrum. specy = 1.5 * mb / h spec_ax = fig.add_axes([chartx, specy, chartw, charth]) try: colour = utils.rgb_to_hex(cfg['highlight_colour']) spec_ax = s.plot_spectrum( ax=spec_ax, tickfmt=tickfmt, ntraces=20, fontsize=cfg['fontsize'], colour=colour, ) except: pass # No spectrum, oh well. for i, line in enumerate(ss): # Add the seismic axis. ax = fig.add_axes([ seismic_left, seismic_bottom + i * seismic_height_fraction + i * pady, seismic_width_fraction[i], seismic_height_fraction ]) # Plot seismic data. if cfg['display'].lower() in ['vd', 'varden', 'variable', 'both']: im = ax.imshow(line.data.T, cmap=cfg['cmap'], clim=[-clip_val, clip_val], extent=[ line.olineidx[0], line.olineidx[-1], 1000 * line.tbasis[-1], line.tbasis[0] ], aspect='auto', interpolation=cfg['interpolation']) if np.argmin(seismic_width) == i: cax = utils.add_subplot_axes(ax, [1.01, 0.02, 0.01, 0.2]) _ = plt.colorbar(im, cax=cax) if cfg['display'].lower() in ['wiggle', 'both']: ax = line.wiggle_plot( cfg['number'], direction, ax=ax, skip=cfg['skip'], gain=cfg['gain'], rgb=cfg['colour'], alpha=cfg['opacity'], lw=cfg['lineweight'], ) valid = ['vd', 'varden', 'variable', 'wiggle', 'both'] if cfg['display'].lower() not in valid: Notice.fail("You must specify the display: wiggle, vd, both.") return # Seismic axis annotations. ax.set_ylabel(utils.LABELS[line.ylabel], fontsize=cfg['fontsize']) ax.set_xlabel(utils.LABELS[line.xlabel], fontsize=cfg['fontsize'], ha='center') ax.tick_params(axis='both', labelsize=cfg['fontsize'] - 2) ax.xaxis.set_major_formatter(tickfmt) ax.yaxis.set_major_formatter(tickfmt) if ('tslice' not in direction): ax.set_ylim(1000 * cfg['trange'][1] or 1000 * line.tbasis[-1], 1000 * cfg['trange'][0]) # Crossing point. Will only work for non-arb lines. try: ax.axvline(ss[i - 1].slineidx[0], c=utils.rgb_to_hex(cfg['highlight_colour']), alpha=0.5) except IndexError: pass # Nevermind. # Grid, optional. if cfg['grid_time'] or cfg['grid_traces']: ax.grid() for l in ax.get_xgridlines(): l.set_color(utils.rgb_to_hex(cfg['grid_colour'])) l.set_linestyle('-') if cfg['grid_traces']: l.set_linewidth(1) else: l.set_linewidth(0) l.set_alpha(min(1, cfg['grid_alpha'])) for l in ax.get_ygridlines(): l.set_color(utils.rgb_to_hex(cfg['grid_colour'])) l.set_linestyle('-') if cfg['grid_time']: if 'tslice' in direction: l.set_linewidth(1) else: l.set_linewidth(1.4) else: l.set_linewidth(0) l.set_alpha(min(1, 2 * cfg['grid_alpha'])) # Watermark. if cfg['watermark_text']: ax = plotter.watermark_seismic(ax, cfg) # Make parasitic (top) axis for labeling CDP number. if (s.data.ndim > 2) and ('tslice' not in direction): ylim = ax.get_ylim() par1 = ax.twiny() par1.spines["top"].set_position(("axes", 1.0)) par1.plot(line.slineidx, np.zeros_like(line.slineidx), alpha=0) par1.set_xlabel(utils.LABELS[line.slabel], fontsize=cfg['fontsize']) par1.set_ylim(ylim) # Adjust ticks tx = par1.get_xticks() newtx = [ line.slineidx[len(line.slineidx) * (i // len(tx))] for i, _ in enumerate(tx) ] par1.set_xticklabels(newtx, fontsize=cfg['fontsize'] - 2) t2 = time.time() Notice.ok("Built plot in {:.1f} s".format(t2 - t1)) ##################################################################### # # SAVE FILE # ##################################################################### Notice.hr_header("Saving") dname, fname, ext = utils.path_bits(target) outfile = cfg['outfile'] or '' if not os.path.splitext(outfile)[1]: outfile = os.path.join(cfg['outfile'] or dname, fname + '.png') fig.savefig(outfile) t3 = time.time() Notice.info("output file {}".format(outfile)) Notice.ok("Saved output in {:.1f} s".format(t3 - t2)) if cfg['stain_paper'] or cfg['coffee_rings'] or cfg['distort'] or cfg[ 'scribble']: fname = os.path.splitext(outfile)[0] + ".stupid.png" fig.savefig(fname) else: return ##################################################################### # # SAVE STUPID FILE # ##################################################################### Notice.hr_header("Applying the stupidity") stupid_image = Image.open(fname) if cfg['stain_paper']: utils.stain_paper(stupid_image) utils.add_rings(stupid_image, cfg['coffee_rings']) if cfg['scribble']: utils.add_scribble(stupid_image) # Trick to remove remaining semi-transparent pixels. result = Image.new("RGB", stupid_image.size, (255, 255, 255)) result.paste(stupid_image) result.save(fname) t4 = time.time() Notice.info("output file {}".format(fname)) Notice.ok("Saved stupidity in {:.1f} s".format(t4 - t3)) return
def fbget_PerPathwayInfo(pathwayNodes, pairedcases): #Input: Nodes from NetPath for a particular pathway #Process: Produces fbget data for every single node in the pathway, puts the data into a dictionary for that node that is formatted as "[Node][output]" in a string. #Output: An array>array containing the information in the text files separated by column and line. #Initialize variables pathwaydict = { } #Holds all the fbget information per node in a dictionary. Processed information is accessible by "[Node][output]" - which is the node, and the type of information in one string. #Variables initialized. for node in range(len(pathwayNodes)): #For determining what kind of data you'd like to pull from firebrowse - for gene expression data, 2 means expression_log2, while 3 means the z-score of that data point. print(fbget.mrnaseq(gene=pathwayNodes[node][2], cohort="coad")) print("The node currently being analyzed is: " + pathwayNodes[node][2]) #Pulls the mRNA sequencing activity fbget_Output = fbget_Reader( fbget.mrnaseq(gene=pathwayNodes[node][2], cohort="coad", page_size=2000), {2}) #Pulls out patient ID and sample type. fbget_Patient = fbget_Reader( fbget.mrnaseq(gene=pathwayNodes[node][2], cohort="coad", page_size=2000), {0, 5}) #Production of the information dictionary pathwaydict pathwaydict[pathwayNodes[node][2]] = fbget_Output pathwaydict[(pathwayNodes[node][2]) + "ID"] = fbget_Patient if pairedcases == True: Ndict, Tdict = fbget_PatientPairer(pathwaydict, ((pathwayNodes[node][2]))) Narray = list(itertools.chain.from_iterable(Ndict.values())) Tarray = list(itertools.chain.from_iterable(Tdict.values())) #Performing a t-test, and then other statistical analysis. print("The amount of normal samples is: ", len(Narray)) print("The amount of tumor samples is: ", len(Tarray)) tstat, tsignificance = stats.ttest_ind(Narray, Tarray, equal_var=True) if tsignificance < 0.05: print("The difference is significant for ", pathwayNodes[node][2]) pathwaydict[(pathwayNodes[node][2]) + "tstat"] = tstat pathwaydict[(pathwayNodes[node][2]) + "tsignificance"] = tsignificance print("The t-test results for ", pathwayNodes[node][2], "are ", pathwaydict[(pathwayNodes[node][2]) + "tstat"], " and ", pathwaydict[(pathwayNodes[node][2]) + "tsignificance"]) print("Normalizing Narray: ") fbget_Normalizing(Narray, False) print("Normalizing Tarray: ") fbget_Normalizing(Tarray, False) #Nodes in a pathway, and then eventually nodes for an entire type of cancer on the pathways it has been seen to affect. normalizedvalue, avg, normalizedavg, zscores = fbget_Normalizing( fbget_Output, True) pathwaydict[(pathwayNodes[node][2]) + "normalizedvalue"] = normalizedvalue pathwaydict[(pathwayNodes[node][2]) + "avg"] = avg pathwaydict[(pathwayNodes[node][2]) + "normalizedavg"] = normalizedavg pathwaydict[(pathwayNodes[node][2]) + "zscores"] = zscores if tsignificance < 0.01: pathwaydict[(pathwayNodes[node][2]) + "huevalue"] = rgb_to_hex( 255, int(255 * tsignificance), int(255 * tsignificance)) else: pathwaydict[(pathwayNodes[node][2]) + "huevalue"] = rgb_to_hex( 255, int(255), int(255)) #e.g. To access WNT7's normalizedavg, use the value "pathwaydict["WNT7normalizedavg"]"" #print(pathwaydict["WNT7Anormalizedavg"]) #DB return pathwaydict
def subclass_init(self, loc=None): super(SimHerbivore, self).subclass_init(loc) self.energy = 40 self.color = rgb_to_hex(self.r, self.g, self.b) self.age = 0
def subclass_init(self, loc=None): super(SimPlant, self).subclass_init(loc) self.energy = 0 self.color = rgb_to_hex(self.r, self.g, self.b) self.size = 0
def plot_histogram(ax, data, tickfmt, cfg): """ Plot a histogram of amplitude values. """ fs = cfg['fontsize'] percentile = cfg['percentile'] data = np.array(data) datamax = np.amax(data) datamin = np.amin(data) datamean = np.nanmean(data) largest = max(datamax, abs(datamin)) clip_val = np.percentile(data, percentile) ax.patch.set_alpha(0.0) color = utils.rgb_to_hex(cfg['highlight_colour']) y, x, _ = ax.hist(np.ravel(data), bins=int(100.0 / (clip_val / largest)), alpha=0.6, color=color, lw=0) ax.set_xlim(-clip_val, clip_val) ax.set_xticklabels(ax.get_xticks(), fontsize=fs - 4) ax.set_xlabel('amplitude', fontsize=fs - 4) ax.xaxis.set_label_coords(0.5, -0.12) ax.set_ylim([0, y.max()]) ax.set_yticks(np.linspace(0, y.max(), 6)) ax.set_ylabel('percentage of samples', fontsize=fs - 4) ax.tick_params(axis='x', pad=25) ax.xaxis.labelpad = 25 ticks = ax.get_yticks().tolist() # ytick labels percentages = 100 * np.array(ticks) / data.size labels = [] for label in percentages: labels.append("{:.2f}".format(label)) ax.set_yticklabels(labels, fontsize=fs - 4) ax.xaxis.set_major_formatter(tickfmt) if datamax < 1: statstring = "\nMinimum: {:.4f}\nMean: {:.4f}\nMaximum: {:.4f}".format( datamin, datamean, datamax) statstring += "\n{:.1f} percentile: {:.4f}".format( percentile, clip_val) elif datamax < 10: statstring = "\nMinimum: {:.2f}\nMean: {:.2f}\nMaximum: {:.2f}".format( datamin, datamean, datamax) statstring += "\n{:.1f} percentile: {:.2f}".format( percentile, clip_val) elif datamax < 100: statstring = "\nMinimum: {:.1f}\nMean: {:.1f}\nMaximum: {:.1f}".format( datamin, datamean, datamax) statstring += "\n{:.1f} percentile: {:.1f}".format( percentile, clip_val) else: statstring = "\nMinimum: {:.0f}\nMean: {:.0f}\nMaximum: {:.0f}".format( datamin, datamean, datamax) statstring += "\n{:.1f} percentile: ±{:.0f}".format( percentile, clip_val) ax.text(.98, .95, 'AMPLITUDE HISTOGRAM', horizontalalignment='right', verticalalignment='top', fontweight='bold', color=utils.rgb_to_hex(cfg['highlight_colour']), transform=ax.transAxes, fontsize=fs - 3) ax.text(.98, .95, statstring, horizontalalignment='right', verticalalignment='top', transform=ax.transAxes, fontsize=fs - 3) ax.set_alpha(0) ax.grid() gridlines = ax.get_xgridlines() + ax.get_ygridlines() for line in gridlines: line.set_linestyle('-') line.set_alpha(0.2) return ax