Esempio n. 1
0
    def c2c_dist(self, color_a, color_b):
        """return the distance(float) between two items(rgb vectors)"""

        a = Color(color_a)
        hsv_a = (a.hsv[0] / 360, a.hsv[1], a.hsv[2])
        b = Color(color_b)
        hsv_b = (b.hsv[0] / 360, b.hsv[1], b.hsv[2])
        dist_c2c = np.linalg.norm(np.array(hsv_a) - np.array(hsv_b))
        return (dist_c2c)
Esempio n. 2
0
def choose_palette():
    hsv2_numb = random.randint(1, 360)

    c_light = Color(hsv=(hsv2_numb, 0.15, 0.86))
    light_color = c_light.hex

    c_dark = Color(hsv=(hsv2_numb, 0.30, 0.36))
    dark_color = c_dark.hex

    return (light_color, dark_color)
Esempio n. 3
0
def display_user_HSV_option(H, S, V):
    """ Display the user selection with HTML paragraph and div

    Parameters
    ----------
    H : int
        Hue value selected by user via slider component.
    S : int
        Saturation value selected by user via slider component.
    V : int
        Value/Brightness value selected by user via slider component.

    Returns
    -------
    list
        Output string displaying user's choice of HSV and the CSS style
        object for the rectangle shape to update the CSS color.
    """
    # output string for displaying user choice
    hex_color = Color(hsv=(H, S / 100, V / 100)).hex
    output_string = "You selected HSV value of H:" + \
        str(H) + ", S: " + str(S) + ", and V: " + str(V) + \
        " (Hex code: " + hex_color + ")"

    # style change for div
    style = {"backgroundColor": hex_color, "height": "50px", "width": "100px"}
    return output_string, style
Esempio n. 4
0
    def __init__(self,
                 label="Shape",
                 description=None,
                 circumscribed_shape=None,
                 inscribed_shape_list=[],
                 position=None,
                 surface_color=Color((200, 200, 200)),
                 *args,
                 **kwargs):

        self.label = label
        self.description = description

        if position is None:
            print("AbstractShape.position --> default")
            position = Point3D(0, 0, 0)

        self.circumscribed_shape = None
        if circumscribed_shape is not None:
            circumscribed_shape.append_shape(self)

        self.inscribed_shape_list = list()
        if inscribed_shape_list is not None:
            for inscribed_shape in inscribed_shape_list:
                self.append_shape(inscribed_shape)

        self.position = position
        print("AbstractShape.position:{}".format(self.position))
        self.surface_color = surface_color
Esempio n. 5
0
def _generate_colours(n, half_life):
    # Cycle through hues linearly
    min_hue = 0  # Hue goes 0 -> 360 then loops around
    # the loop around is implemented later
    max_hue = 940
    hue_step = (max_hue - min_hue) / n

    # Decrease saturation exponentially
    max_saturation = 0.6  # Saturation goes 0 -> 1
    min_saturation = 0
    saturation_values = _generate_exponential_decay(n, half_life,
                                                    max_saturation,
                                                    min_saturation)

    brightness = 0.6  # Brigtness goes 0 (dark) -> 1 (light)

    colours = []  # Array of rgb tuples
    current_hue = max_hue
    for i in range(n):
        current_hue = (current_hue + hue_step) % 360
        # Saturation decays exponentially from max_sat -> min_sat
        # This is shown interatively in geogebra file saturation_decay.gbb
        colour = Color(hsv=(current_hue, saturation_values[i], brightness)).rgb
        colours.append(colour)
    return colours
Esempio n. 6
0
    def run(self):

        # print "tick"

        r = 0
        g = 0
        b = 0

        n_pixels = 512  # number of pixels in the included "octopus" layout
        fps = 10  # frames per second

        mid = 0

        vuVal = n_pixels

        start_time = time.time()
        #Where are the global coords?
        while True:
            mid = (mid + 4) % 255

            pixels = []
            print 'tick', mid
            for ii in range(n_pixels):

                p = (mid + random.randint(1, 40)) % 255

                # h 0-255, s 0.0-1.0, v 0.0-1.0
                col = Color(hsv=(p, random.uniform(0.2, 0.8),
                                 random.uniform(0.2, 0.8)))
                print p, col.rgb
                pixels.append(col.rgb)

            self.client.put_pixels(pixels, channel=1)
            time.sleep(1 / fps)
