def wavelet_ricker_series():
    n_lines = 15
    n_points = 100
    max_offset = 800

    hue = np.random.choice(['blue', 'purple', 'red'])
    luminosity = None
    rand_color = randomcolor.RandomColor()
    background_color = np.array(
        rand_color.generate(
            hue=hue, luminosity=luminosity, format_='Array_rgb')) / 256.
    plt.rcParams["figure.facecolor"] = background_color[0]
    fig, axes = plt.subplots(n_lines, sharex=True, frameon=True)
    offset = 1
    rand_color = randomcolor.RandomColor()
    value = 1.0

    for ax in axes:
        for _ in range(5):
            x_offset = np.random.uniform(0, max_offset)
            a = np.random.uniform(1, 5)
            n_points /= 2.
            color_rgb = np.array(
                rand_color.generate(hue=hue,
                                    luminosity=luminosity,
                                    format_='Array_rgb')) / 256.
            color_rgb = color_rgb[0]
            color_hsv = color.rgb2hsv(color_rgb)
            color_hsv[2] *= 0.4 + 0.6 * x_offset / max_offset
            color_rgb = color.hsv2rgb(color_hsv)

            ax.axis('off')
            n_points = 500
            sample_frac = 0.1
            mode = np.random.uniform(0, n_points)
            x = np.random.triangular(0,
                                     mode,
                                     n_points,
                                     size=int(n_points * sample_frac))
            x = [int(i) for i in x]
            y = signal.ricker(int(n_points), 25)
            y = y[x]

            ax.scatter(x_offset + np.array(x),
                       90 * y,
                       color=color_rgb,
                       s=10.0,
                       alpha=0.99)
            # ax.set_aspect(2)
            offset += 3
            # ax.set_xlim(0, 500)
    fig.set_figheight(5)
    # fig.set_figwidth(4)

    plt.show()
Exemple #2
0
	def random_color(self):
		'''
		Generates random colors for moving averages
		'''
		random_color = randomcolor.RandomColor().generate()

		while random_color in self.colors_used:
			random_color = randomcolor.RandomColor().generate()
		self.colors_used.append(random_color)
		
		return random_color
def fun_squiggles():
    n_lines = 5

    hue = np.random.choice(['blue', 'purple', 'red', 'green'])

    luminosity = None
    fig, axes = plt.subplots(1, n_lines)
    rand_color = randomcolor.RandomColor()
    background_color = np.array(
        rand_color.generate(
            hue=hue, luminosity=luminosity, format_='Array_rgb')) / 256.
    plt.rcParams["figure.facecolor"] = background_color[0]

    for axes_index in range(n_lines):

        axes[axes_index].axis('off')
        rand_color = randomcolor.RandomColor()
        color_rgb = np.array(
            rand_color.generate(
                hue=hue, luminosity=luminosity, format_='Array_rgb')) / 256.
        color_rgb_background = color_rgb[0]
        color_rgb = np.array(
            rand_color.generate(
                hue=hue, luminosity=luminosity, format_='Array_rgb')) / 256.
        color_rgb = color_rgb[0]
        color_hsv = color.rgb2hsv(color_rgb_background)
        color_hsv[2] *= 0.95

        t = np.linspace(0, 10, 1500)
        w = chirp(t, f0=6, f1=1, t1=10, method='linear')

        axes[0].plot(t, w, color=color_rgb)
        axes[0].set_facecolor(color_rgb_background)

        top_freq = np.random.uniform(30, 80)
        widths = np.arange(1, top_freq)
        cwtmatr = signal.cwt(w, signal.ricker, widths)

        for item in cwtmatr:
            color_rgb = np.array(
                rand_color.generate(hue=hue,
                                    luminosity=luminosity,
                                    format_='Array_rgb')) / 256.
            axes[axes_index].plot(item, range(len(item)), color=color_rgb[0])
            height = np.max(item) - np.min(item)
            x_min = np.random.uniform(np.min(item), np.max(item) * 0.8)
            if axes_index == 0:
                x_min = np.min(item)  # + 0.1 * height

            if axes_index == n_lines - 1:
                x_max = np.max(item)  # - 0.1 * height
            x_max = x_min + 0.25 * height
            axes[axes_index].set_xlim(x_min, x_max)
