Ejemplo n.º 1
0
    def afficher_cellules(self, color):

        # test sign
        def test_sign(vectors):
            for i in range(len(vectors) - 1):
                vec1, vec2 = vectors[i], vectors[i + 1]

                # Si le produit scalaire est négatif, alors les vecteurs sont opposés
                if np.dot(vec1, vec2) < 0:
                    return False

            return True

        # Begin
        for cell in self.__cells:

            x1, x2, x3, x4 = cell[:, 0]
            y1, y2, y3, y4 = cell[:, 1]
            u1, u2, u3, u4 = cell[:, 2]
            v1, v2, v3, v4 = cell[:, 3]

            # Les 4 vecteurs
            vecs = [[u1, v1], [u2, v2], [u3, v3], [u4, v4]]

            if not test_sign(vecs):
                verts = [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]
                poly = Polygon(verts)
                poly.set_color(color)
                ax.add_patch(poly)
 def __add_xy_values_as_polygon__(self, xy: list, color: str, closed=False, fill=False, alpha=0.2, line_width=2):
     xy = PlotterInterface.get_xy_from_timestamp_to_date_number(xy)
     polygon = Polygon(np.array(xy), closed=closed, fill=fill)
     polygon.set_visible(True)
     polygon.set_color(color)
     polygon.set_alpha(alpha)
     polygon.set_linewidth(line_width)
     self.axes_for_candlesticks.add_patch(polygon)
 def __plot_single_fibonacci_wave__(self, fib_wave: FibonacciWave, color: str, suffix: str = ''):
     if self.sys_config.config.fibonacci_detail_print:
         fib_wave.print(suffix)
     xy = fib_wave.get_xy_parameter()
     xy = PlotterInterface.get_xy_from_timestamp_to_date_number(xy)
     fib_polygon = Polygon(np.array(xy), closed=False, fill=False)
     fib_polygon.set_visible(True)
     fib_polygon.set_color(color)
     fib_polygon.set_linewidth(1)
     self.axes_for_candlesticks.add_patch(fib_polygon)
     fib_wave_patch = FibonacciWavePatch(fib_wave, fib_polygon)
     self.fibonacci_patch_container.add_patch(fib_wave_patch)
     fib_wave_patch.add_retracement_patch_list_to_axis(self.axes_for_candlesticks)
 def __add_to_ranges_polygon_dic__(self, polygon: Polygon, for_main: bool, range: PatternRange):
     polygon.set_visible(False)
     polygon.set_color('r' if for_main else 'k')
     polygon.set_linewidth(1)
     self.axes_for_candlesticks.add_patch(polygon)
     for ticks in range.tick_list:
         if for_main:
             if ticks.f_var not in self.ranges_polygon_dic_list:
                 self.ranges_polygon_dic_list[ticks.f_var] = [polygon]
             else:
                 self.ranges_polygon_dic_list[ticks.f_var].append(polygon)
         else:
             if ticks.f_var not in self.ranges_opposite_polygon_dic_list:
                 self.ranges_opposite_polygon_dic_list[ticks.f_var] = [polygon]
             else:
                 self.ranges_opposite_polygon_dic_list[ticks.f_var].append(polygon)
Ejemplo n.º 5
0
    def show_cells(self):
        def checker(vecs):
            for i in range(len(vecs) - 1):
                vec1, vec2 = vecs[i], vecs[i + 1]
                if np.dot(vec1, vec2) < 0:
                    return False
            return True

        for cell in self.cells:
            x1, x2, x3, x4 = cell[:, 0]
            y1, y2, y3, y4 = cell[:, 1]
            u1, u2, u3, u4 = cell[:, 2]
            v1, v2, v3, v4 = cell[:, 3]

            vecs = [[u1, v1], [u2, v2], [u3, v3], [u4, v4]]

            if not checker(vecs):
                pts = [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]
                poly = Polygon(pts)
                poly.set_color("yellow")
                self.ax.add_patch(poly)