Esempio n. 7
0
def get_string(img_path):

    # Read image with opencv
    img = cv2.imread(img_path)

    # Convert to gray
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply dilation and erosion to remove some noise
    kernel = np.ones((1, 1), np.uint8)
    img = cv2.dilate(img, kernel, iterations=1)
    img = cv2.erode(img, kernel, iterations=1)

    # Write image after removed noise
    cv2.imwrite(src_path + "removed_noise.png", img)

    #  Apply threshold to get image with only black and white
    img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                cv2.THRESH_BINARY, 31, 2)

    # Write the image after apply opencv to do some ...
    cv2.imwrite(src_path + "thres.png", img)

    im = Image.open(src_path + "thres.png")

    width, height = im.size

    rgb_im = im.convert('RGB')

    for pixel_x in range(0, width):
        for pixel_y in range(0, height):
            r, g, b = rgb_im.getpixel((pixel_x, pixel_y))
            hexColor = Color((r, g, b))
            colorX.append(hexColor.red)
Esempio n. 8
0
    def __init__(self, game, AI, color=None, *groups):
        super().__init__(*groups)
        self.game = game
        self.AI = AI
        self.alive = True

        self.immunity = False
        self.alive_time = 0
        self.points = 0
        self.finishing_seq = [0, 1]
        self.finished = False
        self.previous_goal = None
        self.goals = game.goals  # {1: game.starting_line, 0: game.finish_line}
        self.checkpoints_reached = set()

        self.speed_boost = False

        self.color = Color(tuple(np.random.randint(
            256, size=3))) if not color else color
        self.image = self.original = pygame.Surface([Car.HEIGHT, Car.WIDTH])
        self.image.fill(self.color.rgb)
        self.image.set_colorkey((255, 0, 0))

        self.rect = self.image.get_rect(center=(421, 115))
        self.accel = pygame.Vector2(0, 0)
        self.speed = pygame.Vector2(0, 0)
        self.direction = self.original_dir = pygame.Vector2(1, 0)
        self.angle = 0
Esempio n. 9
0
 def hex_to_rgba(self, color_values):
     colors = [Color(hex=color_hex) for color_hex in color_values]
     rgba_base_pair_map = {
         'A': colors[0],
         'C': colors[1],
         'G': colors[2],
         'T': colors[3]
     }
     return rgba_base_pair_map
Esempio n. 10
0
    def next_frame(self, octopus, data):

        self.mid = (self.mid + 1) % 255

        for pixel in octopus.pixels():
            p = (self.mid + random.randint(1, 40)) % 255
            col = Color(hsv=(p, random.uniform(0.2, 0.8),
                             random.uniform(0.2, 0.8)))
            pixel.color = (col.rgb)
Esempio n. 11
0
 def add_color_page(self, name, color):
     self.add_page()
     self.set_font("Liberation Serif", "", 16)
     background_color = Color(hex=color)
     self.set_fill_color(background_color.red, background_color.green,
                         background_color.blue)
     #self.cell(0, 510, "", 0, 2, "C", True)
     self.cell(218, 510, "", 0, 2, "C",
               True)  # 218pt is half width of the WirMachenDruck A5 page
     self.cell(0, 25, name + "  " + color, 0, 1, "C")
Esempio n. 12
0
 def __init__(self):
     threading.Thread.__init__(self)
     self.stopped = False
     self.end_thread = False
     self.config = getClockConfiguration()
     self.stop_cond = threading.Condition(threading.Lock())
     self.led_ctrl = led_ct.Controller(self.config.pixelCount,
                                       Color(hex=self.config.color).rgb,
                                       self.config.brightness)
     self.generate_leds()