Exemple #4
0
def get_colors(label_number=41, binary=True):
    import randomcolor
    rand_color = randomcolor.RandomColor()
    colors = rand_color.generate(count=label_number)
    if binary:
        b_colors = {'true':'green','false':'r'}
    return colors, b_colors
    def __init__(self, num_classes, bgr=False):
        # Generate color for each class
        rand_color = randomcolor.RandomColor()
        colors = rand_color.generate(luminosity='bright',
                                     count=num_classes,
                                     format_='rgb')

        # Class map dictionary
        self.__class_map = {}
        class_id = 0

        # RGB string to R, G, B values
        p = re.compile(r'rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)')

        # Populate dictionary
        for color in colors:
            matches = p.findall(color)
            r, g, b = matches[0]

            if bgr:
                class_color = (int(b), int(g), int(r))
            else:
                class_color = (int(r), int(g), int(b))

            self.__class_map[class_id] = {}
            self.__class_map[class_id]['color'] = class_color

            class_id += 1
Exemple #6
0
    def def_structure(self, structure: str, parts: list):
        """Define parts in a structure and color the structure and parts.

        Assign parts to be members of a structure. Every structure is
        assigned a hue; the level 1 structure is assigned a color and
        all level 2 parts are assigned a color, all in the same hue
        for clarity. Should have # of structures <= 7 to avoid reusing
        hues.

        """
        index = len(self.parts)  # Number of structures defined previously
        rand_color = randomcolor.RandomColor()
        hues = ['red', 'green', 'blue', 'purple', 'yellow', 'orange', 'pink']
        if index >= len(hues):
            index %= len(hues)
            print("labels: WARNING: reusing hue '{:s}'".format(hues[index]))

        self.parts[structure] += parts
        self.levels[1][structure] = rand_color.generate(hue=hues[index],
                                                        luminosity='bright')[0]
        for part, color in zip(
                parts,
                rand_color.generate(hue=hues[index],
                                    count=len(parts),
                                    luminosity='bright')):
            self.levels[2][part] = color
Exemple #7
0
    def plot(self, x_index, y_index):
        """
        Generates 2D graph of distribution components of the of Gaussian Mixture model.

        Parameters
        ----------
        x_index : int
            Index of sample point to represent the x-axis value.
        y_index : int
            Index of sample point to represent the y-axis value.
        """
        rand_color = randomcolor.RandomColor()
        colors = [colorConverter.to_rgb(rand_color.generate()[0]) for n in enumerate(range(0, self.gmm.n_components))]
        fig = plt.figure(figsize=(10, 10))
        ax = plt.subplot(111)

        X = self.observation_vectors
        labels = self.gmm.model.predict(self.observation_vectors)

        self.__make_ellipses(self.gmm.model, ax, colors)
        for n, color in enumerate(colors):
            data = X[np.where(labels == n)]
            plt.scatter(data[:, x_index], data[:, y_index], s=0.8, color=color)
        plt.xticks(())
        plt.yticks(())
        plt.show()
Exemple #8
0
    def plot(self, x_index, y_index, z_index):
        """
        Generates 3D graph of the clusters of KMeans model

        Parameters
        ----------
        x_index : int
            Index of sample point to represent the x-axis value.
        y_index : int
            Index of sample point to represent the y-axis value.
        z_index : int
            Index of sample point to represent the z-axis value.
        """
        labels = self.kmm.model.labels_
        centroids = self.kmm.model.cluster_centers_

        rand_color = randomcolor.RandomColor()
        colors = [colorConverter.to_rgb(rand_color.generate()[0]) for n in enumerate(range(0, self.kmm.n_clusters))]

        fig = plt.figure(figsize=(10, 10))
        ax = Axes3D(fig)
        ax.autoscale_view()

        X = self.observation_vectors

        for n, color in enumerate(colors):
            data = X[np.where(labels == n)]
            ax.scatter(data[:, x_index], data[:, y_index], data[:, z_index], color=color)
        ax.scatter(centroids[:, x_index], centroids[:, y_index], centroids[:, z_index], marker="x", s=150, linewidths=5, zorder=100)
        ax.autoscale(enable=False, axis='both')
        plt.show()