Ejemplo n.º 6
0
    def afficher_profil(self, color):
        verts = self.__coords[0:len(self.__coords):35]

        poly = Polygon(verts)
        poly.set_color(color)
        ax.add_patch(poly)
Ejemplo n.º 7
0
def main():
    tic = time.perf_counter()

    gn = Granatum()
    sample_coords = gn.get_import("viz_data")
    value = gn.get_import("value")
    coloring_type = gn.get_arg("coloring_type")
    bounding_stdev = gn.get_arg("bounding_stdev")
    label_location = gn.get_arg("label_location")
    label_transform = gn.get_arg("label_transform")
    labelXaxis = gn.get_arg("labelXaxis")
    labelYaxis = gn.get_arg("labelYaxis")
    sigfigs = gn.get_arg("sigfigs")
    numticks = gn.get_arg("numticks")
    font = gn.get_arg('font')

    coords = sample_coords.get("coords")
    dim_names = sample_coords.get("dimNames")
    seed = gn.get_arg('random_seed')
    random.seed(seed)
    np.random.seed(seed)

    df = pd.DataFrame(
        {
            "x": [a[0] for a in coords.values()],
            "y": [a[1] for a in coords.values()],
            "value": pd.Series(value)
        },
        index=coords.keys())

    target_dpi = 300
    target_width = 7.5  # inches
    target_height = 6.5  # inches
    font_size_in_in = font / 72.0  # inches
    font_size_in_px = font_size_in_in * target_dpi

    try:

        if coloring_type == "categorical":
            uniq = df["value"].unique()
            uniq.sort(kind="stable")
            num = uniq.shape[0]
            COLORS2 = plt.get_cmap('gist_rainbow')
            carr = [0] * df.shape[0]
            listcats = list(df["value"])
            miny = min(list(df["y"]))
            maxy = max(list(df["y"]))
            scaley = (maxy - miny) / (target_height * target_dpi)
            print("Scaley = {}".format(scaley))
            colorhash = {}
            colorstep = np.ceil(256.0 / num)
            coffset = randrange(colorstep)
            grouptocolor = np.random.choice(np.arange(num), num, replace=False)

            for i, cat in enumerate(uniq):
                dff = df[df["value"] == cat]
                xs = list(dff["x"])
                ys = list(dff["y"])
                #avgx = sum(dff["x"]) / len(dff["x"])
                #avgy = sum(dff["y"]) / len(dff["y"])
                #plt.scatter(x=dff["x"], y=dff["y"], s=5000 / df.shape[0], c=COLORS[i].hex_l, label=cat)
                #plt.scatter(x=dff["x"], y=dff["y"], s=5000 / df.shape[0], c=[abs(hash(cat)) % 256]*len(dff["x"]), cmap=COLORS2, label=cat)
                #plt.scatter(x=dff["x"], y=dff["y"], s=5000 / df.shape[0], c=abs(hash(cat)) % 256, cmap=COLORS2, label=cat)
                #abs(hash(cat))
                colorindex = (coffset + grouptocolor[i] * colorstep) % 256
                colorhash[cat] = colorindex
                craw = COLORS2((colorindex + 0.0) / 256.0)
                clr = [craw[0], craw[1], craw[2], 0.2]
                whitetransparent = [1.0, 1.0, 1.0, 0.5]
                coloropaque = [craw[0], craw[1], craw[2], 1.0]
                if len(xs) > 3:
                    pts = list(zip(xs, ys))
                    cent = np.mean(pts, axis=0)
                    lengs = list(
                        map(
                            lambda p: math.sqrt(
                                (p[0] - cent[0]) * (p[0] - cent[0]) +
                                (p[1] - cent[1]) * (p[1] - cent[1])), pts))
                    avgleng = st.mean(lengs)
                    stdleng = st.stdev(lengs) * bounding_stdev
                    rpts = []
                    if (stdleng > 0.0):
                        for j, ln in enumerate(lengs):
                            if (ln - avgleng < stdleng):
                                rpts.append(pts[j])
                        pts = rpts
                    cent = np.mean(pts, axis=0)
                    hull = ConvexHull(pts)
                    ptslist = []
                    for pt in hull.simplices:
                        ptslist.append(pts[pt[0]])
                        ptslist.append(pts[pt[1]])
                    ptslist.sort(key=lambda p: np.arctan2(
                        p[1] - cent[1], p[0] - cent[0]))
                    ptslist = ptslist[0::2]
                    ptslist.insert(len(ptslist), ptslist[0])
                    lowestpt = ptslist[0]
                    if label_location == 'bottom':
                        for pt in ptslist:
                            if (pt[1] < lowestpt[1]):
                                lowestpt = pt
                    else:
                        lowestpt = ptslist[randrange(len(ptslist))]
                    if (bounding_stdev >= 0.0):
                        poly = Polygon(1.1 * (np.array(ptslist) - cent) + cent,
                                       facecolor=clr)
                        poly.set_capstyle('round')
                        plt.gca().add_patch(poly)
                        poly.set_color(clr)
                    label_text = cat
                    if label_transform == "numbers":
                        label_text = re.sub("[^0-9]", "", cat)
                    txt = plt.text(lowestpt[0],
                                   lowestpt[1] -
                                   scaley * font_size_in_px * 1.2,
                                   label_text,
                                   fontsize=font,
                                   fontname="Arial",
                                   ha="center",
                                   va="center",
                                   color="black",
                                   bbox=dict(boxstyle="round",
                                             fc=whitetransparent,
                                             ec=coloropaque))
                    # plt.gca().add_artist(txt)
                for j, x in enumerate(listcats):
                    if x == cat:
                        carr[j] = colorhash[cat]
                        #carr[j] = colorhash[cat] / 256.0
                        #int(abs(hash(cat)) % 256)

            plt.scatter(x=df["x"],
                        y=df["y"],
                        s=5000 / df.shape[0],
                        c=carr,
                        cmap=COLORS2)
            lgd = plt.legend(markerscale=6,
                             loc='upper center',
                             bbox_to_anchor=(0.5, -0.05),
                             ncol=5)
    #60 / (5000 / df.shape[0])
        elif coloring_type == "continuous":
            plt.scatter(x=df["x"],
                        y=df["y"],
                        s=5000 / df.shape[0],
                        c=df["value"],
                        cmap="Reds")
            plt.colorbar()

        xmin, xmax = plt.gca().get_xlim()
        ymin, ymax = plt.gca().get_ylim()
        # stepsizex=(xmax-xmin)/numticks
        # stepsizey=(ymax-ymin)/numticks
        xtickArray = resetArray(xmin, xmax, numticks, sigfigs)
        ytickArray = resetArray(ymin, ymax, numticks, sigfigs)
        # plt.xticks(np.arange(xmin, xmax+stepsizex, step=stepsizex), fontsize=font, fontname="Arial")
        # plt.yticks(np.arange(ymin, ymax+stepsizey, step=stepsizey), fontsize=font, fontname="Arial")
        plt.xlim(xtickArray[0], xtickArray[-1])
        plt.ylim(ytickArray[0], ytickArray[-1])
        plt.xticks(xtickArray, fontsize=font, fontname="Arial")
        plt.yticks(ytickArray, fontsize=font, fontname="Arial")
        if labelXaxis == "":
            plt.xlabel(dim_names[0], fontsize=font, fontname="Arial")
        else:
            plt.xlabel(labelXaxis, fontsize=font, fontname="Arial")

        if labelYaxis == "":
            plt.ylabel(dim_names[1], fontsize=font, fontname="Arial")
        else:
            plt.ylabel(labelYaxis, fontsize=font, fontname="Arial")

        # plt.tight_layout()

        gn.add_current_figure_to_results(
            "Scatter-plot",
            dpi=target_dpi,
            width=target_width * target_dpi,
            height=target_height * target_dpi,
            savefig_kwargs={'bbox_inches': 'tight'})

        toc = time.perf_counter()
        time_passed = round(toc - tic, 2)

        timing = "* Finished sample coloring step in {} seconds*".format(
            time_passed)
        gn.add_result(timing, "markdown")

        gn.commit()

    except Exception as e:

        plt.figure()
        plt.text(
            0.05, 0.7,
            'Values used as colors and type of sample metadata are incompatible with each other'
        )

        if coloring_type == 'categorical':
            new_coloring_type = 'continuous'
        else:
            new_coloring_type = 'categorical'

        plt.text(
            0.05, 0.5, 'Retry the step with ' + new_coloring_type +
            ' instead of ' + coloring_type)
        plt.axis('off')
        gn.add_current_figure_to_results('Scatter-plot')

        gn.commit()