Esempio n. 13
0
def change_color(color_hex):
    if color_hex == "":
        logging.warn("Tried to change leds color without value")
        abort(400, description="Changing leds color requires a not empty string value")
    
    match = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', color_hex)
    if not(match):
        logging.warn("Color input value [{}] isn't a valid hex color value".format(str(color_hex)))
        abort(400, description="Color param is invalid. You must provide a valid hex color value")
    color = Color(hex=color_hex)
    clock.change_color(color.rgb)
Esempio n. 14
0
class LightChanger:

    exec_path = "C:/Users/grego/workspace/exec-assistant/C#/MSI-Mystic-Light-Controller/SetLEDsGreen/Deployment/netcoreapp3.1/SetLEDsGreen.exe"
    RED = Color((255, 0, 0))
    GREEN = Color((0, 255, 0))
    YELLOW = Color((255, 255, 0))

    def set_green(self):
        return self.set_color(self.GREEN)

    def set_red(self):
        return self.set_color(self.RED)

    def set_yellow(self):
        return self.set_color(self.YELLOW)

    def set_color(self, color):
        color_args = " " + str(color.red) + " " + str(color.green) + " " + str(
            color.blue)
        command = self.exec_path + color_args
        return subprocess.call(args=command)
Esempio n. 15
0
    def calc(self, name):
        if self.blocks[name] == 0:
            self.canvas.itemconfig(self.triangles[name + "2"],
                                   fill=gray,
                                   stipple='')
            self.present[name] = black
        if self.blocks[name] == 1:
            self.canvas.itemconfig(self.triangles[name + "2"],
                                   fill=colors[name],
                                   stipple="gray25")
            # self.canvas.itemconfig(self.triangles[name + "2"], fill=colors[name+'3'])#, stipple="gray25")
        if self.blocks[name] == 2:
            self.canvas.itemconfig(self.triangles[name + "2"],
                                   fill=colors[name],
                                   stipple="gray50")
            # self.canvas.itemconfig(self.triangles[name + "2"], fill=colors[name+'2'])#, stipple="gray50")
        if self.blocks[name] == 3:
            self.canvas.itemconfig(self.triangles[name + "2"],
                                   fill=colors[name],
                                   stipple="gray75")
            # self.canvas.itemconfig(self.triangles[name + "2"], fill=colors[name+'1'])#, stipple="gray75")
            # self.present[name] = colors[name+'1']
        if self.blocks[name] == 4:
            self.canvas.itemconfig(self.triangles[name + "2"],
                                   fill=colors[name],
                                   stipple='')
            self.present[name] = colors[name]

        out = black
        my_list = []
        for key, color in self.present.items():
            hex_color = hex_to_rgb(color)
            item = hex_color + (0.5, 0)
            my_list.append(item)
            out = rgb_to_hex((Color(hex=color) + Color(hex=out)))

        # r_mix, g_mix, b_mix = colorme(list)
        #
        # Color((r_mix, g_mix, b_mix))
        self.canvas.itemconfig(self.ovals['o'], fill=out)
Esempio n. 16
0
def get_hsv_from_file(hsv_file):

    hsv_list = list()

    with open(hsv_file, "r") as f:
        hex_values = f.read().splitlines()
    for hex_value in hex_values:
        hsv = list(Color(hex=hex_value).hsv)
        hsv[0] /= 2
        hsv[1] *= 255
        hsv[2] *= 255
        hsv_list.append(hsv)
    return hsv_list
Esempio n. 17
0
from asciistuff import Banner

from colorutils import Color

c = Color((255, 255, 255))

for i in range(10, 0, -1):
    print(i, "...")

