Esempio n. 1
0
def init_figures(issplit, isvector, naxes, nplots):
    """
    initialize figures and set up backends

    issplit: true if we're making separate vector and raster figures
    isvector: true if we're making vector lines
    naxes: number of axes, used for sizing
    nplots: number of subplots, used for sizing
    """
    figsize = (3 + 0.6 * naxes, 2 + (4 / 3) * nplots)
    #    figsize = (3 + 0.6 * naxes, 2 + (10/3) * nplots)
    if issplit:
        raster = matplotlib.figure.Figure(figsize=figsize)
        agg.FigureCanvasAgg(raster)
        vector = matplotlib.figure.Figure(figsize=figsize)
        svg.FigureCanvasSVG(vector)
    elif isvector:
        vector = matplotlib.figure.Figure(figsize=figsize)
        svg.FigureCanvasSVG(vector)
        raster = vector
    else:
        raster = matplotlib.figure.Figure(figsize=figsize)
        agg.FigureCanvasAgg(raster)
        vector = raster

    return raster, vector
Esempio n. 2
0
def plot_heldout_prediction(input_vals, probs, fname, title=""):
    """Plotting uncertainity in prediction of a sampled image .
  Args:
    input_vals: A `float`-like Numpy `array` of shape
      IMAGE_SHAPE`, containing a sampled test image.
    probs: A `float`-like Numpy array of shape `[num_monte_carlo,
      1, num_classes]` containing Monte Carlo samples of
      class probabilities for a test image.
    fname: Python `str` filename to save the plot to.
    title: Python `str` title for the plot.
  """
    save_dir = os.path.join(DATA_DIR, "..", "Plots")
    fig = figure.Figure(figsize=(1, 1))
    canvas = backend_agg.FigureCanvasAgg(fig)
    ax = fig.add_subplot(1, 1, 1)
    ax.imshow(input_vals.reshape((IMG_SIZE, IMG_SIZE)), interpolation="None")
    canvas.print_figure(os.path.join(save_dir, fname + "_image.png"),
                        format="png")

    fig = figure.Figure(figsize=(10, 5))
    canvas = backend_agg.FigureCanvasAgg(fig)
    ax = fig.add_subplot(1, 1, 1)
    #Predictions
    y_pred_list = list(np.argmax(probs, axis=1).astype(np.int32))
    bin_range = [x for x in range(43)]
    ax.hist(y_pred_list, bins=bin_range)
    ax.set_xticks(bin_range)
    ax.set_title("Histogram of predicted class: " + title)
    ax.set_xlabel("Class")
    ax.set_ylabel("Frequency")
    fig.tight_layout()
    save_dir = os.path.join(DATA_DIR, "..", "Plots")
    canvas.print_figure(os.path.join(save_dir, fname + "_predicted_class.png"),
                        format="png")
    print("saved {}".format(fname))
Esempio n. 3
0
def grafic(tela):
    # soma_indices = 1
    import matplotlib
    import matplotlib.pyplot as plt
    pygame.draw.rect(tela, cinza, (0, 0, 1200, 800), 0)
    matplotlib.use("Agg")
    import matplotlib.backends.backend_agg as agg
    processos_infos = []
    for processos in psutil.process_iter():
        processos_infos.append({
            "pid": processos.pid,
            "nome": processos.name(),
            "rss": processos.memory_info().rss,
            "vms": processos.memory_info().vms
        })
    names = [info["pid"] for info in processos_infos]
    values1 = [info["vms"] / 1024 / 1024 for info in processos_infos]
    values2 = [info["rss"] / 1024 / 1024 for info in processos_infos]

    fig_1, axs = plt.subplots()
    lines_1, = axs.plot(names, values1)
    plt.xlabel("pid")
    plt.ylabel("vms")
    plt.setp(lines_1, color='b', linewidth=1.0)
    fig_1.suptitle('PID X VMS')

    fig_2, axs = plt.subplots()
    lines_2, = axs.plot(names, values2)
    plt.xlabel("pid")
    plt.ylabel("rss")
    plt.setp(lines_2, color='b', linewidth=1.0)
    fig_2.suptitle('PID X RSS')

    canvas_1 = agg.FigureCanvasAgg(fig_1)
    canvas_1.draw()
    tamanho_1 = canvas_1.get_width_height()
    renderer = canvas_1.get_renderer()
    raw_data_1 = renderer.tostring_rgb()

    canvas_2 = agg.FigureCanvasAgg(fig_2)
    canvas_2.draw()
    tamanho_2 = canvas_2.get_width_height()
    renderer = canvas_2.get_renderer()
    raw_data_2 = renderer.tostring_rgb()

    superficie_grafico_1 = pygame.image.fromstring(raw_data_1, tamanho_1,
                                                   "RGB")
    tela.blit(superficie_grafico_1, (0, 150))

    superficie_grafico_2 = pygame.image.fromstring(raw_data_2, tamanho_2,
                                                   "RGB")
    tela.blit(superficie_grafico_2, (590, 150))