Ejemplo n.º 8
0
    def create_stats_circle(self, color='b', bg_color=None, **kwargs):
        c = 'black'
        if color_distance(Color(c), bg_color) < (MAX_COLOR_DIFF / 2):
            c = 'white'

        inner_circle = Circle((0, 0), radius=1.1, fc='none', ec=c)
        outer_circle = Circle((0, 0), radius=1.55, fc='none', ec=c)
        outest_circle = Circle((0, 0), radius=1.65, fc='none', ec=c)
        fig, ax = self.create_empty_stats_circle(c)
        stat_spread = []
        for idx, line in enumerate(self.stats.values()):
            x, y = line[0].get_data()
            power = POWERS[idx]
            power_value = kwargs.get(power, 'E')
            if power_value is None:
                power_value = 'E'
            power_value = power_value.upper()
            power_int = LETTERS_TO_INT.get(power_value, 0)

            # Small correction to the text position
            correction = 0.03
            r = 60 * idx / 180 * pi

            sinr = np.round(np.sin(r), 5)
            cosr = np.round(np.cos(r), 5)

            if sinr < 0:
                lx = 1.25 * sinr - correction
            else:
                lx = 1.25 * sinr + correction
            if cosr < 0:
                ly = 1.25 * cosr - correction
            else:
                ly = 1.25 * cosr + correction

            rot = (0 + min(check_negative(cosr) * 180, 0)) - 60 * idx
            if sinr == 0:
                rot = 0

            ax.text(lx,
                    ly,
                    power_value,
                    color=c,
                    alpha=0.9,
                    fontsize=14,
                    weight='bold',
                    ha='center',
                    va='center')
            ax.text(lx * 1.50,
                    ly * 1.50,
                    power,
                    color=c,
                    fontsize=17,
                    ha='center',
                    rotation=rot,
                    va='center')

            x = x[power_int]
            y = y[power_int]
            stat_spread.append([x, y])

        r1 = outer_circle.radius
        r2 = outest_circle.radius
        w = 3.0
        for r in range(0, 360, 15):
            sinr = np.round(np.sin(np.deg2rad(r)), 5)
            cosr = np.round(np.cos(np.deg2rad(r)), 5)
            x = (r1 * sinr, r2 * sinr)
            y = (r1 * cosr, r2 * cosr)
            ax.plot(x, y, '-', color=c, linewidth=w)

        pol = Polygon(stat_spread, fc='y', alpha=0.7)
        pol.set_color(color)

        fig.gca().add_patch(inner_circle)
        fig.gca().add_patch(outer_circle)
        fig.gca().add_patch(outest_circle)
        fig.gca().add_patch(pol)
        fig.gca().autoscale(True)
        fig.gca().set_axis_off()

        ax.axis('scaled')

        fig.canvas.draw()

        return fig, ax