print(Banner("Universidad Nacional Autonoma de Mexico!!"))
"""
from asciistuff import Banner
from colorutils import Color

c = Color ((255,255,255))

print(Banner("Universidad Nacional Autonoma de Mexico")
"""
Esempio n. 18
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Primary Color Palette
"""
from colorutils import Color

red = Color((255, 0, 0))
yellow = Color((255, 255, 0))
blue = Color((0, 0, 255))

all = [red, yellow, blue]
Esempio n. 19
0
def event(year, name):
    # hard-code import of kook drafts while I don't have
    # a database set up for that info yet
    from app.kooks import kooks
    event_name = name
    event = wsl.Event.query.filter_by(year=year, name=event_name).first()

    def find_color_for_athlete(athlete_name):
        '''
    quick utility function for finding the color
    to assign to an athlete's box based on the
    kook that drafted them
    '''
        if wsl._is_placeholder_athlete_name(athlete_name):
            return "#bbbbbb"

        for kook, attrs in kooks.items():
            if athlete_name in attrs["athletes"]:
                return attrs["color"]
        else:
            raise ValueError(
                "Could not find kook with athlete {}".format(athlete_name))

    # top section of event page will be a large table displaying
    # the heat-by-heat results from an event.
    # attributes of cells in this table with be either `table`,
    # if there's a table to display, or `title`, a special
    # attribute reserved for the first row so that we know
    # how many round columns to create
    first_row = []
    for n, _ in enumerate(event.rounds):
        cell = {"table": False, "title": "Round {}".format(n + 1)}
        first_row.append(cell)
    rows = [first_row]

    for round in event.rounds:
        if not round.completed and not client.sleeping:
            round.update()

    # now piece together each row of the table separately
    heat_winning_scores = {}
    num_rows = max([len(round.heats.all()) for round in event.rounds])
    for i in range(num_rows):
        row = []
        for round in event.rounds:
            # try to get the heat for this row. If there aren't enough,
            # then we'll just leave it blank
            try:
                heat = round.heats[i]
            except IndexError:
                row.append({"table": False, "title": False})
                continue

            # now build this table for this table *element*
            # record the winning score so that we can circle the
            # corresponding box
            table = []
            max_score = max([result.score or 0 for result in heat.athletes])
            heat_winning_scores[heat.id] = max_score
            for result in heat.athletes:
                name = result.athlete.name
                background = find_color_for_athlete(name)
                alpha_values = ["55", "bb", "ff"]
                background += alpha_values[heat.status]

                h, s, v = Color(hex=background).hsv
                text_color = "#ffffff" if v < 0.3 else "#000000"

                winner = (result.score == max_score) and heat.completed
                border = "5px solid #000000" if winner else "1px solid #ffffff"
                table.append({
                    "name": name,
                    "background": background,
                    "score": result.score,
                    "text": text_color,
                    "border": border
                })
            row.append({"table": table, "title": False})
        rows.append(row)

    _SCORE_BREAKDOWN = [265, 1330, 3320, 4745, 6085, 7800, 10000]
    kook_rows = []
    idx, row = 0, []
    for kook, attrs in kooks.items():
        h, s, v = Color(hex=attrs["color"]).hsv
        text_color = "#ffffff" if v < 0.3 else "#000000"
        kook_dict = {
            "background": attrs["color"],
            "text": text_color,
            "name": kook
        }

        total_score, athletes = 0, []
        for athlete_name in attrs["athletes"]:
            athlete = wsl.Athlete.query.filter_by(name=athlete_name).first()
            for n, round in enumerate(event.rounds[2:]):
                for heat in round.heats:
                    heat_result = wsl.HeatResult.query.filter_by(
                        athlete_id=athlete.id, heat_id=heat.id).first()
                    if heat_result is not None:
                        if n == (len(list(event.rounds)) - 3):
                            n += 1
                            winning_score = heat_winning_scores[heat.id]
                            if heat_result.score == winning_score:
                                n += 1
                        break
                else:
                    break

            score = _SCORE_BREAKDOWN[n]
            total_score += score
            athletes.append({"name": athlete_name, "score": score})

        kook_dict["score"] = total_score
        kook_dict["athletes"] = athletes

        # reset row after every 3. TODO: something more robust here
        # for configurable competitor sizes and displays
        row.append(kook_dict)
        idx += 1
        if idx == 3:
            kook_rows.append(row)
            idx, row = 0, []

    event_name = event_name.replace('-', ' ').title()
    event_name = '{} {}'.format(event_name, year)
    return render_template('event.html',
                           event_name=event_name,
                           rows=rows,
                           kook_rows=kook_rows)
Esempio n. 20
0
def ReadNetwork(root, fl='coOccurrence.npz', cutoff=100, verbose=1):
    '''Reads the network and outputs a networkx graph instance'''
    mat = scipy.sparse.load_npz('{}/{}'.format(root, fl)).tocsr()
    labels = []
    lines = open('{}/UIsMapped.txt'.format(root)).read().split('\n')
    for i in range(0, len(lines)):
        line = lines[i].split('\t')
        if len(line) > 1:
            labels.append(line[1])
    labels = np.array(labels)
    # eliminate diagonal as it stores the degree
    mat.setdiag(0)
    mat.eliminate_zeros()

    # Eliminate nodes with Unknown labels
    mask = labels != 'Unknown'
    mat = mat[:, mask][mask, :]
    labels = labels[mask]

    # eliminate edges that are low confidence
    matShape = mat.shape
    nonzero = (mat > cutoff).nonzero()
    vals = mat[nonzero]
    mat = scipy.sparse.coo_matrix((vals.A1, nonzero), shape=matShape).tocsr()

    # Get rid of low degree nodes
    while np.sum(
            mat.astype(bool).sum(axis=1) < 4
    ) > 0:  # while loop as some <4 degree nodes are linked to degree 5 nodes
        degreeMask = mat.astype(bool).sum(axis=1) >= 4
        mat = mat[:, degreeMask.A1][degreeMask.A1, :]
        labels = labels[degreeMask.A1]

    nonzero = scipy.sparse.tril(
        mat, k=-1).nonzero()  # use only the lower triangle minus the diagonal

    ind1 = nonzero[0]  #[mask.A1]
    ind2 = nonzero[1]  #[mask.A1]

    if verbose:
        print('Iterating over {} edges'.format(ind1.shape))

    c = Counter(labels)
    # Make network
    net = nx.Graph()
    #nonNormnet=nx.Graph()

    colorLs = ['Chemical', 'Disease', 'Gene']
    colors = [
        Color(rgb=[230, 159, 0]),
        Color(rgb=[86, 180, 223]),
        Color(rgb=[0, 158, 115]),
        Color(rgb=[240, 228, 66]),
        Color(rgb=[0, 114, 178]),
        Color(rgb=[213, 94, 0])
    ]  # color blind safe palette
    colorcomb = list(itertools.combinations_with_replacement(colorLs, 2))
    #factors=[0.05,0.2,1,0.2,1,1]
    #print(colorcomb)
    for i, j in zip(ind1, ind2):
        w = mat[i, j]
        l1 = labels[i]
        l2 = labels[j]
        net.add_node(i, style='invis')
        net.add_node(j, style='invis')
        #nonNormnet.add_node(i,style='invis')
        #nonNormnet.add_node(j,style='invis')

        try:
            color = colors[colorcomb.index((l1, l2))]
            #factor=100/factors[colorcomb.index((l1,l2))]
        except:
            color = colors[colorcomb.index((l2, l1))]
            #factor=100/factors[colorcomb.index((l2,l1))]

        net.add_edge(i,
                     j,
                     weight=w,
                     label1=l1,
                     label2=l2,
                     color='{}'.format(color.hex))
        #nonNormnet.add_edge(i,j,weight=w/100,label1=l1,label2=l2,color='{}'.format(color.hex))

    return net
Esempio n. 21
0
def draw_text(draw, title, title_size, subtitle, subtitle_size):
    font_title = ImageFont.truetype(
        "assets/fonts/WDRSlab-BoldVZ-v101.ttf", size=title_size
    )
    font_subtitle = ImageFont.truetype(
        "assets/fonts/WDR Sans Book.ttf", size=subtitle_size
    )

    spacing_title = int(title_size / 5)
    spacing_subtitle = int(subtitle_size / 5)

    calc_size_title = draw.textsize(
        re.sub(".", "M", title), font=font_title, spacing=spacing_title
    )
    calc_size_subtitle = draw.textsize(
        re.sub(".", "M", subtitle), font=font_subtitle, spacing=spacing_subtitle
    )

    y_offset = int(img_height * 0.03) + spacing_title
    gradient_width = img_widths[Mode.SQUARE] / TARGET_WIDTH_SQUARE * 35

    x0 = 0
    y0 = (
        img_height
        - y_offset
        - ((calc_size_subtitle[1] + spacing_title * 2) if subtitle else 0)
        - calc_size_title[1]
        - spacing_title * 4
    )
    x1 = gradient_width
    y1 = img_height - y_offset

    start = Color(hex=COLORS["GRADIENT"]["start"]).rgb
    end = Color(hex=COLORS["GRADIENT"]["end"]).rgb

    for line in range(y0, y1):
        fac = (line - y0) / (y1 - y0)
        color = Color(tuple(s * fac + e * (1 - fac) for s, e in zip(start, end)))
        draw.line(((x0, line), (x1, line)), fill=color.hex)

    x = gradient_width + spacing_title * 2
    y = (
        img_height
        - y_offset
        - ((calc_size_subtitle[1] + spacing_title * 2) if subtitle else 0)
        - spacing_title * 2
        - calc_size_title[1]
    )
    draw.text(
        (x, y),
        title,
        align="left",
        fill=COLORS["TEXT"],
        font=font_title,
        spacing=spacing_title,
    )

    y = img_height - y_offset - calc_size_subtitle[1] - spacing_title * 2
    draw.text(
        (x, y),
        subtitle,
        align="left",
        fill=COLORS["TEXT"],
        font=font_subtitle,
        spacing=spacing_subtitle,
    )
Esempio n. 22
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Secondary Color Palette
"""
from colorutils import Color