Esempio n. 4
0
def latex_to_png_mpl(s, wrap, color='Black', scale=1.0):
    try:
        from matplotlib import figure, font_manager, mathtext
        from matplotlib.backends import backend_agg
        from pyparsing import ParseFatalException
    except ImportError:
        return None

    # mpl mathtext doesn't support display math, force inline
    s = s.replace('$$', '$')
    if wrap:
        s = u'${0}$'.format(s)

    try:
        prop = font_manager.FontProperties(size=12)
        dpi = 120 * scale
        buffer = BytesIO()

        # Adapted from mathtext.math_to_image
        parser = mathtext.MathTextParser("path")
        width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop)
        fig = figure.Figure(figsize=(width / 72, height / 72))
        fig.text(0, depth / height, s, fontproperties=prop, color=color)
        backend_agg.FigureCanvasAgg(fig)
        fig.savefig(buffer, dpi=dpi, format="png", transparent=True)
        return buffer.getvalue()
    except (ValueError, RuntimeError, ParseFatalException):
        return None
def create_graph(figure, plot_size):
    canvas = agg.FigureCanvasAgg(figure)
    canvas.draw()
    renderer = canvas.get_renderer()
    raw_data = renderer.tostring_rgb()
    graph = pygame.image.fromstring(raw_data, plot_size, "RGB")
    return graph
Esempio n. 6
0
def grafica():
    fig = pylab.figure(
        figsize=[4, 4],  # Inches
        dpi=100,  # 100 dots per inch, so the resulting buffer is 400x400 pixels
    )
    ax = fig.gca()
    ax.plot([1, 2, 4])

    canvas = agg.FigureCanvasAgg(fig)
    canvas.draw()
    renderer = canvas.get_renderer()
    raw_data = renderer.tostring_rgb()

    pygame.init()

    window = pygame.display.set_mode((600, 400), DOUBLEBUF)
    screen = pygame.display.get_surface()

    size = canvas.get_width_height()

    surf = pygame.image.fromstring(raw_data, size, "RGB")
    screen.blit(surf, (0, 0))
    pygame.display.flip()

    crashed = False
    while not crashed:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                crashed = True
def plot_heldout_prediction(input_vals, probs, fname, n=10, title=""):
    """Save a PNG plot visualizing posterior uncertainty on heldout data.
  Args:
    input_vals: A `float`-like Numpy `array` of shape
      `[num_heldout] + IMAGE_SHAPE`, containing heldout input images.
    probs: A `float`-like Numpy array of shape `[num_monte_carlo,
      num_heldout, num_classes]` containing Monte Carlo samples of
      class probabilities for each heldout sample.
    fname: Python `str` filename to save the plot to.
    n: Python `int` number of datapoints to vizualize.
    title: Python `str` title for the plot.
  """
    fig = figure.Figure(figsize=(9, 3 * n))
    canvas = backend_agg.FigureCanvasAgg(fig)
    for i in range(n):
        ax = fig.add_subplot(n, 3, 3 * i + 1)
        ax.imshow(input_vals[i, :].reshape(IMAGE_SHAPE[:-1]),
                  interpolation="None")

        ax = fig.add_subplot(n, 3, 3 * i + 2)
        for prob_sample in probs:
            sns.barplot(np.arange(10), prob_sample[i, :], alpha=0.1, ax=ax)
            ax.set_ylim([0, 1])
        ax.set_title("posterior samples")

        ax = fig.add_subplot(n, 3, 3 * i + 3)
        sns.barplot(np.arange(10), np.mean(probs[:, i, :], axis=0), ax=ax)
        ax.set_ylim([0, 1])
        ax.set_title("predictive probs")
    fig.suptitle(title)
    fig.tight_layout()

    canvas.print_figure(fname, format="png")
    print("saved {}".format(fname))