Exemple #9
0
def main():
    if not os.path.exists(DATASET_FOLDER):
        print("Dataset not found")
        return

    imgpaths = []
    classes = []
    classes_set = []

    with open(DATASET_FOLDER + VALIDATION_NAME, 'r') as csvfile:
        trainreader = csv.reader(csvfile)
        headers = next(trainreader, None)
        for row in trainreader:
            imgpaths.append(row[0])
            classes.append(row[1])
            if row[1] not in classes_set:
                classes_set.append(row[1])

    if len(imgpaths) != len(classes):
        print("Wrong sizes between imgpaths and classes.")

    rand_color = randomcolor.RandomColor()
    colors = rand_color.generate(luminosity='bright', count=len(classes_set))

    colors_dict = {cl: color for (cl, color) in zip(classes_set, colors)}

    aspectratios = []  # (w/h, color)
    aspectratios.extend(
        Parallel(n_jobs=NUM_PROCESSOR)(
            delayed(aspectratio)(img_file, cl, colors_dict)
            for (img_file, cl) in zip(imgpaths, classes)))
    random.shuffle(aspectratios)
    drawaspectratios(aspectratios, colors_dict)
Exemple #10
0
def random_colors(count):
    rand_color = randomcolor.RandomColor()
    random_colors = [
        map(int, rgb_str[4:-1].replace(',', ' ').split()) for rgb_str in
        rand_color.generate(luminosity="bright", count=count, format_='rgb')
    ]
    return random_colors
Exemple #11
0
def gif_flicker_custom(code,
                       outputfile,
                       field_width=30,
                       space_width=15,
                       height=50,
                       wait=50):
    color_count = 4

    data = swap_bytes(code)

    stream = []

    for j in range(0, color_count):
        for i in range(color_count - 1, -1, -1):
            stream.append(str(i) + str(j) * 4)

    stream.append(str(color_count - 1) * 5)

    hex_count = math.floor(math.log(color_count**4, 16))

    for i in range(0, len(data), hex_count):
        c = data[i:i + hex_count]
        v = int(c, 16)
        v = base_convert(v, color_count).zfill(4)[::-1]

        for i in range(color_count - 1, -1, -1):
            stream.append(str(i) + v)

    width = 5 * field_width + 6 * space_width
    images = []

    rand_color = randomcolor.RandomColor()
    colors = rand_color.generate(count=color_count, format_='rgb')
    #print(stream)
    for frame in stream:
        im = Image.new('RGB', (width, height), colors[0])
        draw = ImageDraw.Draw(im)

        x = space_width
        for c in frame:
            draw.rectangle([(x, 0), (x + field_width, height)],
                           fill=colors[int(c, color_count)],
                           width=0)

            x += space_width + field_width

        im = im.convert('P',
                        dither=None,
                        palette=Image.ADAPTIVE,
                        colors=color_count)

        images.append(im)

    images[0].save(outputfile,
                   save_all=True,
                   append_images=images[1:],
                   optimize=False,
                   duration=wait,
                   loop=0,
                   disposal=2)
Exemple #12
0
    def paint_graph(self, location, graph, communities):

        sys.stdout.write('Drawing graph ... ')
        sys.stdout.flush()
        network = gt.Graph(graph, directed=False)
        folder = os.path.abspath(self._output_dir)

        r_cols = randomcolor.RandomColor().generate(count=len(communities) + 1)
        colors = [
            list(int(r_col[1:][i:i + 2], 16) for i in (0, 2, 4))
            for r_col in r_cols
        ]

        color = network.new_vertex_property('int')

        base_color = colors.pop()
        for v in network.vertices():
            color[v] = (base_color[0] << 16) + (
                base_color[1] << 8) + base_color[2]
        for community in communities:
            c = colors.pop()
            for v in community:
                color[v] = (c[0] << 16) + (c[1] << 8) + c[2]
        pos = gt.sfdp_layout(network)
        gt.graph_draw(network,
                      pos=pos,
                      vertex_fill_color=color,
                      output=os.path.join(
                          folder,
                          str(len(communities)) + '_' + location +
                          '_graph-communities.svg'))
        sys.stdout.write('Ok!\n')
        sys.stdout.flush()