green = Color((0, 255, 0))
purple = Color((128, 0, 128))
orange = Color((255, 165, 0))

all = [green, purple, orange]
Esempio n. 23
0
from colorutils import Color
import replacement
from replacement import Replacer
import tkinter as tk

#newReplacer = Replacer()

#Using colorutils
buttonColor = Color((110, 190, 250))

#instantiation
window = tk.Tk()
window.geometry("400x400")

#strings lolw
theText = tk.StringVar()
replacedWord = tk.StringVar()
replacementWord = tk.StringVar()


#the main f****r
def Replace():
    #Get rid of any previous replacements
    theNewText.delete("0.0", tk.END)

    #converting tkinter shit into strings
    entireText = theWholeText.get()
    getReplacedWord = replacedWord.get()
    getReplacementWord = replacementWord.get()

    #replacement
def gen_plot(opt, affect_x, affect_y, cat_type, top_speakers, skip_by):
    ax_axis = [i - (opt.window_size - 1) for i in affect_x.keys()]
    affect_y = copy.deepcopy(affect_y)
    print('Converting points to percentages for cat_type ' + str(cat_type) +
          '...')
    for user in tqdm(top_speakers):
        tay = []
        for i in range(len(ax_axis)):
            tindex = int(i * 1.0 / len(ax_axis) *
                         len(affect_y[user][cat_type]))
            # print('tindex is ' + str(tindex))
            # print('userlen: ' + str(len(affect_y[user])))
            tay.append(affect_y[user][cat_type][tindex] * 100.0 /
                       opt.window_size)
        affect_y[user][cat_type] = tay

        # SKIP BY
        t_affect_y = []
        for i in range(0, len(affect_y[user][cat_type]), skip_by):
            t_affect_y.append(affect_y[user][cat_type][i])
        affect_y[user][cat_type] = t_affect_y
    ax_axis = range(len(affect_y[user][cat_type]))

    # affect_y[user].extend([0]*(len(ax_axis) - len(affect_y[user])))
    # print('afy: ' + str(affect_y[user][cat_type]))

    # ay_avg = [np.average([affect_y[user][cat_type][i] for user in top_speakers if affect_y[user][cat_type][i] > 0]) for i in range(len(ax_axis))]
    # ay_std = [np.std([affect_y[user][cat_type][i] for user in top_speakers if affect_y[user][cat_type][i] > 0]) for i in range(len(ax_axis))]
    # num_users = [np.sum([1 for user in top_speakers if affect_y[user][cat_type][i] > 0]) for i in range(len(ax_axis))]
    # ay_above = np.array(ay_avg) + np.array(ay_std)
    # ay_below = np.array(ay_avg) - np.array(ay_std)

    ay_avg = []
    ay_above = []
    ay_below = []
    sum_bins = [0, 0, 0, 0]
    for i in range(len(ax_axis)):
        tarr = [
            affect_y[user][cat_type][i] for user in top_speakers
            if affect_y[user][cat_type][i] > 0
        ]
        # ay_avg.append(np.average(tarr))
        # print(tarr)
        if tarr == []:
            ay75, ay50, ay25 = 0, 0, 0
        else:
            ay75, ay50, ay25 = np.percentile(tarr, [75, 50, 25])
        # print('ay75: ' + str(ay75))
        # print('ay50: ' + str(ay50))
        # print('ay25: ' + str(ay25))
        # print('np.average: ' + str(np.average(tarr)))
        ay_above.append(ay75)
        ay_below.append(ay25)
        ay_avg.append(ay50)
        sum_bins[int(i / (len(ax_axis) / len(sum_bins)))] += ay50

    color_fill = Color(random_rgb())
    color_edge = color_fill - Color((16, 16, 16))

    x_min = min(ax_axis)
    x_max = max(ax_axis)

    if opt.aggregate_stats:
        plt.plot(ax_axis,
                 ay_avg,
                 c=[cc * 1.0 / 255 for cc in color_edge.rgb],
                 label='Median')
        # plt.plot(ax_axis, ay_above, c=np.random.rand(3,), label='+std')
        # plt.plot(ax_axis, ay_below, c=np.random.rand(3,), label='-std')
        plt.fill_between(ax_axis,
                         ay_below,
                         ay_above,
                         alpha=0.5,
                         edgecolor=color_edge.hex,
                         facecolor=color_fill.hex)
        # plt.plot(ax_axis, num_users, c='black', label='Number of Users')
        print('median line: ' + ''.join([
            '(' + str(xiz[0]) + ',' + str(xiz[1]) + ')'
            for xiz in zip(ax_axis, ay_avg)
        ]))
        print('iqr3: ' + ''.join([
            '(' + str(xiz[0]) + ',' + str(xiz[1]) + ')'
            for xiz in zip(ax_axis, ay_above)
        ]))
        print('iqr1: ' + ''.join([
            '(' + str(xiz[0]) + ',' + str(xiz[1]) + ')'
            for xiz in zip(ax_axis, ay_below)
        ]))
    else:
        for user in top_speakers:
            plt.plot(ax_axis, affect_y[user][cat_type], c=np.random.rand(3, ))

    plt.xlabel('Distance of Sliding Window from Most Similar Words')
    plt.ylabel('Percentage of Words in Category')
    plt.xticks([
        x_min, (x_min + x_max) / 4, (x_min + x_max) / 2,
        (x_min + x_max) / 4 * 3, x_max
    ], ['0%', '25%', '50%', '75%', '100%'])
    plt.legend()
    return sum_bins