Esempio n. 8
0
def figure_to_image(figure, close=True):
    """Render matplotlib figure to numpy format.

    Returns:
        numpy.array: image in [CHW] order
    """
    if not np:
        logger.warning(NUMPY_ERROR_MESSAGE)

    try:
        import matplotlib.pyplot as plt
        import matplotlib.backends.backend_agg as plt_backend_agg
    except ImportError:
        logger.warning(MATPLOTLIB_ERROR_MESSAGE)

    canvas = plt_backend_agg.FigureCanvasAgg(figure)
    canvas.draw()
    data = np.frombuffer(canvas.buffer_rgba(), dtype=np.uint8)
    w, h = figure.canvas.get_width_height()
    image_hwc = data.reshape([h, w, 4])[:, :, 0:3]
    image_chw = np.moveaxis(image_hwc, source=2, destination=0)
    if close:
        try:
            plt.close(figure.number)
        except:
            plt.close(figure)
    return image_chw
def desenha_grafico(tipo):
    import matplotlib
    import matplotlib.pyplot as plt
    matplotlib.use("Agg")
    import matplotlib.backends.backend_agg as agg
    lista_p, lista_v = pega_processos(tipo)
    names = lista_p
    values = lista_v

    fig, axs = plt.subplots()
    axs.plot(names, values)
    posicao_grafico = 0

    if (tipo == "grafico_vms"):
        fig.suptitle('Uso de memoria VMS')
        posicao_grafico = 70
    else:
        fig.suptitle('Uso de memoria RSS')
        posicao_grafico = 550

    canvas = agg.FigureCanvasAgg(fig)
    canvas.draw()
    size = canvas.get_width_height()
    renderer = canvas.get_renderer()
    raw_data = renderer.tostring_rgb()
    surf = pygame.image.fromstring(raw_data, size, "RGB")
    tela.blit(surf, (100, posicao_grafico))
Esempio n. 10
0
def draw_loss_graph(train_loss_list, test_loss_list, train_epoch_list=None,
                    test_epoch_list=None, train_color='blue', test_color='red',
                    legend_loc='upper right', title=None):
    # Axis data
    # Losses
    train_loss = np.asarray(train_loss_list)
    test_loss = np.asarray(test_loss_list)
    # Epochs
    if train_epoch_list:
        train_epoch = np.asarray(train_epoch_list)
    else:
        train_epoch = np.arange(0, len(train_loss_list))
    if test_epoch_list:
        test_epoch = np.asarray(test_epoch_list)
    else:
        test_epoch = np.arange(0, len(test_loss_list))

    # Create new figure
    plt.clf()
    fig, ax = plt.subplots()
    ax.plot(train_epoch, train_loss, label='train', color=train_color)
    ax.plot(test_epoch, test_loss, label='test', color=test_color)

    def draw_annotate(label, x, y, color):
        ax.scatter(x, y, 20, color=color)
        ax.annotate(label, xy=(x, y), xytext=(+20, +10),
                    textcoords='offset points',
                    arrowprops={'arrowstyle': '->',
                                'connectionstyle': 'arc3,rad=.2'})

    # Show min values
    if train_loss.shape[0] > 0:
        min_idx = np.argmin(train_loss)
        x, y = train_epoch[min_idx], train_loss[min_idx]
        draw_annotate('min train loss: %0.3f' % y, x, y, train_color)
    if test_loss.shape[0] > 0:
        min_idx = np.argmin(test_loss)
        x, y = test_epoch[min_idx], test_loss[min_idx]
        draw_annotate('min test loss: %0.3f' % y, x, y, test_color)

    # Settings
    ax.set_xlabel("epoch")
    ax.set_ylabel("loss rate")
    ax.set_xlim(left=0)
    ax.set_ylim(bottom=0)
    ax.legend(loc=legend_loc)
    if title is not None:
        ax.set_title(title)

    # Draw
    canvas = agg.FigureCanvasAgg(fig)
    canvas.draw()
    renderer = canvas.get_renderer()
    img = np.fromstring(renderer.tostring_rgb(), dtype=np.uint8, sep='')
    img = img.reshape(canvas.get_width_height()[::-1] + (3,))

    # Close
    plt.close('all')

    return img