Exemple #13
0
def process(data, threshold, size):
    cord_lst, cord_id = extract_cords(data)
    clusters, n_clusters = dbscan(cord_lst, threshold, size)
    #colorset
    rand_color = randomcolor.RandomColor()
    color_lst = rand_color.generate(count=n_clusters)
    #generate geojson
    features = []
    for i in range(len(clusters)):
        if clusters[i].size:
            cords = clusters[i].tolist()
            cords_set = set()
            for cord in cords:
                cords_set.add(tuple(cord))
            if i != 0:
                top_keywords = process_text(list(cords_set), cord_id)
                summary = "Number of posts: " + str(
                    len(cords)) + ", Top 10 Keywords:"
                for keyword, frequency in top_keywords:
                    summary = summary + " " + keyword + "(" + str(
                        frequency) + ")"
            cord_mp = MultiPoint(list(cords_set))
            if i == 0:
                feature = Feature(geometry=cord_mp,
                                  properties={"color": "#826969"})
            else:
                feature = Feature(geometry=cord_mp,
                                  properties={
                                      "color": color_lst[i - 1],
                                      "summary": summary
                                  })
            features.append(feature)
    feature_collection = FeatureCollection(features)
    return feature_collection
Exemple #14
0
    def __init__(self,
                 base_stations,
                 clients,
                 xlim,
                 map_limits,
                 output_dpi=500,
                 scatter_size=30,
                 output_filename='output.png'):
        self.output_filename = output_filename
        self.base_stations = base_stations
        self.clients = clients
        self.xlim = xlim
        self.map_limits = map_limits
        self.output_dpi = output_dpi
        self.scatter_size = scatter_size
        self.fig = plt.figure(figsize=(32, 24))
        self.fig.canvas.set_window_title('Network Slicing Simulation')

        self.gs = gridspec.GridSpec(4, 4, width_ratios=[3, 3, 3, 3])

        rand_color = randomcolor.RandomColor()
        colors = rand_color.generate(luminosity='bright',
                                     count=len(base_stations))
        # colors = [np.random.randint(256*0.2, 256*0.7+1, size=(3,))/256 for __ in range(len(self.base_stations))]
        for c, bs in zip(colors, self.base_stations):
            bs.color = c
Exemple #15
0
    def _get_dynamic_augmentations(self, leave):
        augmentations = []
        downscale = random.choice([True, False])
        if self._scale:
            h, w, c = leave.shape
            scale_max = self._max_width/w - 1
            scale_min = -(1 - self._min_width/w)
            if downscale:
                augmentations.append(albu.RandomScale(scale_limit=[scale_min, 0.0], p=1))
            else:
                augmentations.append(albu.RandomScale(scale_limit=[0.0, scale_max], p=1))
        else:
            augmentations.append(None)

        rand_color = randomcolor.RandomColor()
        color = rand_color.generate(hue="green", count=1)
        if self._dropout_aug:
            augmentations.append(self._get_dropout_aug(leave, color))
        else:
            augmentations.append(None)

        blur_aug = self._blur_aug()
        if blur_aug:
            augmentations.append(blur_aug)
        else:
            if self._sharpen:
                augmentations.append(albu.IAASharpen(p=0.5))
            else:
                augmentations.append(None)
        return augmentations
Exemple #16
0
def visualize_layers(reachable_layers):

    layers = {}

    for (x, y, z), label in label_matrix.voxels.items():

        pos = Vec3(x, y, z)

        if label == 0 or label not in reachable_layers:
            continue

        if label in layers:
            layers[label][pos] = True
            continue

        layers[label] = np.zeros(label_matrix.shape, dtype=bool)
        layers[label][pos] = True

    color_gen = randomcolor.RandomColor()
    colors = color_gen.generate(count=len(layers), format_='rgb')

    for i in range(len(colors)):
        values = map(lambda e: int(e), re.findall('\\d+', colors[i]))
        values = list(values)
        colors[i] = (values[0] / 255, values[1] / 255, values[2] / 255)

    meshes = []

    i = 0
    for label in layers:
        color = colors[i]
        meshes.append(Mesh.from_voxel_grid(layers[label], colors=color))
        i += 1

    show(meshes)
