def maybe_blend(base_color, overlay_color): """ Try to blend semi transparent overlay color on opaque base color. Return None if not successful """ import re try: bc = spectra.html(base_color).to("rgb") except ValueError: return None try: # If overlay color is hex code or named color, it's # opaque, return as is return spectra.html(overlay_color).hexcode except ValueError: # Otherwise, it might be rgba pass rgba_match = re.match(r"rgba\(([^,]+),([^,]+),([^,]+),([^,]+)\)", overlay_color) if rgba_match is None: return None r, g, b, a = [float(n) for n in rgba_match.groups()] overlay_rgb = spectra.rgb(r / 255, g / 255, b / 255) blended = overlay_rgb.blend(bc, 1 - a) return blended.hexcode
def make_colour_map(colours, indexes=None, size=256, gradient=True): """Make a colour map for a list of colours aligned to indexes. Parameters ---------- colours : list of (spectra color objects or strings) The list can contain spectra color objects or strings containing namded colors or hexcodes. indexes : list of ints The index placements to tell when to move from one colour to the next size : int The size of the colour map. gradient : bool Whether to trasition between colours as a gradient (True) or jump between at the indexes. (False) Returns ------- numpy ndarray(size,3) of float The derived colour map. """ if not indexes: # If indexes is not set, return an even continuous distribution. colour_array = spectra.range(colours, size) # Convert of Color objects to 2D numpy array of rgb and return return np.asarray([c.rgb for c in colour_array]) * 255 # Otherwise, align the colour map to the indexes # Find the colours between the first and second index. run_size = indexes[1] - indexes[0] + 1 if gradient: colour_run = spectra.range([colours[0], colours[1]], run_size) colour_map = np.asarray([c.rgb for c in colour_run]) * 255 else: colour_map = np.tile(np.asarray(spectra.html(colours[0]).rgb), (run_size, 1)) * 255 # Find the remaining colours values and concatenate into one array. for run in range(1, len(indexes) - 1): run_size = indexes[run + 1] - indexes[run] + 1 if gradient: colour_run = spectra.range([colours[run], colours[run + 1]], run_size) crt = np.asarray([c.rgb for c in colour_run]) * 255 else: crt = np.tile(np.asarray(spectra.html(colours[run]).rgb), (run_size, 1)) * 255 # Note: To avoid overlap we cut off the last value from the current colour map colour_map = np.concatenate((colour_map[:-1, :], crt), axis=0) return colour_map
def get_colour(self, val, colformat="hex", lighten=0.3): """Given a value, return a colour within the colour scale""" # Ported from the original JavaScript for continuity # Seems to work better than adjusting brightness / saturation / luminosity rgb_converter = lambda x: max(0, min(1, 1 + ((x - 1) * lighten))) try: # When we have non-numeric values (e.g. Male/Female, Yes/No, chromosome names, etc), and a qualitive # scale (Set1, Set3, etc), we don't want to attempt to parse numbers, otherwise we will end up with all # values assigned with the same color. But instead we will geta has from a string to hope to assign # a unique color for each possible enumeration value. if self.name in mqc_colour_scale.qualitative_scales and isinstance( val, str): thecolour = spectra.html(self.colours[hash(val) % len(self.colours)]) thecolour = spectra.rgb( *[rgb_converter(v) for v in thecolour.rgb]) return thecolour.hexcode # When there is only 1 color in scale, spectra.scale() will crash with DevisionByZero elif len(self.colours) == 1: thecolour = spectra.html(self.colours[0]) thecolour = spectra.rgb( *[rgb_converter(v) for v in thecolour.rgb]) return thecolour.hexcode else: # Sanity checks val = re.sub("[^0-9\.-e]", "", str(val)) if val == "": val = self.minval val = float(val) val = max(val, self.minval) val = min(val, self.maxval) domain_nums = list( np.linspace(self.minval, self.maxval, len(self.colours))) my_scale = spectra.scale(self.colours).domain(domain_nums) # Lighten colours thecolour = spectra.rgb( *[rgb_converter(v) for v in my_scale(val).rgb]) return thecolour.hexcode except: # Shouldn't crash all of MultiQC just for colours return ""
def handle(self, *args, **options): luminance = options.get('luminance', None) if not luminance: raise Exception('--luminance is required') if luminance > 100 or luminance < -100: raise Exception('Luminance must be in between -100 and 100') Hashtag = get_hashtag_model() processed_hashtags = 0 for hashtag in Hashtag.objects.all().iterator(): with transaction.atomic(): color = spectra.html(hashtag.color) if luminance > 0: color = color.brighten(luminance) else: color = color.darken(luminance * -1) hashtag.color = color.hexcode hashtag.save() logger.info('Processed hashtags for post with name:' + str(hashtag.name)) processed_hashtags = processed_hashtags + 1 logger.info('Updated %d hashtags colors' % processed_hashtags)
def get_random_pastel_color(): # Its a random color jeez, we dont need cryptographically secure randomness h, s, l = random.random( ), 0.5 + random.random() / 2.0, 0.4 + random.random() / 5.0 # nosec r, g, b = [int(256 * i) for i in colorsys.hls_to_rgb(h, l, s)] hex_color = '#%02x%02x%02x' % (r, g, b) color = spectra.html(hex_color).darken(amount=20) return color.hexcode
def _make_col_alpha(cols, alpha): """ Take a HTML colour value and return a rgba string with alpha """ cols_return = [] for col in cols: col_srgb = spectra.html(col) cols_rgb = [c * 255.0 for c in col_srgb.clamped_rgb] cols_return.append("rgba({},{},{},{})".format(*cols_rgb, alpha)) return cols_return
def processArgumentNotation(self, argument, parent): type = argument.get("TYPE") elementToReturn = None if type: type = type.split() # split on space typeOfElement = type[0] typeArguments = type[1:] # all elements other then the first if typeOfElement == "FILE": if len(typeArguments) == 0: elementToReturn = wx.FilePickerCtrl(parent=parent, message="Open file", style=wx.FD_OPEN) else: elementToReturn = wx.FilePickerCtrl( parent=parent, message="Open file", wildcard=self.wildcardReturn(typeArguments), style=wx.FD_OPEN) elif typeOfElement == "DROPDOWN": elementToReturn = wx.ComboBox(parent=parent, choices=typeArguments) elif typeOfElement == "SLIDER": minValue = None maxValue = None if len(typeArguments) == 0: minValue = 0 maxValue = 100 else: minValue = int(typeArguments[0]) maxValue = int(typeArguments[1]) elementToReturn = wx.Slider(parent=parent, minValue=minValue, maxValue=maxValue, style=wx.SL_LABELS) elif typeOfElement == "COLOR": if len(typeArguments) == 0: elementToReturn = wx.ColourPickerCtrl(parent=parent) else: elementToReturn = wx.ColourPickerCtrl( parent=parent, colour=wx.Colour(*spectra.html(typeArguments[0]).rgb)) elif typeOfElement == "TEXT": if len(typeArguments) == 0: elementToReturn = wx.TextCtrl(parent=parent, value="") else: elementToReturn = wx.TextCtrl( parent=parent, value=typeArguments[0].replace("_", " ")) else: elementToReturn = wx.TextCtrl(parent=parent, value="") # just a generic text box return elementToReturn
def createDiceOneColor(document, basesize, angle, color): if type(color) is list: baseColor = spectra.html(color[0]) if len(color) >= 2: lightColor = spectra.html(color[1]) else: lightColor = spectra.lab(baseColor.to("lab").values[0] * 1.1, baseColor.to("lab").values[1], baseColor.to("lab").values[2]) if len(color) == 3: lightestColor = spectra.html(color[2]) else: lightestColor = spectra.lab(baseColor.to("lab").values[0] * 1.2, baseColor.to("lab").values[1], baseColor.to("lab").values[2]) else: baseColor = spectra.html(color) lightColor = spectra.lab(spectra.html(color).to("lab").values[0] * 1.1, spectra.html(color).to("lab").values[1], spectra.html(color).to("lab").values[2]) lightestColor = spectra.lab(spectra.html(color).to("lab").values[0] * 1.2, spectra.html(color).to("lab").values[1], spectra.html(color).to("lab").values[2]) return createDice(document, basesize, angle, baseColor.hexcode, lightestColor.hexcode, lightColor.hexcode)
def get_dark_palette(): """ Return the default dark color palette. """ palette = get_default_palette() for color in [ "blue", "green", "yellow", "orange", "red", "electric-blue", "purple", ]: palette[color] = spectra.html(palette[color]).darken(10).hexcode return palette
def __init__( self, track_files=[ "/Users/DarthRNA/Documents/Robin/GRAPHY_TEST/miR29_WT_Th2.bam" ]): self.track_files = track_files self.color_values = ["#0080ff", "#0080ff", "#0080ff", "#0080ff"] self.figwidth = 0.0 self.figheight = 5 self.refseqtrack = True self.LeftToRight = False self.strand = "-" self.colors = itertools.cycle( [spectra.html(i).darken(20).hexcode for i in self.color_values]) self.shade = itertools.cycle(self.color_values) self.limits = "default" self.bedtrack = False self.start = 142903034 self.stop = 142906867 self.staggerbed = False self.bigwignames = [] self.wig_df_list = {} self.shade_by_bed = False self.output_folder = "/Users/DarthRNA/Documents/Robin/TrackImages/" self.geneid = "Actb" self.outputsuffix = "" self.outputformat = "pdf" self.dpi = 300 self.track_names = [i.split("/")[-1] for i in self.track_files] self.track_type = ['s' for i in track_files] self.axis_off = False self.legend = True self.staticaxes = True self.bedfile = None self.bedtype = None self.name = None self.chrom = "chr5" self.refseqid = "NM_007393" self.annotate_bed = False self.fontsize = 12 self.scaleRPM = False
def set(server, colour): try: hsv = spectra.html(colour).to("hsv").values except: click.secho("Conversion Error!", blink=True, fg="red") click.echo("This color couldn't be converted to HSV.") return result = requests.post(server + "/state", json={ "hue": hsv[0], "saturation": hsv[1], "value": hsv[2] }) if result.status_code == 200: click.secho("Success!", fg="green") click.echo("Changed color to {}. Status Code: {}".format( colour, result.status_code)) else: click.secho("Requests Error!", blink=True, fg="red") click.echo("Status Code: {} Message: {}".format( result.status_code, result.json()["error"]))
"""Opacity that is roughly inversely proportional to the ellipse's area in steradians """ errors = N.radians(orientation.angular_errors()) area = N.pi * N.prod(errors / 2) return N.interp(area, (0.002, 0.01), (0.05, 0.01)) plot_ellipses(axes[0], df, black) grouped = df.groupby("Geological Classification") color_ix = dict(IO="black", IOC="red", B="green", OL="blue") group_ix = dict(IO=0, IOC=1, B=2, OL=3) for name, group in grouped: color = spectra.html(color_ix[name]) plot_ellipses(axes[1], group, color.rgb) plt.tight_layout() fig.savefig(argv[1], bbox_inches='tight') fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(6, 6), subplot_kw=dict(projection='polar')) axes = axes.reshape(4) # Axis setup for ax in axes: setup_axis(ax) ax.set_xticklabels([])
def brighten(color_hex, amount): color = spectra.html(color_hex) return color.brighten(amount).hexcode
def to_colormath(spectra_color): lab_values = spectra.html(spectra_color.hexcode).to("lab").values return LabColor(*lab_values)
def darken(color_hex, amount): color = spectra.html(color_hex) return color.darken(amount).hexcode
def on_button_clicked(b): clear_output() ## SANITY CHECKS ### if not len(file_widget.value) > 0: print "ERROR: It's required to pick a .bam alignment!" return ##################### if lookuptype_widget.value == "location": chrom, start, stop = ct.easylocation(location_widget.value) strand = strand_widget.value elif lookuptype_widget.value == "geneid": chrom, start, stop, value, strand = df_refseq_3utr.loc[ refseqid_widget.value] if bedtracks_widget.value == "None": bedtrack = False bedfile = None bedtype = None name = None elif bedtracks_widget.value == "Peaks": bedtrack = True bedfile = bedfiles_allowed[bedtracks_widget.value]["bedfile"] bedtype = "bed" name = "Peaks" elif bedtracks_widget.value == "Other": bedtrack = True bedfile = other_bedtracks_widget.value bedtype = "bed" name = "Bedtrack" elif bedtracks_widget.value == "Targetscan": bedtrack = True bedfile = bedfiles_allowed[bedtracks_widget.value]["bedfile"] if miRNA_widget.value == "ALL": bedtype = bedfiles_allowed[bedtracks_widget.value]["bedtype"] name = bedfiles_allowed[bedtracks_widget.value]["name"] else: bedtype = "targetscan" name = miRNA_widget.value elif bedtracks_widget.value == "Custom": bedtrack = True bedfile = w_default_folder.value + miRNA_widget.value bedtype = "bed" name = miRNA_widget.value track_type = [] for t in w_antisense_check.options: if t in w_antisense_check.value: track_type.append("as") else: track_type.append("s") geneid = geneid_widget.value refseqid = refseqid_widget.value track_names = [ f for f in w_antisense_check.options if f.split(".")[-1] == "bam" ] bigwignames = [ f for f in w_antisense_check.options if f.split(".")[-1] == "bw" ] track_files = [w_default_folder.value + f for f in track_names] bigwigfiles = [w_default_folder.value + f for f in bigwignames] depths = get_depth_data(track_files, track_names, chrom, start, stop, strand, track_type) wig_df_list = get_wig_data(bigwigfiles, bigwignames, chrom, start, stop) outputformat = w_fileformat.value figwidth = w_xscale.value dpi = w_dpi.value LeftToRight = w_invert.value annotate_bed = w_labels.value staggerbed = w_stagger.value refseqtrack = w_refseq.value shade_by_bed = w_shadeBed.value outputsuffix = w_filesuffix.value staticaxes = w_staticaxes.value axis_off = not w_boundingbox.value fontsize = w_fontsize.value legend = w_legend.value figheight = 2.5 * len(w_antisense_check.options) output_folder = w_outputfolder.value color_values = [w_cp1.value, w_cp2.value, w_cp3.value] shade = itertools.cycle(color_values) colors = itertools.cycle( [spectra.html(i).darken(20).hexcode for i in color_values]) plot(figwidth, figheight, refseqtrack, LeftToRight, strand, depths, colors, shade, limits, bedtrack, start, stop, staggerbed, bigwignames, wig_df_list, shade_by_bed, output_folder, geneid, outputsuffix, outputformat, dpi, track_names, axis_off, legend, staticaxes, bedfile, bedtype, name, chrom, refseqid, annotate_bed, fontsize)
query = """SELECT sentence.index_in_book, color.name, color.base, book.id, mention.index_in_sent FROM color, mention, sentence, clause, book WHERE mention.color=color.id AND mention.clause=clause.id AND clause.sentence=sentence.id AND sentence.book=book.id AND book.id IN (3759, 3694, 5727, 4032, 4637, 2743, 5866, 1032, 5155, 2410)""" c.execute(query) for row in c.fetchall(): sentence_index = row[0] mention_index = row[4] # in sentence color_name = row[1] color_base = row[2] book_id = row[3] if hex_codes[color_name] != 'NULL': #print(color_name) #print(hex_codes[color_name]) lab0 = spectra.html(hex_codes[color_name]).to('lab').values lab0 = LabColor(lab_l=lab0[0], lab_a=lab0[1], lab_b=lab0[2]) mention_index_in_book = get_index_mention(book_id, sentence_index) mentions[book_id].append( (color_name, color_base, mention_index_in_book + mention_index, lab0, hex_codes[color_name])) # dynamic time warping def d(a, b): val = abs(a[2] - b[2]) * delta_e_cie2000(a[3], b[3]) # val = abs(a[2] - b[2]) * abs(int(a[4], 16) - int(b[4], 16)) #print(val) return val
def scores(request): # todo: this param handling code is absolutely disgusting, it should be more beautiful. # todo: should we just get the last contest if there is no contest at all? submitted_contest = request.GET.get("contest", "") if submitted_contest is not None and submitted_contest.isnumeric(): submitted_contest = int(submitted_contest) else: submitted_contest = 0 if submitted_contest > -1: try: contest = Contest.objects.get(id=submitted_contest) except ObjectDoesNotExist: contest = get_default_contest(request) else: contest = get_default_contest(request) # remove disqualified teams. teams = Team.objects.all().filter(participating_in_contest=contest, allowed_to_submit_things=True) scores = [] for team in teams: """ Out of simplicity _ALL_ scores are retrieved instead of the last one per URL. Last one-per is not supported in Django and therefore requires a lot of code. The deviation is negligible during a contest as not so much will change in a day or two. On the long run it might increase the score a bit when incorrect fixes are applied or a new error is found. If the discovered issue is fixed it doesn't deliver additional points. """ scans = list(EndpointGenericScan.objects.all().filter( endpoint__url__urlsubmission__added_by_team=team.id, endpoint__url__urlsubmission__has_been_accepted=True, rating_determined_on__lte=contest.until_moment, type__in=ENDPOINT_SCAN_TYPES, )) scans += list(UrlGenericScan.objects.all().filter( url__urlsubmission__added_by_team=team.id, url__urlsubmission__has_been_accepted=True, rating_determined_on__lte=contest.until_moment, type__in=URL_SCAN_TYPES, )) added_urls = (UrlSubmission.objects.all().filter( added_by_team=team.id, has_been_accepted=True, has_been_rejected=False, ).count()) added_organizations = (OrganizationSubmission.objects.all().filter( added_by_team=team.id, has_been_accepted=True, has_been_rejected=False).count()) rejected_organizations = (OrganizationSubmission.objects.all().filter( added_by_team=team.id, has_been_accepted=False, has_been_rejected=True, ).count()) rejected_urls = (UrlSubmission.objects.all().filter( added_by_team=team.id, has_been_accepted=False, has_been_rejected=True, ).count()) final_calculation = { "high": 0, "medium": 0, "low": 0, } for scan in scans: temp_calculation = get_severity(scan) final_calculation["high"] += temp_calculation["high"] final_calculation["medium"] += temp_calculation["medium"] final_calculation["low"] += temp_calculation["low"] score_multiplier = { "low": 100, "medium": 250, "high": 1000, "rejected_organization": 1337, "rejected_url": 1337, "organization": 500, "url": 250, } # if you're too lazy to enter a color. # or the control doesn't work. if team.color: color = spectra.html(team.color.upper()) # nope, deep frying doesn't help us # color = color.saturate(100) # deep fry the color, so something remains even after insane brighten color = color.brighten(10) color_code = color.hexcode else: color_code = "#FFFFFF" score = { "team": team.name, "team_color": team.color, # transparency makes it lighter and more beautiful. "team_color_soft": "%s%s" % (color_code, "33"), "high": final_calculation["high"], "high_multiplier": score_multiplier["high"], "high_score": final_calculation["high"] * score_multiplier["high"], "medium": final_calculation["medium"], "medium_multiplier": score_multiplier["medium"], "medium_score": final_calculation["medium"] * score_multiplier["medium"], "low": final_calculation["low"], "low_multiplier": score_multiplier["low"], "low_score": final_calculation["low"] * score_multiplier["low"], "added_organizations": added_organizations, "added_organizations_multiplier": score_multiplier["organization"], "added_organizations_score": added_organizations * score_multiplier["organization"], "added_urls": added_urls, "added_urls_multiplier": score_multiplier["url"], "added_urls_score": added_urls * score_multiplier["url"], "rejected_organizations": rejected_organizations, "rejected_organizations_multiplier": score_multiplier["rejected_organization"], "rejected_organizations_score": rejected_organizations * score_multiplier["rejected_organization"], "rejected_urls": rejected_urls, "rejected_urls_multiplier": score_multiplier["rejected_url"], "rejected_urls_score": rejected_urls * score_multiplier["rejected_url"], "total_score": final_calculation["high"] * score_multiplier["high"] + final_calculation["medium"] * score_multiplier["medium"] + final_calculation["low"] * score_multiplier["low"] + added_organizations * score_multiplier["organization"] + added_urls * score_multiplier["url"] - (rejected_urls * score_multiplier["rejected_url"] + rejected_organizations * score_multiplier["rejected_organization"]), } scores.append(score) # order the scores from high to low. scores = sorted(scores, key=lambda k: (k["total_score"], k["high"], k["medium"], k["low"]), reverse=True) return render( request, "game/scores.html", { "team": get_team_info(request), "scores": scores, "contest": contest, "menu_selected": "scores" }, )
def on_button_clicked(b): clear_output() ## SANITY CHECKS ### if not len(file_widget.value)>0: print "ERROR: It's required to pick a .bam alignment!" return ##################### if lookuptype_widget.value=="location": chrom,start,stop = ct.easylocation(location_widget.value) strand = strand_widget.value elif lookuptype_widget.value=="geneid": chrom,start,stop,value,strand = df_refseq_3utr.loc[refseqid_widget.value] if bedtracks_widget.value == "None": bedtrack=False bedfile=None bedtype=None name=None elif bedtracks_widget.value == "Peaks": bedtrack=True bedfile = bedfiles_allowed[bedtracks_widget.value]["bedfile"] bedtype = "bed" name = "Peaks" elif bedtracks_widget.value == "Other": bedtrack=True bedfile = other_bedtracks_widget.value bedtype = "bed" name = "Bedtrack" elif bedtracks_widget.value == "Targetscan": bedtrack=True bedfile = bedfiles_allowed[bedtracks_widget.value]["bedfile"] if miRNA_widget.value == "ALL": bedtype = bedfiles_allowed[bedtracks_widget.value]["bedtype"] name = bedfiles_allowed[bedtracks_widget.value]["name"] else: bedtype = "targetscan" name = miRNA_widget.value elif bedtracks_widget.value == "Custom": bedtrack=True bedfile = w_default_folder.value+miRNA_widget.value bedtype = "bed" name = miRNA_widget.value track_type=[] for t in w_antisense_check.options: if t in w_antisense_check.value: track_type.append("as") else: track_type.append("s") geneid= geneid_widget.value refseqid = refseqid_widget.value track_names = [f for f in w_antisense_check.options if f.split(".")[-1]=="bam"] bigwignames = [f for f in w_antisense_check.options if f.split(".")[-1]=="bw"] track_files = [w_default_folder.value + f for f in track_names] bigwigfiles = [w_default_folder.value + f for f in bigwignames] depths = get_depth_data(track_files,track_names,chrom,start,stop,strand,track_type) wig_df_list = get_wig_data(bigwigfiles,bigwignames,chrom,start,stop) outputformat = w_fileformat.value figwidth = w_xscale.value dpi = w_dpi.value LeftToRight = w_invert.value annotate_bed = w_labels.value staggerbed = w_stagger.value refseqtrack = w_refseq.value shade_by_bed = w_shadeBed.value outputsuffix = w_filesuffix.value staticaxes = w_staticaxes.value axis_off= not w_boundingbox.value fontsize = w_fontsize.value legend = w_legend.value figheight = 2.5*len(w_antisense_check.options) output_folder = w_outputfolder.value color_values = [w_cp1.value,w_cp2.value,w_cp3.value] shade = itertools.cycle(color_values) colors = itertools.cycle([spectra.html(i).darken(20).hexcode for i in color_values]) plot(figwidth,figheight,refseqtrack,LeftToRight,strand,depths, colors,shade,limits,bedtrack,start,stop,staggerbed,bigwignames, wig_df_list,shade_by_bed,output_folder,geneid,outputsuffix,outputformat,dpi,track_names,axis_off, legend,staticaxes,bedfile,bedtype,name,chrom,refseqid,annotate_bed,fontsize)
async def color_props(e): params = e.pattern_match.group(1) or "" args, color = parse_arguments(params, ['format', 'extended']) reply_message = await e.get_reply_message() if not color: await e.edit("Please provide a color...", delete_in=3) return if args.get('format') == 'rgb': r, g, b = re.findall(r'[\-.0-9]+', color) parsed = spectra.rgb(r, g, b) elif args.get('format') == 'lab': l, a, b = re.findall(r'[\-.0-9]+', color) parsed = spectra.lab(l, a, b) elif args.get('format') == 'lch': l, c, h = re.findall(r'[\-.0-9]+', color) parsed = spectra.lch(l, c, h) elif args.get('format') == 'hsl': h, s, l = re.findall(r'[\-.0-9]+', color) parsed = spectra.hsl(h, s, l) elif args.get('format') == 'hsv': h, s, v = re.findall(r'[\-.0-9]+', color) parsed = spectra.hsv(h, s, v) elif args.get('format') == 'xyz': x, y, z = re.findall(r'[\-.0-9]+', color) parsed = spectra.xyz(x, y, z) elif args.get('format') == 'cmy': c, m, y = re.findall(r'[\-.0-9]+', color) parsed = spectra.cmy(c, m, y) elif args.get('format') == 'cmyk': c, m, y, k = re.findall(r'[\-.0-9]+', color) parsed = spectra.cmyk(c, m, y, k) else: parsed = spectra.html(color) rgb = [round(x * 255) for x in parsed.to('rgb').clamped_rgb] hsl = parsed.to('hsl').values hsv = parsed.to('hsv').values formats = { 'hex': parsed.hexcode, 'rgb': values__to_str(rgb), 'hsl': values__to_str(hsl), 'hsv': values__to_str(hsv) } if args.get('extended'): formats.update({ 'lab': values__to_str(parsed.to('lab').values), 'lch': values__to_str(parsed.to('lch').values), 'xyz': values__to_str(parsed.to('xyz').values), 'cmyk': values__to_str(parsed.to('cmyk').values) }) message = "" for fmt in formats.items(): message += f"**{fmt[0]}**: `{fmt[1]}` \n" swatch = make_swatch(tuple(rgb)) await e.delete() await e.client.send_file(e.chat_id, swatch, caption=message, reply_to=reply_message)
def run(figwidth, color_values, track_names, track_type, bedtrack, bedfile, bedtype, name, annotate_bed, geneid, chrom, start, stop, refseqid, strand, bigwignames, fontsize, shade_by_bed): # ############# Constant Values ############# Do not edit # staticaxes = True # LeftToRight = False # axis_off = False # refseqtrack = True staticaxes = True if request.GET['staticaxes'] == "true": staticaxes = True elif request.GET['staticaxes'] == "false": staticaxes = False LeftToRight = False if request.GET['LeftToRight'] == "true": LeftToRight = True elif request.GET['LeftToRight'] == "false": LeftToRight = False axis_off = False if request.GET['axis_off'] == "true": axis_off = True elif request.GET['axis_off'] == "false": axis_off = False refseqtrack = True if request.GET['refseqtrack'] == "true": refseqtrack = True elif request.GET['refseqtrack'] == "false": refseqtrack = False figheight = float(figwidth / 4.0) shade = itertools.cycle(color_values) colors = itertools.cycle( [spectra.html(i).darken(20).hexcode for i in color_values]) limits = [start, stop] staggerbed = True output_folder = path_to_static + "../Output/" outputformat = "png" outputsuffix = "" + str(random.randint(1, 1019080210)) dpi = float(300.0) legend = True static_url = staticfiles_storage.url('graphy_static/') # track_files = ['Data' + f for f in track_names] track_files = [static_url + f for f in track_names] bigwigfiles = ['Data' + f for f in bigwignames] wig_df_list = get_wig_data(bigwigfiles, bigwignames, chrom, start, stop) depths = get_depth_data(track_files, track_names, chrom, start, stop, strand, track_type) # ############# Constant Values ############# plot_value = plot(figwidth, figheight, refseqtrack, LeftToRight, strand, depths, colors, shade, limits, bedtrack, start, stop, staggerbed, bigwignames, wig_df_list, shade_by_bed, output_folder, geneid, outputsuffix, outputformat, dpi, track_names, axis_off, legend, staticaxes, bedfile, bedtype, name, chrom, refseqid, annotate_bed, fontsize) """ to convert this values = { 'GCliPP_everything.bam': { 142903034: 0, 142903035: 0, 142906866: 0 }, 'miR29_WT_Th17.bam': { 142903034: 0, 142903035: 0, 142906866: 0 } } into this [ { "year": "142903035", "GCliPP_everything": 1, "miR29_WT_Th17": 0 }, { "year": "142903035", "GCliPP_everything": 1, "miR29_WT_Th17": 0 } ] """ real_value = [] bam_files = [] for value in plot_value: bam_files.append(value) for bam_file in bam_files: this_bam_file_index = bam_files.index(bam_file) if this_bam_file_index == 0: values_of_this_bam = plot_value[bam_file] for this_val in values_of_this_bam: first_dict_val = this_val break for val in values_of_this_bam: # print('val', val) real_value.append({ # 'x_axis': values_of_this_bam[val], bam_file: values_of_this_bam[val], 'year': str( (val + 100) - first_dict_val ) #our charts doesn't support less than 3 digit or more than 6 digit # 'year': str(val) #our charts doesn't support less than 3 digit or more than 6 digit }) else: values_of_this_bam = plot_value[bam_file] for ind, val2 in enumerate(values_of_this_bam): this_index = ind real_value[this_index][bam_file] = values_of_this_bam[val2] # print(real_value) csv_url = '/static/CSV_Output/' + geneid + outputsuffix + '.csv' pdf_url = '/static/Output/' + geneid + outputsuffix + '.pdf' outputsuffix = 'static/Output/' + geneid + outputsuffix + '.png' return { 'bam_files': bam_files, 'image_url': outputsuffix, 'pdf_url': pdf_url, 'csv_url': csv_url, 'graph_data': real_value, 'label_data': plot_value.get('label_data', {}), 'first_dict_val': first_dict_val #for converting date to number in labeling need to use in js }
def convertColors(): out = [] for i in range(0, 20): out.append(spectra.html(colorScale(i)).desaturate(amount=60).hexcode) print(out)
def get_theme(mode="light", strong_grid=False, palette="default"): """ Return a matplotlib theme as a dictionary. Parameters ---------- mode : 'light', 'gray', dark' the theme's mode strong_grid : bool, optional whether to use strong grid lines palette : 'default', 'light', 'dark' whether to use the default color palette, or the light/dark versions Returns ------- theme : dict the dictionary holding the theme parameters Examples -------- >>> from matplotlib import pyplot as plt >>> import numpy as np >>> with plt.style.context(get_theme(mode="dark")): >>> plt.plot(np.random.random(size=10)) """ assert mode in ["dark", "gray", "light"] assert palette in ["default", "light", "dark"] if mode == "light": BG_COLOR = "#ffffff" TEXT_COLOR = "#353d42" LABEL_COLOR = "#666666" GRID_COLOR = "#666666" if strong_grid else "#d8d8d8" elif mode == "gray": BG_COLOR = "#353d42" TEXT_COLOR = LABEL_COLOR = "#ffffff" GRID_COLOR = "#ffffff" if strong_grid else "#4e5254" elif mode == "dark": BG_COLOR = "#121516" TEXT_COLOR = LABEL_COLOR = "#ffffff" GRID_COLOR = "#ffffff" if strong_grid else "#4e5254" # figure out the palette of colors colors = [ "#2176d2", "#58c04d", "#f3c613", "#f99300", "#f40000", "#25cef7", "#d233ff", ] if palette == "dark": colors = [spectra.html(color).darken(10).hexcode for color in colors] if palette == "light": colors = [spectra.html(color).brighten(10).hexcode for color in colors] theme = {} # Axes theme["axes.spines.left"] = False theme["axes.spines.bottom"] = False theme["axes.spines.top"] = False theme["axes.spines.right"] = False theme["axes.facecolor"] = BG_COLOR theme["axes.grid"] = True theme["axes.grid.axis"] = "both" theme["axes.grid.which"] = "major" theme["axes.labelcolor"] = TEXT_COLOR theme["axes.labelpad"] = 4.0 theme["axes.labelsize"] = 12.0 theme["axes.labelweight"] = "bold" theme["axes.linewidth"] = 0.75 theme["axes.prop_cycle"] = cycler("color", colors) theme["axes.titlepad"] = 6.0 theme["axes.titlesize"] = 18.0 theme["axes.titleweight"] = "bold" theme["axes.unicode_minus"] = True theme["axes.xmargin"] = 0.1 theme["axes.ymargin"] = 0.1 theme["axes.axisbelow"] = True # Grid theme["grid.alpha"] = 1.0 theme["grid.color"] = GRID_COLOR theme["grid.linestyle"] = "-" theme["grid.linewidth"] = 0.75 # Figure theme["figure.dpi"] = 300 theme["figure.frameon"] = True theme["figure.facecolor"] = BG_COLOR theme["figure.edgecolor"] = BG_COLOR theme["figure.figsize"] = [6.4, 4.8] theme["figure.subplot.left"] = 0.10 theme["figure.subplot.right"] = 0.95 theme["figure.subplot.bottom"] = 0.07 # Font theme["font.size"] = 12.0 theme["font.family"] = "Open Sans" # Legend theme["legend.framealpha"] = 1.0 theme["legend.edgecolor"] = "none" # Lines theme["lines.linewidth"] = 4.0 theme["lines.solid_capstyle"] = "round" theme["lines.dash_capstyle"] = "round" theme["lines.dashed_pattern"] = 3.7, 2.3 theme["lines.dashdot_pattern"] = 6.4, 2.3, 1.5, 2.3 theme["lines.dotted_pattern"] = 1, 1.65 theme["lines.scale_dashes"] = True # Patch theme["patch.linewidth"] = 0 # Savefig theme["savefig.edgecolor"] = BG_COLOR theme["savefig.facecolor"] = BG_COLOR # Text theme["text.color"] = TEXT_COLOR # Xticks theme["xtick.alignment"] = "center" theme["xtick.bottom"] = True theme["xtick.color"] = LABEL_COLOR theme["xtick.direction"] = "out" theme["xtick.labelbottom"] = True theme["xtick.labelsize"] = 12 theme["xtick.labeltop"] = False theme["xtick.major.bottom"] = True theme["xtick.major.pad"] = 3.5 theme["xtick.major.size"] = 0.0 theme["xtick.major.top"] = True theme["xtick.major.width"] = 0.75 theme["xtick.minor.bottom"] = True theme["xtick.minor.pad"] = 3.4 theme["xtick.minor.size"] = 0.0 theme["xtick.minor.top"] = True theme["xtick.minor.visible"] = False theme["xtick.minor.width"] = 0.6 theme["xtick.top"] = False # Yticks theme["ytick.alignment"] = "bottom" theme["ytick.color"] = LABEL_COLOR theme["ytick.direction"] = "in" theme["ytick.labelleft"] = True theme["ytick.labelright"] = False theme["ytick.labelsize"] = 12.0 theme["ytick.left"] = True theme["ytick.major.left"] = True theme["ytick.major.pad"] = 3.5 theme["ytick.major.right"] = True theme["ytick.major.size"] = 0.0 theme["ytick.major.width"] = 0.75 theme["ytick.minor.left"] = True theme["ytick.minor.pad"] = 3.4 theme["ytick.minor.right"] = True theme["ytick.minor.size"] = 0.0 theme["ytick.minor.visible"] = False theme["ytick.minor.width"] = 0.6 theme["ytick.right"] = False return theme
def on_button_clicked(b): clear_output() ## SANITY CHECKS ### if not len(file_widget.value) > 0: print "ERROR: It's required to pick a .bam alignment!" return ##################### if lookuptype_widget.value == "location": cPlot.chrom, cPlot.start, cPlot.stop = ct.easylocation( location_widget.value) cPlot.strand = strand_widget.value elif lookuptype_widget.value == "geneid": df_refseq_3utr = pd.read_table( "/Users/DarthRNA/Documents/Robin/genomes/mm10_refseq_3utr.bed", names=['chrom', 'start', 'stop', 'name', 'score', 'strand']) df_refseq_3utr.name = [ "_".join(x.split("_")[0:2]) for x in df_refseq_3utr.name ] df_refseq_3utr = df_refseq_3utr.drop_duplicates("name") df_refseq_3utr = df_refseq_3utr.set_index("name") cPlot.chrom, cPlot.start, cPlot.stop, foo, cPlot.strand = df_refseq_3utr.loc[ refseqid_widget.value] track_type = [] for t in w_antisense_check.options: if t in w_antisense_check.value: track_type.append("as") else: track_type.append("s") cPlot.geneid = geneid_widget.value cPlot.refseqid = refseqid_widget.value cPlot.track_names = [ f for f in w_antisense_check.options if f.split(".")[-1] == "bam" ] cPlot.bigwignames = [ f for f in w_antisense_check.options if f.split(".")[-1] == "bw" ] cPlot.track_files = [w_default_folder.value + f for f in cPlot.track_names] cPlot.bigwigfiles = [w_default_folder.value + f for f in cPlot.bigwignames] cPlot.track_type = track_type cPlot.outputformat = w_fileformat.value cPlot.figwidth = w_xscale.value cPlot.dpi = w_dpi.value cPlot.LeftToRight = w_invert.value cPlot.annotate_bed = w_labels.value cPlot.staggerbed = w_stagger.value cPlot.refseqtrack = w_refseq.value cPlot.shade_by_bed = w_shadeBed.value cPlot.outputsuffix = w_filesuffix.value cPlot.staticaxes = w_staticaxes.value cPlot.axis_off = not w_boundingbox.value cPlot.fontsize = w_fontsize.value cPlot.legend = w_legend.value cPlot.figheight = 2.5 * len(w_antisense_check.options) cPlot.output_folder = w_outputfolder.value cPlot.scaleRPM = w_rpm.value color_values = [w_cp1.value, w_cp2.value, w_cp3.value] cPlot.shade = itertools.cycle(color_values) cPlot.colors = itertools.cycle( [spectra.html(i).darken(20).hexcode for i in color_values]) cPlot.plot()