Esempio n. 25
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ROYGBV Color Palette
"""
from colorutils import Color

red = Color((255, 0, 0))
orange = Color((255, 165, 0))
yellow = Color((255, 255, 0))
green = Color((0, 255, 0))
blue = Color((0, 0, 255))
violet = Color((238, 130, 238))

all = [red, orange, yellow, green, blue, violet]
Esempio n. 26
0
def colorArray(hue):
  arr=[]
  for i in range(9): # pick the number of shades
     c=Color(hsv=(hue, random.randint(22,100)/100, random.randint(22,100)/100)) # 0 would include black too
     arr.append((int(c.red),int(c.green), int(c.blue))) 
  return arr
Esempio n. 27
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
RGB Color Palette
"""
from colorutils import Color

red = Color((255, 0, 0))
green = Color((0, 255, 0))
blue = Color((0, 0, 255))

all = [red, green, blue]
Esempio n. 28
0
from colorutils import Color, ArithmeticModel
import matplotlib.colors as mcolors

color_list = [
    "dodgerblue", "orangered", "lightgreen", "mediumorchid", "gold",
    "firebrick", "darkorange", "springgreen", "lightcoral"
]
color_list2 = list(mcolors.CSS4_COLORS)
primary_colors = {
    "d": Color(web="#e3c44c", arithmetic=ArithmeticModel.BLEND),
    "a": Color(web="#d73824", arithmetic=ArithmeticModel.BLEND),
    "c": Color(web="#66CB5E", arithmetic=ArithmeticModel.BLEND),
    "b": Color(web="#6e91ee", arithmetic=ArithmeticModel.BLEND)
}
Esempio n. 29
0
def hex_from_color(color):
    color = 255 * np.minimum(color, np.ones(3))
    return Color((int(color[0]), int(color[1]), int(color[2]))).hex