Exemple #17
0
 def setup(self):
     rand_color = randomcolor.RandomColor()
     self.shape('circle')
     self.shapesize(0.5, 0.5)
     self.color(rand_color.generate())
     self.penup()
     self.goto(randint(-150, 150), randint(-150, 150))
Exemple #18
0
def party_rgb():
    color = randomcolor.RandomColor().generate(count=1, format_='rgb')
    rgb = [
        int(value.strip())
        for value in color[0][4:color[0].rfind(')')].split(',')
    ]
    return rgb[0], rgb[1], rgb[2]
Exemple #19
0
def paint_graph(path, graph, communities):
    if path:
        sys.stdout.write('Drawing graph ... ')
        sys.stdout.flush()
        network = gt.Graph(graph, directed=False)
        folder = os.path.abspath(path)
        # colors = random.sample(range(100,151), len(communities))
        r_cols = randomcolor.RandomColor().generate(count=len(communities) + 1)
        colors = [
            list(int(r_col[1:][i:i + 2], 16) for i in (0, 2, 4))
            for r_col in r_cols
        ]

        # color = graph.new_vertex_property('vector<float>')
        color = network.new_vertex_property('int')

        base_color = colors.pop()
        for v in network.vertices():
            color[v] = (base_color[0] << 16) + (
                base_color[1] << 8) + base_color[2]
        for community in communities:
            c = colors.pop()
            for v in community:
                color[v] = (c[0] << 16) + (c[1] << 8) + c[2]
        pos = gt.sfdp_layout(network)
        gt.graph_draw(network,
                      pos=pos,
                      vertex_fill_color=color,
                      output=os.path.join(folder, 'graph-communities.svg'))
        sys.stdout.write('Ok!\n')
        sys.stdout.flush()
Exemple #20
0
def draw_best_objects(tracker, indices, energy=None, filename="", image_size=[], gen_title=False):
  n_objects = len(tracker.object_names)
  rc = randomcolor.RandomColor()
  colorset = rc.generate(luminosity='bright', count=n_objects, format_='rgb')
  color_list = []
  for i in range(0, n_objects):
    color_array = np.fromstring(colorset[i][4:-1], sep=",", dtype=np.int)
    color_array = color_array * (1. / 255.)
    color_list.append(color_array)
  
  legend_list = []
  for i in range(0, n_objects):
    legend_list.append((tracker.object_names[i], color_list[i]))
  
  box_list = []
  for i in range(0, n_objects):
    box_coords = tracker.box_pairs[indices[i]][1][0:4]
    box_and_color = np.hstack((box_coords, color_list[i]))
    box_list.append(box_and_color)
  
  title = ""
  if gen_title:
    title = "Object Detections"
    
    if energy != None:
      title = "Object Detections (energy={0:.3f})".format(energy)
  draw_image_box(tracker.image_path, box_list, legend_list, title, filename, size=image_size)