Esempio n. 11
0
def make_pie(size, values, labels, title):
    """
    make a pie chart using matplotlib.
    return the chart as a pygame surface
    make the pie chart a square that is as tall as the display.
    """
    logging.debug('make_pie(...,...,%s)', title)
    inches = size[1] / 100.0
    fig = plt.figure(figsize=(inches, inches), dpi=100, tight_layout={'pad': 0.10}, facecolor='k')
    ax = fig.add_subplot(111)
    ax.pie(values, labels=labels, autopct='%1.1f%%', textprops={'color': 'w'}, wedgeprops={'linewidth': 0.25},
           colors=('b', 'g', 'r', 'c', 'm', 'y', '#ff9900', '#00ff00', '#663300'))
    ax.set_title(title, color='white', size=48, weight='bold')

    handles, labels = ax.get_legend_handles_labels()
    legend = ax.legend(handles[0:5], labels[0:5], title='Top %s' % title, loc='lower left')  # best
    frame = legend.get_frame()
    frame.set_color((0, 0, 0, 0.75))
    frame.set_edgecolor('w')
    legend.get_title().set_color('w')
    for text in legend.get_texts():
        plt.setp(text, color='w')

    canvas = agg.FigureCanvasAgg(fig)
    canvas.draw()
    renderer = canvas.get_renderer()
    raw_data = renderer.tostring_rgb()

    plt.close(fig)

    canvas_size = canvas.get_width_height()
    logging.debug('make_pie(...,...,%s) done', title)
    return raw_data, canvas_size
Esempio n. 12
0
    def render(self, state):
        width = self.resolution[0] / self.dpi
        height = self.resolution[1] / self.dpi
        fig = plt.figure(0, figsize=(width, height), dpi=self.dpi)

        current, wait, backlog, time = state
        lines = current.shape[0]

        # Axes {{{
        axs_current = [
            plt.subplot2grid((lines, 3), (i, 0)) for i in range(lines)
        ]
        axs_wait = [plt.subplot2grid((lines, 3), (i, 1)) for i in range(lines)]
        ax_backlog = plt.subplot2grid((lines, 3), (0, 2), rowspan=lines)
        # End of Axes }}}

        for i, (ax_current, ax_wait) in enumerate(zip(axs_current, axs_wait)):
            self.plot_substate(ax_current, f'Current resources {i}',
                               current[i])
            self.plot_substate(ax_wait, f'Waiting jobs stack {i}',
                               np.mean(wait[i], axis=0))
        self.plot_substate(ax_backlog, 'Backlog', backlog, True)

        fig.tight_layout()
        canvas = agg.FigureCanvasAgg(fig)
        canvas.draw()
        renderer = canvas.get_renderer()
        raw_data = renderer.tostring_rgb()
        size = canvas.get_width_height()
        plt.close(fig)

        return np.frombuffer(raw_data, dtype=np.uint8).reshape(
            (size[0], size[1], 3))
Esempio n. 13
0
def draw_hand():
    

ax.plot([1, 2, 4])
 
canvas = agg.FigureCanvasAgg(fig)
canvas.draw()
renderer = canvas.get_renderer()
raw_data = renderer.tostring_rgb()
 

 
pygame.init()
 
window = pygame.display.set_mode((600, 400), DOUBLEBUF)
screen = pygame.display.get_surface()
 
size = canvas.get_width_height()
 
surf = pygame.image.fromstring(raw_data, size, "RGB")
screen.blit(surf, (0,0))
pygame.display.flip()
 
while True:
    pass
Esempio n. 14
0
def FigureToSummary(name, fig):
  """Create tf.Summary proto from matplotlib.figure.Figure.

  Args:
    name: Summary name.
    fig: A matplotlib figure object.

  Returns:
    A `tf.Summary` proto containing the figure rendered to an image.
  """
  canvas = backend_agg.FigureCanvasAgg(fig)
  fig.canvas.draw()
  ncols, nrows = fig.canvas.get_width_height()
  png_file = six.BytesIO()
  canvas.print_figure(png_file)
  png_str = png_file.getvalue()
  return tf.Summary(value=[
      tf.Summary.Value(
          tag='%s/image' % name,
          image=tf.Summary.Image(
              height=nrows,
              width=ncols,
              colorspace=3,
              encoded_image_string=png_str))
  ])