Ejemplo n.º 9
0
class Plot:
    def __init__(self, fig, ax):
        self.fig = fig
        self.ax = ax
        self.plot_dict = {}
        self.plot_dict2 = {}

        self.dark_fg = "0.2"
        self.bright_fg = "0.64"
        self.white_bg = "1.0"
        self.gray_bg = "0.5"
        self.black_bg = "0.0"

        # plot points per 90°
        self.num_x = 30

        self.z = 0.2
        self.top_bottom_border = 2 * self.z
        self.paired_function_offset = 0.5
        self.row_offset = 2.0

        self.rows = 12
        self.cols = 10
        self.height = (self.rows - 1) * self.row_offset + 2 * self.z + self.paired_function_offset + 2 * self.top_bottom_border
        self.width = self.cols * 2 * np.pi

        self.r = self.height / self.width
        self.width = self.height

        self.white_triangle = Polygon([[0, self.height],
                                       [0.5 * self.width, self.height],
                                       [0, 0.5 * self.height]],
                                      color=self.white_bg)
        self.gray_polygon = Polygon([[0.5 * self.width, self.height],
                                     [self.width, self.height],
                                     [self.width, 0.5 * self.height],
                                     [0.5 * self.width, 0],
                                     [0, 0],
                                     [0, 0.5 * self.height]], color=self.gray_bg)
        self.black_triangle = Polygon([[self.width, 0.5 * self.height],
                                       [self.width, 0],
                                       [0.5 * self.width, 0]],
                                      color=self.black_bg)

        self.ax.add_patch(self.white_triangle)
        self.ax.add_patch(self.gray_polygon)
        self.ax.add_patch(self.black_triangle)

        for i in range(self.rows):
            if i % 2 == 0:
                colors = (self.dark_fg, self.dark_fg, self.bright_fg, self.bright_fg)
            else:
                colors = (self.bright_fg, self.dark_fg, self.dark_fg, self.bright_fg)
            for j in range(self.cols):
                for k in range(4):
                    xs = np.linspace((2*j+k/2)*np.pi*self.r, (2*j+(k+1)/2)*np.pi*self.r, self.num_x)
                    y1 = self.z * np.sin(xs / self.r) + i * self.row_offset + self.z + self.top_bottom_border
                    y2 = y1 + self.paired_function_offset
                    # keep plots for color changing
                    self.plot_dict[(i, j, k)] = self.ax.plot(xs, y1, color=colors[k])
                    self.plot_dict2[(i, j, k)] = self.ax.plot(xs, y2, color=colors[k])

    def update_white_bg(self, val):
        self.white_triangle.set_color(str(val))
        self.fig.canvas.draw()

    def update_gray_bg(self, val):
        self.gray_polygon.set_color(str(val))
        self.fig.canvas.draw()

    def update_black_bg(self, val):
        self.black_triangle.set_color(str(val))
        self.fig.canvas.draw()

    def update_bright_fg(self, val):
        self.bright_fg = str(val)
        self.update_colors()
        self.fig.canvas.draw()

    def update_dark_fg(self, val):
        self.dark_fg = str(val)
        self.update_colors()
        self.fig.canvas.draw()

    def update_colors(self):
        for i in range(self.rows):
            if i % 2 == 0:
                colors = (self.dark_fg, self.dark_fg, self.bright_fg, self.bright_fg)
            else:
                colors = (self.bright_fg, self.dark_fg, self.dark_fg, self.bright_fg)
            for j in range(self.cols):
                for k in range(4):
                    for l in self.plot_dict[(i, j, k)]:
                        l.set_color(colors[k])
                    for l in self.plot_dict2[(i, j, k)]:
                        l.set_color(colors[k])
Ejemplo n.º 10
0
    def profile(self, color):
        pts = self.coords[0:len(self.coords):35]

        poly = Polygon(pts)
        poly.set_color(color)
        self.ax.add_patch(poly)