Exemple #21
0
def run_2():
    fig = plt.figure(constrained_layout=False, frameon=False)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_facecolor((0.07, 0.07, 0.05))

    rand_color = randomcolor.RandomColor()

    c1 = np.random.uniform(-15, 15)
    c2 = np.random.uniform(-30, 30)
    f_y = lambda x_, c0: c2 * x_**2 + c1 * x_**1 + c0 * np.random.uniform(
        -1, 1)

    for index, total_points in enumerate([50, 80, 120]):

        main_rgb_color = np.array(
            rand_color.generate(hue="blue", count=1,
                                format_='Array_rgb')) / 256.
        main_rgb_color = main_rgb_color[0]

        for another_index in range(10):

            x = np.linspace(0, 2, total_points)
            y = another_index + 10 * f_y(x, np.random.uniform(-20, 20))
            max = 50
            err = np.random.uniform(5, max) * np.sin(
                x * np.random.uniform(5, max))
            for _ in range(5):
                err += np.random.uniform(5, max) * np.sin(
                    x * np.random.uniform(5, max))
                max *= 0.9
                max = np.max([max, 20])

            if np.random.rand() < 0.05:
                y = y[::-1]

            tmp_hsv_color = color.rgb2hsv(main_rgb_color)
            tmp_hsv_color[2] *= np.random.uniform(0.6, 1.0)
            ecolor = color.hsv2rgb(tmp_hsv_color)

            if index == 0:
                elinewidth = 50
                alpha = 0.005
            else:
                elinewidth = np.random.uniform(2, 10)
                alpha = 1 - np.random.power(10)
                alpha = np.max([0.3, alpha])

            ax.errorbar(x,
                        y,
                        err,
                        linewidth=0,
                        ecolor=ecolor,
                        elinewidth=elinewidth,
                        barsabove=True,
                        errorevery=total_points // 40,
                        snap=True,
                        alpha=alpha)

    plt.show()
Exemple #22
0
def community_graph(links_df, original_df, g_export='graph.json'):
    """ Function to create json file based on communities generated by nx
    Args:
        links_df (pandas data frame): The data frame on which we will create the graph from
        original_df (pandas data frame): data frame of the nodes

    returns:
        A data frame that represents the nodes with a unique group_id and color
    """

    print(
        "Creating a nodes data frame representing the nodes with a unique group ids and colors"
    )

    # clean up column names accordingly
    links_df = links_df.rename(columns={
        "target": "source",
        "neighbor": "target"
    })
    # define graph
    """ change: source='target' and target='neighbor' """
    g = nx.from_pandas_edgelist(links_df, source='source', target='target')
    # compute the best partition
    G = g
    # c = list(greedy_modularity_communities(G))
    partition = community.best_partition(G)
    # merge the groupids onto the df
    partition_items = partition.items()
    df_with_groupids = pd.DataFrame(partition_items,
                                    columns=['Code', 'group_id'])
    # get edges only where source and target nodes belong to a valid community for now
    nodes_in_communities = df_with_groupids['Code'].unique()
    edges_for_community_nodes_df = links_df.loc[
        links_df['source'].isin(nodes_in_communities)
        & links_df['target'].isin(nodes_in_communities)]
    # merge unique ids onto the original dataframe
    df_merged = pd.merge(original_df,
                         df_with_groupids,
                         how='left',
                         on=['Code'])
    # add a unique color - NaN's will have same color
    unique_community_ids = df_merged['group_id'].unique()

    color_dict = []
    for groupid in unique_community_ids:
        # generate a random color
        color = randomcolor.RandomColor().generate()[0]
        color_dict.append({'group_id': groupid, 'color_code': color})

    # create a dataframe from the color and unique id
    color_df = pd.DataFrame(color_dict)

    # # merge that dataframe with the original
    df_merged_with_color = pd.merge(df_merged,
                                    color_df,
                                    how='left',
                                    on=['group_id'])

    return df_merged_with_color
Exemple #23
0
    def make_block(self):
        rand_color = randomcolor.RandomColor()
        block = Turtle("square")
        block.color(rand_color.generate())
        block.shapesize(1, 1)
        block.penup()

        return block
def run_2(save_fig=False):
    n_lines = 3
    n_points = 800
    x_min = -20
    x_max = 20

    hue = np.random.choice(['blue', 'purple', 'red'])
    luminosity = None
    rand_color = randomcolor.RandomColor()
    background_color = np.array(
        rand_color.generate(
            hue=hue, luminosity=luminosity, format_='Array_rgb')) / 256.
    plt.rcParams["figure.facecolor"] = background_color[0]
    fig, axes = plt.subplots(n_lines, sharex=True, frameon=True)
    offset = 1
    rand_color = randomcolor.RandomColor()
    value = 1.0

    for ax in axes:
        n_points /= 2.
        color_rgb = np.array(
            rand_color.generate(
                hue=hue, luminosity=luminosity, format_='Array_rgb')) / 256.
        color_rgb = color_rgb[0]
        color_hsv = color.rgb2hsv(color_rgb)
        color_hsv[2] *= value
        value *= 0.9
        color_rgb = color.hsv2rgb(color_hsv)

        ax.axis('off')
        # x = offset * np.random.uniform(-2, 2, int(n_points))
        # x = np.random.normal(0, offset * 2, int(n_points))
        mode = np.random.uniform(x_min, x_max)
        x = np.random.triangular(x_min, mode, x_max, size=int(n_points))

        y = 1 * np.sinc(x**2)
        ax.scatter(x, y / offset, color=color_rgb, s=1.5)
        ax.set_aspect(15)
        offset += 3
        ax.set_xlim(x_min, x_max)
    fig.set_figheight(5)
    fig.set_figwidth(8)

    if save_fig:
        plt.savefig('dotted_lines')
    plt.show()