Esempio n. 15
0
    def create_canvas_and_axes(self):
        # Create a figure.
        fig = figure.Figure()

        # Create a canvas and add the figure to it
        self.canvas = backend_agg.FigureCanvasAgg(fig)
        self.axes = fig.add_subplot(111)
Esempio n. 16
0
    def update_env():

        obs = env.reset(wd=wd, ws=ws)
        print(f'initializing flow filed for  {wd} with {env.cur_yaws}')
        farm.reinitialize_flow_field(wind_direction=[wd], wind_speed=[ws])

        farm.calculate_wake(yaw_angles=env.cur_yaws)
        nominal_power = farm.get_farm_power()
        print(f'nominal power {nominal_power}')

        action = agent.compute_action(obs)
        print(f'actions : {action}')
        #  Execute the actions
        if env.continuous_action_space:
            env.cur_yaws = action * env.allowed_yaw
        else:
            env.cur_yaws = action - env.allowed_yaw
        farm.calculate_wake(yaw_angles=env.cur_yaws)
        # obs, reward, done, info = env.step(action=action, no_variation=True)
        steering_power = farm.get_farm_power()

        hor_plane = farm.get_hor_plane(
            height=farm.floris.farm.turbines[0].hub_height
        )  # x_resolution=400, y_resolution=100)
        # Plot and show
        fig, ax = plt.subplots()
        wfct.visualization.visualize_cut_plane(hor_plane, ax=ax)
        canvas = agg.FigureCanvasAgg(fig)
        canvas.draw()
        renderer = canvas.get_renderer()
        size = canvas.get_width_height()
        raw_data = renderer.tostring_rgb()
        surf = pygame.image.fromstring(raw_data, size, "RGB")

        return surf, nominal_power, steering_power