Esempio n. 30
0
def UpdateActivityAssignmentsUI():
    print("Updating Activity Students")
    stuMaxChoice = len(allStudents[0].choices[0])
    for act in allActivities:
        act.stuNameFrame.destroy()
        act.stuNameFrame = Frame(act.stuNameParentFrame)
        act.stuNameFrame.pack()

        count = 0
        n = 0

        for stu in act.assigned:
            choiceIndex = 0
            for acts in stu.choices[act.period]:
                if (acts.name == act.name):
                    break
                choiceIndex += 1

            print("For act " + act.name + " with " + str(act.assignedCount) +
                  " - " + str(len(act.assigned)) + " assigned, adding " +
                  stu.name + " - " + str(choiceIndex))
            myC = Color(hsv=(((stuMaxChoice - choiceIndex) / stuMaxChoice) *
                             120, 1, 1))
            Label(act.stuNameFrame,
                  text=str(stu.grade) + " - " + stu.name,
                  relief=GROOVE,
                  width=15,
                  bg=myC.hex).grid(column=n % 11,
                                   row=math.floor(n / 11),
                                   ipadx=3,
                                   ipady=3,
                                   padx=3,
                                   pady=3)
            count += 1
            n += 1

            if (count == slotMultipliers[0][0]):
                Frame(act.stuNameFrame,
                      width=8,
                      height=15,
                      relief=GROOVE,
                      bg="#80ffd9").grid(column=n % 11,
                                         row=math.floor(n / 11),
                                         sticky=N + S)  # blue
                n += 1
            elif (count == slotMultipliers[1][0]):
                Frame(act.stuNameFrame,
                      width=8,
                      height=15,
                      relief=GROOVE,
                      bg="#93ff80").grid(column=n % 11,
                                         row=math.floor(n / 11),
                                         sticky=N + S)  # green
                n += 1
            elif (count == slotMultipliers[2][0]):
                Frame(act.stuNameFrame,
                      width=8,
                      height=15,
                      relief=GROOVE,
                      bg="#fffd80").grid(column=n % 11,
                                         row=math.floor(n / 11),
                                         sticky=N + S)  # yellow
                n += 1

        if (count > slotMultipliers[2][0]):
            Frame(act.stuNameFrame,
                  width=8,
                  height=15,
                  relief=GROOVE,
                  bg="#ff8080").grid(column=n % 11,
                                     row=math.floor(n / 11),
                                     sticky=N + S)  # red
            n += 1