Exemple #25
0
def run_1():
    fig = plt.figure(constrained_layout=False, frameon=False)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_facecolor((0.37, 0.37, 0.35))

    rand_color = randomcolor.RandomColor()

    for index, total_points in enumerate([50, 80, 120]):

        main_rgb_color = np.array(
            rand_color.generate(hue="blue", count=1,
                                format_='Array_rgb')) / 256.
        main_rgb_color = main_rgb_color[0]

        x = np.linspace(0, 3, total_points)
        for _ in range(500):
            if index == 0:
                y = np.random.uniform(-30, 30) * x**2 + np.random.uniform(
                    -15, 15) * x**1 + np.random.uniform(-1, 1)
            else:
                y = np.random.uniform(-25, 20) * x**2 + np.random.uniform(
                    -10, 10) * x**1 + np.random.uniform(-10, 10)

            max = 20
            err = np.random.uniform(5, max) * np.sin(
                x * np.random.uniform(5, max))
            for _ in range(5):
                err += np.random.uniform(5, max) * np.sin(
                    x * np.random.uniform(5, max))
                max *= 0.4
                max = np.max([max, 20])

            if np.random.rand() < 0.5:
                y = y[::-1]

            tmp_hsv_color = color.rgb2hsv(main_rgb_color)
            tmp_hsv_color[2] *= np.random.uniform(0.4, 0.7)
            ecolor = color.hsv2rgb(tmp_hsv_color)

            if index == 0:
                elinewidth = 100
                alpha = 0.05
            else:
                elinewidth = np.random.uniform(50, 100)
                alpha = 1 - np.random.power(1)

            ax.errorbar(x,
                        y,
                        err,
                        linewidth=0,
                        ecolor=ecolor,
                        elinewidth=elinewidth,
                        barsabove=True,
                        errorevery=total_points // 40,
                        snap=True,
                        alpha=alpha)

    plt.show()
Exemple #26
0
def giveusernewcode(family):
    rc = randomcolor.RandomColor()
    rando = rc.generate(hue=family)
    actualhexcode = rando[0]
    notborked = actualhexcode.strip("#")
    url = urlbase + "/givecode?hex=" + notborked + "&fam=" + family
    result = requests.get(url)
    print(result.text + " written")
    return actualhexcode
Exemple #27
0
def category_badge(category):
    if category not in CATEGORY_NAMES:
        return {}
    return {
        'category': category,
        'name': CATEGORY_NAMES[category],
        'color':
        randomcolor.RandomColor(category).generate(luminosity='dark')[0],
    }
    def test_seed(self):
        if self.py_version == 3:
            expected_color = ['#e094be']
        else:
            expected_color = ['#c0caf7']

        color = self.rand_color.generate()
        self.assertEqual(color, expected_color)
        self.assertEqual(color, randomcolor.RandomColor(42).generate())
Exemple #29
0
 def setup(self):
     rand_color = randomcolor.RandomColor()
     self.color(rand_color.generate())
     self.penup()
     self.hideturtle()
     self.goto(0, 300)
     self.write(f"Level - {self.level}",
                align="center",
                font=("Comic Sans", 20, "bold"))
Exemple #30
0
def random_col():
    rand_color = randomcolor.RandomColor()
    main_color = rand_color.generate()

    if main_color in color_list:
        rand_color()
    else:
        color_list.append(main_color[0])
    return True