Esempio n. 17
0
def PlotBlockBar(BlockNumber, FigSize=3, xpos=.5, ypos=.5, UPDATE=False):
    matplotlib.rcParams.update({'font.size': 22})
    X = np.linspace(0, BlockNumber, BlockNumber + 1)
    fig = pylab.figure(figsize=(FigSize * 6, FigSize), dpi=100)
    ax = fig.gca()
    ax.barh(np.asarray([0]),
            np.asarray([BlockNumber + 1]),
            align='center',
            color='green')
    plt.xticks(range(Blocks + 1))
    ax.set_xlim(0, Blocks)
    labels = ['Prac']
    alphabet = [
        '0', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
        'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    ]
    [labels.append(alphabet[i]) for i in range(1, Blocks)]
    labels.append('End!')
    ax.set_xticklabels([])
    ax.set_ylim(-.005, .005)
    ax.get_yaxis().set_visible(False)
    ax.tick_params(axis='x', length=100, width=2)
    bg = str(BG[0] / 255.)
    fig.patch.set_facecolor(bg)
    canvas = agg.FigureCanvasAgg(fig)
    canvas.draw()
    renderer = canvas.get_renderer()
    raw_data = renderer.tostring_rgb()
    size = canvas.get_width_height()
    surf = pygame.image.fromstring(raw_data, size, "RGB")
    screen = DISPLAYSURF
    screen.blit(
        pygame.transform.scale(surf, (1200, 200)),
        (int(WINDOW_WIDTH * xpos + 150), int(WINDOW_HEIGHT * ypos - 150)))
Esempio n. 18
0
def graph_results(score, length):
    fig = pylab.figure(figsize=[4, 4], dpi=90)
    ax = fig.gca()
    ax.plot(score)
    ax.set_title("Agents score over {}/{} Iteration".format(
        length, len(score)))
    ax.set_xlabel('Iteration')
    ax.set_ylabel('Score')

    canvas = agg.FigureCanvasAgg(fig)
    canvas.draw()
    renderer = canvas.get_renderer()
    raw_data = renderer.tostring_rgb()

    pygame.init()

    screen = pygame.display.get_surface()

    size = canvas.get_width_height()

    surf = pygame.image.fromstring(raw_data, size, "RGB")
    screen.blit(surf, (800, 200))
    area = pygame.Rect(800, 0, 600, 700)
    pygame.display.update(area)
    pylab.close('all')
Esempio n. 19
0
def getRawData(fig):
    canvas = agg.FigureCanvasAgg(fig)
    canvas.draw()
    renderer = canvas.get_renderer()
    raw_data = renderer.tostring_rgb()
    size = canvas.get_width_height()
    return raw_data, size
Esempio n. 20
0
def script_init(sbj_id, day, disconnect_file):
    #Colors
    green = (0, 200, 0)
    labels, ratios, fig, pixel_points = rc.main(sbj_id, day)
    all_markers = {}
    start_time, end_time, start, end = get_disconnected_times(disconnect_file)

    for i in xrange(len(labels)):
        marker_cur = Marker(labels[i], ratios[i], pixel_points[i],
                            start_time + timedelta(seconds=i))
        if int(pixel_points[i][0]) not in all_markers:
            all_markers[int(pixel_points[i][0])] = {}
        if int(pixel_points[i][1]) not in all_markers[int(pixel_points[i][0])]:
            all_markers[int(pixel_points[i][0])][int(pixel_points[i][1])] = []
        all_markers[int(pixel_points[i][0])][int(
            pixel_points[i][1])].append(marker_cur)
    canvas = agg.FigureCanvasAgg(fig)
    canvas.draw()
    renderer = canvas.get_renderer()
    raw_data = renderer.tostring_rgb()

    window = pygame.display.set_mode((1280, 480), pygame.locals.DOUBLEBUF)
    screen = pygame.display.get_surface()

    size = canvas.get_width_height()

    surf = pygame.image.fromstring(raw_data, size, "RGB")
    screen.blit(surf, (0, 0))
    pygame.draw.rect(screen, green, (0, 0, 80, 40))
    TextSurf, TextRect = text_objects("Restart",
                                      pygame.font.Font('freesansbold.ttf', 20))
    TextRect.center = ((40), (20))
    screen.blit(TextSurf, TextRect)
    pygame.display.flip()
    return all_markers, screen
Esempio n. 21
0
    def Plot_mean_std(mean, std, layer):
        fig = figure.Figure(figsize=(20, 20))
        canvas = backend_agg.FigureCanvasAgg(fig)
        ax = fig.add_subplot(121)
        sns.distplot(mean,
                     label='mean',
                     hist=False,
                     color="g",
                     kde_kws={"shade": True},
                     ax=ax)
        ax1 = fig.add_subplot(122)
        sns.distplot(std,
                     label='std',
                     hist=False,
                     color="g",
                     kde_kws={"shade": True},
                     ax=ax1)

        ax.set_xlabel('Weight value')
        ax.set_ylabel('Density')
        ax.legend()
        fig.tight_layout()
        fname = os.path.join(self.FLAGS.data_dir,
                             (layer[0].split('/')[-2] + "_Mean_STD_Plot.png"))
        canvas.print_figure(fname, format="png")
        return
Esempio n. 22
0
def cli():
    args = get_args()
    table = pandas.read_table(args.table, sep=" ")
    fig = matplotlib.figure.Figure(figsize=(6,15))
    agg.FigureCanvasAgg(fig)
    multibarchart(fig, table)
    fig.savefig("report")
Esempio n. 23
0
    def create_canvas(self, rang, function, size, pos, surface):
        fig = pylab.figure(
            figsize=list(size),  # Inches
            dpi=1,
            facecolor=(
                0.0, 0.0, 0.0, 1.0
            )  # 100 dots per inch, so the resulting buffer is 400x400 pixels
        )
        ax = fig.gca()
        ax.set_axis_off()
        ax.set_facecolor((0.0, 1.0, 0.0, 1.0))
        ax.plot(rang, function, linewidth=100)

        canvas = agg.FigureCanvasAgg(fig)
        canvas.draw()
        s = canvas.get_width_height()
        renderer = canvas.get_renderer()
        raw_data = renderer.tostring_argb()
        id_ = code_generator(6)
        self.requests.append({
            "data": raw_data,
            "size": s,
            "pos": pos,
            "id": id_,
            "surface": surface
        })
        return id_
Esempio n. 24
0
def graphic():
    global time0, success, miss_prev, hit_prev, hit, miss, B, fig, graf, canvas, renderer, raw_data, surf
    if pygame.time.get_ticks() - time0 > 2000:
        time0 = pygame.time.get_ticks()
        if (hit + miss - hit_prev - miss_prev) == 0:
            success = 0
        else:
            success = 100 * (hit - hit_prev) / (hit + miss - hit_prev -
                                                miss_prev)
        sdvig(success)
        miss_prev = miss
        hit_prev = hit
        B = [(hit * 100) / (hit + miss)] * 20

        fig = pylab.figure(
            figsize=[6, 4],  # Inches
            dpi=200
        )  # 100 dots per inch, so the resulting buffer is 400x400 pixels
        matplotlib.pyplot.xlabel(r'Время')
        matplotlib.pyplot.ylabel(r"Успешность")
        graf = fig.gca()
        graf.plot(B, color='g')
        graf.plot(A, color='b')
        canvas = agg.FigureCanvasAgg(fig)
        canvas.draw()
        renderer = canvas.get_renderer()
        raw_data = renderer.tostring_rgb()
        surf = pygame.image.fromstring(raw_data, size, "RGB")
def plot_weight_posteriors(names, qm_vals, qs_vals, fname):
    """Save a PNG plot with histograms of weight means and stddevs.
  Args:
    names: A Python `iterable` of `str` variable names.
    qm_vals: A Python `iterable`, the same length as `names`,
      whose elements are Numpy `array`s, of any shape, containing
      posterior means of weight varibles.
    qs_vals: A Python `iterable`, the same length as `names`,
      whose elements are Numpy `array`s, of any shape, containing
      posterior standard deviations of weight varibles.
    fname: Python `str` filename to save the plot to.
  """
    fig = figure.Figure(figsize=(6, 3))
    canvas = backend_agg.FigureCanvasAgg(fig)

    ax = fig.add_subplot(1, 2, 1)
    for n, qm in zip(names, qm_vals):
        sns.distplot(qm.flatten(), ax=ax, label=n)
    ax.set_title("weight means")
    ax.set_xlim([-1.5, 1.5])
    ax.legend()

    ax = fig.add_subplot(1, 2, 2)
    for n, qs in zip(names, qs_vals):
        sns.distplot(qs.flatten(), ax=ax)
    ax.set_title("weight stddevs")
    ax.set_xlim([0, 1.])

    fig.tight_layout()
    canvas.print_figure(fname, format="png")
    print("saved {}".format(fname))
Esempio n. 26
0
def pygame_loop(prediction, img):

    if prediction <= 10:
        speed_label = myFont.render('Slow', 1, white)
    elif prediction > 10 and prediction <= 25:
        speed_label = myFont.render('Medium', 1, white)
    elif prediction > 25 and prediction <= 40:
        speed_label = myFont.render('Fast', 1, white)
    else:
        speed_label = myFont.render('Very Fast', 1, white)

    A.append(prediction)
    line1.set_ydata(A)
    line1.set_xdata(range(len(A)))
    ax.relim()
    ax.autoscale_view()

    canvas = agg.FigureCanvasAgg(fig)
    canvas.draw()
    renderer = canvas.get_renderer()
    raw_data = renderer.tostring_rgb()
    size = canvas.get_width_height()
    surf = pygame.image.fromstring(raw_data, size, "RGB")
    screen.blit(surf, (0, 480))

    # draw on
    pygame.surfarray.blit_array(camera_surface, img.swapaxes(0, 1))
    screen.blit(camera_surface, (0, 0))

    diceDisplay = myFont.render(str(prediction), 1, white)
    screen.blit(randNumLabel, (50, 420))
    screen.blit(speed_label, (300, 420))
    screen.blit(diceDisplay, (50, 450))
    clock.tick(60)
    pygame.display.flip()
def DrawMask(GenMask=False):
    sz = 6
    gd = 40
    pygame.draw.rect(
        DISPLAYSURF, BG,
        (0, WINDOW_HEIGHT * .25, WINDOW_WIDTH, WINDOW_HEIGHT * .55))
    matrix = np.random.uniform(50, 30, gd * gd).reshape((gd, gd))
    fig = pylab.figure(figsize=(sz, sz), dpi=100)
    ax = fig.gca()
    ax.set_axis_off()
    ax.matshow(matrix, cmap=plt.cm.binary)
    bg = BG[0] / 255.
    fig.patch.set_facecolor(str(bg))
    canvas = agg.FigureCanvasAgg(fig)
    canvas.draw()
    renderer = canvas.get_renderer()
    raw_data = renderer.tostring_rgb()
    size = canvas.get_width_height()
    surf = pygame.image.fromstring(raw_data, size, "RGB")
    screen = DISPLAYSURF
    if GenMask:
        plt.close('all')
        return (surf, sz * 50)
    screen.blit(surf,
                (WINDOW_WIDTH * .5 - sz * 50, WINDOW_HEIGHT * .5 - sz * 50))
    update()
    plt.close('all')
Esempio n. 28
0
    def add_figure(self, tag, figure, step=None, close=True):
        """
        Logs a Matplotlib figure.

        Example:

        ```python
        with Logger() as logger:
            for trial in range(100):
                simulate(1000.0)
                fig = plt.figure()
                plt.plot(pop.r)
                logger.add_figure("Activity", fig, trial)
        ```

        :param tag: name of the image in tensorboard.
        :param figure: a list or 1D numpy array of values.
        :param step: time index.
        :param close: whether the logger will close the figure when done (default: True).
        """

        import matplotlib.pyplot as plt
        import matplotlib.backends.backend_agg as plt_backend_agg
        canvas = plt_backend_agg.FigureCanvasAgg(figure)
        canvas.draw()
        data = np.frombuffer(canvas.buffer_rgba(), dtype=np.uint8)
        w, h = figure.canvas.get_width_height()
        image_hwc = data.reshape([h, w, 4])[:, :, 0:3]
        image_chw = np.moveaxis(image_hwc, source=2, destination=0)
        if close:
            plt.close(figure)
        self._summary.add_image(tag, image_chw, step)
Esempio n. 29
0
def draw_fuelusing():

    color_back_fig = (20 / 255, 20 / 255, 20 / 255)

    mpl.rcParams.update({
        "lines.color": "white",
        "patch.edgecolor": "white",
        "text.color": "white",
        "axes.facecolor": color_back_fig,
        "axes.edgecolor": "lightgray",
        "axes.labelcolor": "white",
        "xtick.color": "white",
        "ytick.color": "white",
        "grid.color": "lightgray",
        "figure.facecolor": color_back_fig,
        "figure.edgecolor": "black",
        "savefig.facecolor": "black",
        "savefig.edgecolor": "black"
    })

    fig, ax = plt.subplots()
    x = numpy.linspace(0, 2, 10)
    plt.plot(consumptionx, consumptiony, label="Fogyasztás")
    plt.xlabel('Idő (sec)')
    plt.ylabel('Fogyasztás (l/100km)')
    plt.title("Átlagfogyasztás")
    plt.legend()

    canvas = agg.FigureCanvasAgg(fig)
    canvas.draw()
    renderer = canvas.get_renderer()
    size = canvas.get_width_height()
    return pygame.image.frombuffer(renderer.tostring_rgb(), size, "RGB")
Esempio n. 30
0
	def run(self):
		running = True
		self.screen.fill(BLACK)
		while running:
			for event in pygame.event.get():
				if event.type == pygame.QUIT:	running = False
				if event.type == pygame.KEYDOWN:
					running = False
			
			self.grid.particle_to_density()
			fig = plt.figure(figsize = (SCREENSIZE[0]/100.0,SCREENSIZE[1]/100.0), dpi = 100, frameon = False)
			#fig, ax = plt.subplots(1)
			fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
			plt.imshow(self.grid.grid.T/10**8, cmap = 'magma', vmin = 0, vmax = 2)
			plt.axis('off')
			plt.axis('tight')
			canvas = agg.FigureCanvasAgg(fig)
			plt.close()
			canvas.draw()
			renderer = canvas.get_renderer()
			raw_data = renderer.tostring_rgb()
			surf = pygame.image.fromstring(raw_data, canvas.get_width_height(), "RGB")
			self.screen.blit(surf, (0,0))
			self.grid.calculate_potential()
			self.grid.calculate_force()
			self.grid.update()
			
			pygame.display.flip()
			
		pygame.quit()
		sys.exit()