Пример #1
0
def fourth_alternating_code():
    code = [-1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, -1]
    x_1 = np.linspace(0, math.pi, 200)
    y_1 = np.sin(x_1)
    sin_fns = []
    for i in range(len(code)):
        x = np.linspace(2 * math.pi * i + math.pi / 2,
                        2 * math.pi * (i + 1) + math.pi / 2, 200)
        y = -np.sin(x) * code[i]
        sin_fns.append((x, y))

    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig.subplots_adjust(top=0.85)
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2, -1),
                           2 * math.pi,
                           1,
                           fill=True,
                           color='g',
                           alpha=0.5))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 2 * math.pi, 0),
                           4 * math.pi,
                           1,
                           fill=True,
                           color='g',
                           alpha=0.5))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 6 * math.pi, -1),
                           4 * math.pi,
                           1,
                           fill=True,
                           color='g',
                           alpha=0.5))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 10 * math.pi, 0),
                           2 * math.pi,
                           1,
                           fill=True,
                           color='g',
                           alpha=0.5))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 12 * math.pi, -1),
                           2 * math.pi,
                           1,
                           fill=True,
                           color='g',
                           alpha=0.5))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 14 * math.pi, 0),
                           2 * math.pi,
                           1,
                           fill=True,
                           color='g',
                           alpha=0.5))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 16 * math.pi, -1),
                           4 * math.pi,
                           1,
                           fill=True,
                           color='g',
                           alpha=0.5))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 20 * math.pi, 0),
                           2 * math.pi,
                           1,
                           fill=True,
                           color='g',
                           alpha=0.5))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 22 * math.pi, -1),
                           4 * math.pi,
                           1,
                           fill=True,
                           color='g',
                           alpha=0.5))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 2 * math.pi, -1),
                           0,
                           2,
                           fill=True,
                           color='#000000'))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 6 * math.pi, -1),
                           0,
                           2,
                           fill=True,
                           color='#000000'))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 10 * math.pi, -1),
                           0,
                           2,
                           fill=True,
                           color='#000000'))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 12 * math.pi, -1),
                           0,
                           2,
                           fill=True,
                           color='#000000'))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 14 * math.pi, -1),
                           0,
                           2,
                           fill=True,
                           color='#000000'))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 16 * math.pi, -1),
                           0,
                           2,
                           fill=True,
                           color='#000000'))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 20 * math.pi, -1),
                           0,
                           2,
                           fill=True,
                           color='#000000'))
    ax.add_patch(
        mpatches.Rectangle((math.pi / 2 + 22 * math.pi, -1),
                           0,
                           2,
                           fill=True,
                           color='#000000'))

    for i in range(len(sin_fns)):
        ax.plot(sin_fns[i][0], sin_fns[i][1], c='r')
    ax = fig.add_subplot(111)
    fig.subplots_adjust(top=0.85)

    ax.axis([0, 100, -5, 5])
    ax.axis('off')

    plt.show()
    plt.clf()
    autocorrelation = con_psl_matrix(code)
    x = []
    for i in range(len(autocorrelation)):
        x.append(i)

    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig.subplots_adjust(top=0.85)
    ax.scatter(x, np.abs(autocorrelation))
    ax.plot(x, np.abs(autocorrelation))
    ax.axis([-1, 30, -1, 15])
    ax.axis('off')
    plt.show()
    plt.clf()
Пример #2
0
def draw_rois(image,
              rois,
              refined_rois,
              mask,
              class_ids,
              class_names,
              limit=10):
    """
    anchors: [n, (y1, x1, y2, x2)] list of anchors in image coordinates.
    proposals: [n, 4] the same anchors but refined to fit objects better.
    """
    masked_image = image.copy()

    # Pick random anchors in case there are too many.
    ids = np.arange(rois.shape[0], dtype=np.int32)
    ids = np.random.choice(ids, limit,
                           replace=False) if ids.shape[0] > limit else ids

    fig, ax = plt.subplots(1, figsize=(12, 12))
    if rois.shape[0] > limit:
        plt.title("Showing {} random ROIs out of {}".format(
            len(ids), rois.shape[0]))
    else:
        plt.title("{} ROIs".format(len(ids)))

    # Show area outside image boundaries.
    ax.set_ylim(image.shape[0] + 20, -20)
    ax.set_xlim(-50, image.shape[1] + 20)
    ax.axis('off')

    for i, id in enumerate(ids):
        color = np.random.rand(3)
        class_id = class_ids[id]
        # ROI
        y1, x1, y2, x2 = rois[id]
        p = patches.Rectangle((x1, y1),
                              x2 - x1,
                              y2 - y1,
                              linewidth=2,
                              edgecolor=color if class_id else "gray",
                              facecolor='none',
                              linestyle="dashed")
        ax.add_patch(p)
        # Refined ROI
        if class_id:
            ry1, rx1, ry2, rx2 = refined_rois[id]
            p = patches.Rectangle((rx1, ry1),
                                  rx2 - rx1,
                                  ry2 - ry1,
                                  linewidth=2,
                                  edgecolor=color,
                                  facecolor='none')
            ax.add_patch(p)
            # Connect the top-left corners of the anchor and proposal for easy visualization
            ax.add_line(lines.Line2D([x1, rx1], [y1, ry1], color=color))

            # Label
            label = class_names[class_id]
            ax.text(rx1,
                    ry1 + 8,
                    "{}".format(label),
                    color='w',
                    size=11,
                    backgroundcolor="none")

            # Mask
            m = utils.unmold_mask(mask[id], rois[id][:4].astype(np.int32),
                                  image.shape)
            masked_image = apply_mask(masked_image, m, color)

    ax.imshow(masked_image)

    # Print stats
    print("Positive ROIs: ", class_ids[class_ids > 0].shape[0])
    print("Negative ROIs: ", class_ids[class_ids == 0].shape[0])
    print("Positive Ratio: {:.2f}".format(class_ids[class_ids > 0].shape[0] /
                                          class_ids.shape[0]))
Пример #3
0
def display_instances(image,
                      boxes,
                      masks,
                      class_ids,
                      class_names,
                      scores=None,
                      title="",
                      figsize=(16, 16),
                      ax=None,
                      show_mask=True,
                      show_bbox=True,
                      colors=None,
                      captions=None,
                      confidence_threshold=0.9):
    """
    boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates.
    masks: [height, width, num_instances]
    class_ids: [num_instances]
    class_names: list of class names of the dataset
    scores: (optional) confidence scores for each box
    title: (optional) Figure title
    show_mask, show_bbox: To show masks and bounding boxes or not
    figsize: (optional) the size of the image
    colors: (optional) An array or colors to use with each object
    captions: (optional) A list of strings to use as captions for each object
    """
    # Number of instances
    N = boxes.shape[0]
    if not N:
        print("\n*** No instances to display *** \n")
    else:
        assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]

    # If no axis is passed, create one and automatically call show()
    auto_show = False
    if not ax:
        fig, ax = plt.subplots(1, figsize=figsize)
        auto_show = True

    # Generate random colors
    colors = colors or random_colors(N)

    # Show area outside image boundaries.
    height, width = image.shape[:2]
    ax.set_ylim(height + 10, -10)
    ax.set_xlim(-10, width + 10)
    ax.axis('off')
    ax.set_title(title)

    masked_image = image.astype(np.uint32).copy()
    for i in range(N):
        if (scores[i] > confidence_threshold):
            color = colors[i]

            # Bounding box
            if not np.any(boxes[i]):
                # Skip this instance. Has no bbox. Likely lost in image cropping.
                continue
            y1, x1, y2, x2 = boxes[i]
            if show_bbox:
                p = patches.Rectangle((x1, y1),
                                      x2 - x1,
                                      y2 - y1,
                                      linewidth=2,
                                      alpha=0.7,
                                      linestyle="dashed",
                                      edgecolor=color,
                                      facecolor='none')
                ax.add_patch(p)

            # Label
            if not captions:
                class_id = class_ids[i]
                score = scores[i] if scores is not None else None
                label = class_names[class_id]
                caption = "{} {:.3f}".format(label, score) if score else label
            else:
                caption = captions[i]
            ax.text(x1,
                    y1 + 8,
                    caption,
                    color='w',
                    size=11,
                    backgroundcolor="none")

            # Mask
            mask = masks[:, :, i]
            if show_mask:
                masked_image = apply_mask(masked_image, mask, color)

            # Mask Polygon
            # Pad to ensure proper polygons for masks that touch image edges.
            padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2),
                                   dtype=np.uint8)
            padded_mask[1:-1, 1:-1] = mask
            contours = find_contours(padded_mask, 0.5)
            for verts in contours:
                # Subtract the padding and flip (y, x) to (x, y)
                verts = np.fliplr(verts) - 1
                p = Polygon(verts, facecolor="none", edgecolor=color)
                ax.add_patch(p)
    ax.imshow(masked_image.astype(np.uint8))
    if auto_show:
        fig.savefig("MaskRCNN_output.jpg",
                    bbox_inches="tight",
                    figsize=(height, width))
Пример #4
0
def deploy(model):

    transform = transforms.Compose(
        [transforms.Resize((300, 300)),
         transforms.ToTensor()])

    img_list = []
    img_names = []
    for root, _, files in os.walk("./sample_images"):
        for name in files:
            if not name.startswith("."):
                img_names.append(name)
                img = Image.open(os.path.join(root, name))
                img = transform(img)
                img_list.append(img)

    img_batch = torch.stack(img_list).to(model.device)

    np_imgs = []
    for k in range(img_batch.shape[0]):
        np_img = img_batch[k].detach().cpu().numpy()
        np_imgs.append(np.stack([np_img[0], np_img[1], np_img[2]], axis=2))

    model.eval()
    softmax = nn.Softmax(dim=1)
    out = model.forward(img_batch)
    for j in range(img_batch.shape[0]):
        flat_out = out[j]
        class_scores = flat_out[:, :model.num_classes]
        class_scores = softmax(class_scores)
        class_scores, class_labels = torch.max(class_scores, 1)
        index_helper = torch.arange(0,
                                    class_labels.shape[0],
                                    device=model.device,
                                    dtype=torch.long)
        valid_out_mask = class_labels > 0.4
        valid_out_indices = torch.masked_select(index_helper, valid_out_mask)

        raw_boxes = flat_out[:, model.num_classes:]
        reparam_boxes = torch.stack([
            model.wa_vec * raw_boxes[:, 0] + model.xa_vec,
            model.ha_vec * raw_boxes[:, 1] + model.ya_vec,
            model.wa_vec * torch.exp(raw_boxes[:, 2]),
            model.ha_vec * torch.exp(raw_boxes[:, 3])
        ],
                                    dim=1)

        reparam_boxes = torch.stack([
            reparam_boxes[:, 0] - 0.5 * reparam_boxes[:, 2],
            reparam_boxes[:, 1] - 0.5 * reparam_boxes[:, 3],
            reparam_boxes[:, 0] + 0.5 * reparam_boxes[:, 2],
            reparam_boxes[:, 1] + 0.5 * reparam_boxes[:, 3]
        ],
                                    dim=1)

        detected_boxes = reparam_boxes[valid_out_indices]
        detected_scores = class_scores[valid_out_indices]
        detected_labels = class_labels[valid_out_indices]

        good_box_indices = nms(detected_boxes,
                               detected_scores,
                               iou_threshold=0.5)
        detected_boxes = detected_boxes[good_box_indices]
        detected_scores = detected_scores[good_box_indices]
        detected_labels = detected_labels[good_box_indices]

        fig, ax = plt.subplots(1)
        ax.imshow(np_imgs[j])
        #print(detected_boxes.shape[0])
        for n in range(detected_boxes.shape[0]):
            x1 = detected_boxes[n, 0]
            y1 = detected_boxes[n, 1]
            x2 = detected_boxes[n, 2]
            y2 = detected_boxes[n, 3]
            rect_corner = x1, y1
            rect = patches.Rectangle(rect_corner,
                                     x2 - x1,
                                     y2 - y1,
                                     linewidth=1,
                                     edgecolor='r',
                                     facecolor='none')
            ax.add_patch(rect)
            #ax.text(x1, y1, "{}, {:.3f}".format(INV_COCO_DICT[int(detected_labels[n])], float(detected_scores[n])), color='r')
            ax.text(x1,
                    y1,
                    "{}, {:.3f}".format(INV_VOC_DICT[int(detected_labels[n])],
                                        float(detected_scores[n])),
                    color='r')

        plt.savefig("./sample_detections/" + img_names[j])
Пример #5
0
from PIL import Image
from matplotlib import patches
from io import BytesIO

response = requests.get(image_url)
image = Image.open(BytesIO(response.content))
print(faces)
plt.figure(figsize=(8, 8))
ax = plt.imshow(image, alpha=0.6)
for face in faces:
    fr = face["faceRectangle"]
    fa = face["faceAttributes"]
    origin = (fr["left"], fr["top"])
    p = patches.Rectangle(origin,
                          fr["width"],
                          fr["height"],
                          fill=False,
                          linewidth=2,
                          color='b')
    ax.axes.add_patch(p)
    plt.text(origin[0],
             origin[1],
             "%s, %d" % (fa["gender"].capitalize(), fa["age"]),
             fontsize=20,
             weight="bold",
             va="bottom")

    print(fa["gender"].capitalize(), fa["age"],
          max(fa["emotion"], key=fa["emotion"].get))
_ = plt.axis("off")
Пример #6
0
                start_time = time.time()
                trackers = mot_tracker.update(dets)
                cycle_time = time.time() - start_time
                total_time += cycle_time

                for d in trackers:
                    print('%d,%d,%.2f,%.2f,%.2f,%.2f,1,-1,-1,-1' %
                          (frame, d[4], d[0], d[1], d[2] - d[0], d[3] - d[1]),
                          file=out_file)
                    if (display):
                        d = d.astype(np.int32)
                        ax1.add_patch(
                            patches.Rectangle((d[0], d[1]),
                                              d[2] - d[0],
                                              d[3] - d[1],
                                              fill=False,
                                              lw=3,
                                              ec=colours[d[4] % 32, :]))
                        ax1.set_adjustable('box-forced')

                if (display):
                    fig.canvas.flush_events()
                    plt.draw()
                    ax1.cla()

    print("Total Tracking took: %.3f for %d frames or %.1f FPS" %
          (total_time, total_frames, total_frames / total_time))
    if (display):
        print(
            "Note: to get real runtime results run without the option: --display"
        )
Пример #7
0
def test(model, img_path):

    transform = transforms.Compose(
        [transforms.Resize((300, 300)),
         transforms.ToTensor()])

    pil_image = Image.open(img_path)  #.rotate(270)
    img_batch = transform(pil_image).unsqueeze(0)
    img_batch = img_batch.to(model.device)

    np_imgs = []
    for k in range(img_batch.shape[0]):
        np_img = img_batch[k].detach().cpu().numpy()
        np_imgs.append(np.stack([np_img[0], np_img[1], np_img[2]], axis=2))

    model.eval()
    softmax = nn.Softmax(dim=1)
    out = model.forward(img_batch)
    for j in range(img_batch.shape[0]):
        flat_out = out[j]
        class_scores = flat_out[:, :model.num_classes]
        class_scores = softmax(class_scores)
        class_scores, class_labels = torch.max(class_scores, 1)
        index_helper = torch.arange(0,
                                    class_labels.shape[0],
                                    device=model.device,
                                    dtype=torch.long)
        valid_out_mask = class_labels > 0.4
        valid_out_indices = torch.masked_select(index_helper, valid_out_mask)

        raw_boxes = flat_out[:, model.num_classes:]
        reparam_boxes = torch.stack([
            model.wa_vec * raw_boxes[:, 0] + model.xa_vec,
            model.ha_vec * raw_boxes[:, 1] + model.ya_vec,
            model.wa_vec * torch.exp(raw_boxes[:, 2]),
            model.ha_vec * torch.exp(raw_boxes[:, 3])
        ],
                                    dim=1)

        reparam_boxes = torch.stack([
            reparam_boxes[:, 0] - 0.5 * reparam_boxes[:, 2],
            reparam_boxes[:, 1] - 0.5 * reparam_boxes[:, 3],
            reparam_boxes[:, 0] + 0.5 * reparam_boxes[:, 2],
            reparam_boxes[:, 1] + 0.5 * reparam_boxes[:, 3]
        ],
                                    dim=1)

        detected_boxes = reparam_boxes[valid_out_indices]
        detected_scores = class_scores[valid_out_indices]
        detected_labels = class_labels[valid_out_indices]

        good_box_indices = nms(detected_boxes,
                               detected_scores,
                               iou_threshold=0.5)
        detected_boxes = detected_boxes[good_box_indices]
        detected_scores = detected_scores[good_box_indices]
        detected_labels = detected_labels[good_box_indices]

        fig, ax = plt.subplots(1)
        ax.imshow(np_imgs[j])
        print(detected_boxes.shape[0])
        for n in range(detected_boxes.shape[0]):
            x1 = detected_boxes[n, 0]
            y1 = detected_boxes[n, 1]
            x2 = detected_boxes[n, 2]
            y2 = detected_boxes[n, 3]
            rect_corner = x1, y1
            rect = patches.Rectangle(rect_corner,
                                     x2 - x1,
                                     y2 - y1,
                                     linewidth=1,
                                     edgecolor='r',
                                     facecolor='none')
            ax.add_patch(rect)
            #ax.text(x1, y1, "{}, {:.3f}".format(INV_COCO_DICT[int(detected_labels[n])], float(detected_scores[n])), color='r')
            ax.text(x1,
                    y1,
                    "{}, {:.3f}".format(INV_VOC_DICT[int(detected_labels[n])],
                                        float(detected_scores[n])),
                    color='r')

        plt.show()
Пример #8
0
def plot_corona(num_dic,
                day,
                month,
                name,
                ID,
                geraet_min=None,
                geraet_max=None,
                anteil_beatmung=0.05):
    '''
    Plots cumulative case numbers against time for the specific county. Fits for any dataset 
    larger than eight a exponential function and estimates the doubling time. For the fit only 
    the last eight data points are used to get a recent description of the evolution. Estimates the 
    the doubling time from every fit by taking the fitting constants b of the ``y = a * exp(b * x)``
    underlying theory into account::
    
    ``DT = ln(2)/b``
    
    Input
    =====
    
    num_dic :  dictionary {'fall': array, 'tod':array, 'gesund': array}
           Array of cumulative number of cases
    
    day : np.array
          String with 5 number entries to select the specific county.
    
    name : str
            Name of specific region
    
    ID : str 
            ID of county in Germany e.g. '09182' for LK Miesbach

    geraet_min : int, None
            Minimum capacity of intensive care

    geraet_max : int, default = None
            Maximum capacity of intensive care
    
    anteil_beatmung : float, default = 0.05
            Approximated fraction of demand for intensive care

    return
    ======
    
    DT : list
        Contains name of county, day array and DT array containing the 8 last data points 
        where fit was possible
    
        name : str
            Name of specific region
    
        day : np.array
            Array of 8 days before and including the fit day
    
        val_DT : list
            list containing the calculated day-depending doubling times
    
        rates : list
            list containing rates (mortality rate, recovery rate, still ill rate)
    
        pass_all : dict
            dictionary of daily values of new cases, deaths and recovered cases
    '''
    import matplotlib.pyplot as plt
    import numpy as np
    from scipy.optimize import curve_fit

    print '-' * 30
    print name
    print '-' * 30

    num = num_dic['fall'][num_dic['fall'] > 0]
    num_tod = num_dic['tod'][num_dic['fall'] > 0]
    num_gesund = num_dic['gesund'][num_dic['fall'] > 0]

    day = day[num_dic['fall'] > 0]
    month = month[num_dic['fall'] > 0]
    day_max = 150.
    day_ticks = [
        14, 18, 22, 26, 30, 3, 7, 11, 15, 19, 23, 27, 1, 5, 9, 13, 17, 21, 25,
        29, 2, 6, 10, 14, 18, 22, 26, 30, 3, 7, 11, 15, 19, 23, 27
    ]

    fig, ax = plt.subplots(4,
                           figsize=(10, 22),
                           gridspec_kw={'height_ratios': [3, 1, 1, 1]})

    ax[0].set_title(name + ' (#' + ID + ')')
    ax[0].axis([13, day_max, 0.9, 1e5])

    ax[0].set_title('Abb. 1', loc='right', fontsize=8)
    ax[1].axis([13, day_max, 0.8, 1e3])
    ax[1].set_title('Abb. 2', loc='right', fontsize=8)
    ax[2].set_xlim([13, day_max])
    ax[2].set_title('Abb. 3', loc='right', fontsize=8)
    ax[3].set_xlim([13, day_max])
    ax[3].set_title('Abb. 4', loc='right', fontsize=8)

    ####
    # move to March time frame
    #########
    day_real = np.copy(day)
    day[month == 2] = day[month == 2] - 29
    day[month == 1] = day[month == 1] - 29 - 31
    day[month == 4] = day[month == 4] + 31
    day[month == 5] = day[month == 5] + 31 + 30
    day[month == 6] = day[month == 6] + 31 + 30 + 31
    day[month == 7] = day[month == 7] + 31 + 30 + 31 + 30

    #print 'day now', day
    #print 'day_real', day_real

    #########
    # fit
    #########
    def func(x, a, b):  #, c):
        #return a * np.exp(b * x)# + c #
        #return a * b**(c*x)
        return np.log(a) + b * x  #log-linear

    x = np.arange(10, day_max, 0.5)

    # fit only when there are more than 6 data points and cases every day.
    data_points = range(8, len(day) + 1)

    DTs = []
    Ntot_today = []
    Ntot_week = []
    R4s = []

    col = 30
    colapp = []
    print 'Tag  DTs  R4'
    for cut in data_points:
        #print day[cut-8:cut]
        #print num[cut-8:cut]

        #########
        ### changed 8 fit
        #########
        #popt, pcov = curve_fit(func, day[:cut], num[:cut])
        popt, pcov = curve_fit(func, day[cut - 8:cut],
                               np.log(num[cut - 8:cut]))
        #print len(day[cut-8:cut])

        #####
        # loglog
        cond_week = day[cut - 8:cut] > day[cut - 1] - 7
        num_week = num[cut - 8:cut][cond_week]

        Ntot_today.append(num[cut - 8:cut][-1])
        Ntot_week.append(num_week[-1] - num_week[0])

        ########
        # Reproduction number for Rtime notification days (4 days strict)

        #%%%%%%%%#daytoday = int(day[cut-1])
        #%%%%%%%%#dayminus4 = int(daytoday - 5)
        #%%%%%%%%#dayminus8 = int(daytoday - 9)
        #%%%%%%%%#print daytoday, dayminus4, dayminus8
        #%%%%%%%%#
        #%%%%%%%%#print num[day == daytoday], num[day == dayminus4], num[day == dayminus8]
        #%%%%%%%%#
        #%%%%%%%%#R4_row = (num[day == daytoday] - num[day == dayminus4]) / (num[day == dayminus4] - num[day == dayminus8])
        #%%%%%%%%#print R4_row
        #%%%%%%%%#
        #%%%%%%%%#raise Exception('stop')

        ########
        # Reproduction number for Rtime notification days
        #print num[cut-8:cut]

        if cut - 9 < 0:
            num_before_int = num[cut - 8:cut][0]
        else:
            num_before_int = num[cut - 8] - num[cut - 9]
        num_diff_8 = np.append(num_before_int, np.diff(num[cut - 8:cut]))
        #print num_diff_8

        R4 = np.sum(num_diff_8[4:]) / np.sum(num_diff_8[0:4])
        R4s.append(R4)
        #print num_diff_8[0:4], num_diff_8[4:]

        #########
        # doubling time
        #########
        DT = np.round(np.log(2) / popt[1], 2)
        #print DT#,  popt
        DTs.append(DT)
        #print popt, np.log(2) / popt[1]

        print '%02d' % int(day_real[cut - 1]) + '.' + '%02d' % int(
            month[cut - 1]), '%6.2f' % DT  #, '%6.2f'%R4

        #print("a =", popt[0], "+/-", pcov[0,0]**0.5)
        #print("b =", popt[1], "+/-", pcov[1,1]**0.5)
        #print("c =", popt[2], "+/-", pcov[2,2]**0.5)

        ##########
        # plot
        ##########

        ########
        # plot fit
        #########
        day_label = 'Fit am ' + '%02d' % int(
            day_real[cut - 1]) + '.' + '%02d' % int(
                month[cut - 1]) + '; VZ: ' + '%6.2f' % DT + ' d'
        ax[0].semilogy(x,
                       np.exp(func(x, *popt)),
                       '-',
                       color=plt.cm.viridis(int(col)),
                       label=day_label)

        colapp.append(int(col))
        col = col + 256 / len(data_points)

        ########
        # plot Beatmungsbedarf
        #########
        if cut == data_points[-1]:

            # Beatmungsampel
            bedarf = anteil_beatmung * np.exp(func(x, *popt))

            ax[0].semilogy(x,
                           bedarf,
                           '-',
                           lw=3,
                           color=plt.cm.Reds(200),
                           label='Ampel (Beatmungsbedarf ca. ' +
                           str(int(anteil_beatmung * 100)) + '%)')
            ax[0].semilogy(x[(bedarf < geraet_max)],
                           bedarf[(bedarf < geraet_max)],
                           '-',
                           lw=3,
                           color=plt.cm.jet(180),
                           label='Ampel (Beatmungsbedarf ca. ' +
                           str(int(anteil_beatmung * 100)) + '%)')
            ax[0].semilogy(x[bedarf < geraet_min],
                           bedarf[bedarf < geraet_min],
                           '-',
                           lw=3,
                           color=plt.cm.Greens(200),
                           label='Ampel (Beatmungsbedarf ca. ' +
                           str(int(anteil_beatmung * 100)) + '%)')

            # Fehler
            ax[0].semilogy(
                x,
                0.05 * np.exp(
                    func(x, popt[0] - pcov[0, 0]**0.5,
                         popt[1] - pcov[1, 1]**0.5)),
                #popt[2] - pcov[2,2]**0.5),
                '--',
                color='k',
                alpha=0.5,
                label='Unsicherheiten')
            ax[0].semilogy(
                x,
                0.05 * np.exp(
                    func(x, popt[0] + pcov[0, 0]**0.5,
                         popt[1] + pcov[1, 1]**0.5)),
                #popt[2] + pcov[2,2]**0.5),
                '--',
                color='k',
                alpha=0.5)

    #print 'day now2', day

    ####
    # Beatmungs Kapazitaet
    #########
    ax[0].plot([x[0], x[-1]], [geraet_min] * 2,
               'k:',
               label="Kapazitaet Beatmungsapparate")
    ax[0].plot([x[0], x[-1]], [geraet_max] * 2, 'k:')

    ####
    # gemeldete Fallzahlen
    #########
    ax[0].semilogy(day, num, 'k+', label="COVID19 erkrankt")
    ax[0].semilogy(day, num_tod, 'k*', label="davon verstorben")
    ax[0].semilogy(day, num_gesund, 'ko', alpha=0.3, label="davon genesen")

    #print 'day now3', day

    print '+' * 30
    print 'Sterberate (%): ', np.round(num_tod[-1] / num[-1] * 100, 2)
    print 'Gesunde (%):    ', np.round(num_gesund[-1] / num[-1] * 100, 2)
    print '+' * 30

    #############
    # formating
    #############

    from matplotlib.ticker import ScalarFormatter
    for axis in [ax[0].xaxis, ax[0].yaxis]:
        axis.set_major_formatter(ScalarFormatter())

    ax[0].grid(True, which="both")
    ax[0].set_xticks(np.arange(14, day_max, 4))
    ax[0].set_xticklabels(day_ticks)

    ax[0].text(13, 0.5, 'Mar')
    ax[0].text(31, 0.5, 'Apr')
    ax[0].text(31 + 30, 0.5, 'Mai')
    ax[0].text(31 + 30 + 31, 0.5, 'Juni')
    ax[0].text(31 + 30 + 31 + 30, 0.5, 'Juli')

    ax[0].annotate('Ausgangssperre',
                   ha='center',
                   xy=(21, ax[0].get_ylim()[0]),
                   xytext=(21, 0.4),
                   arrowprops=dict(arrowstyle='-|>',
                                   color='grey',
                                   lw=2,
                                   ls='-'),
                   alpha=0.6)
    ax[0].annotate('Ostern',
                   ha='center',
                   xy=(31 + 12, ax[0].get_ylim()[0]),
                   xytext=(31 + 12, 0.4),
                   arrowprops=dict(arrowstyle='-|>',
                                   color='grey',
                                   lw=2,
                                   ls='-'),
                   alpha=0.6)
    ax[0].annotate('Ende Ferien',
                   ha='center',
                   xy=(31 + 20, ax[0].get_ylim()[0]),
                   xytext=(31 + 20, 0.4),
                   arrowprops=dict(arrowstyle='-|>',
                                   color='grey',
                                   lw=2,
                                   ls='-'),
                   alpha=0.6)

    # credit bar
    credit = 'Christine Greif\nhttp://www.usm.uni-muenchen.de/~koepferl\nThis work is licensed under CC-BY-SA 4.0\nData: NPGEO-DE; VZ = Verdopplungszeit'
    loc_label = ax[0].get_xlim()[1] * 1.12
    link = ax[0].text(loc_label, 9e4, credit, fontsize=8, va='top')
    link.set_url('http://www.usm.uni-muenchen.de/~koepferl')

    # label
    ax[0].set_ylabel('Gesamte Fallzahlen')
    lgd = ax[0].legend(loc='best', bbox_to_anchor=(1.12, 0.93))

    # percent
    #########
    EW_county = get_people_of_county(asked_ID=ID)

    axi = ax[0].twinx()

    #print 'lim', ax.get_ylim(), ax.get_ylim()[0] / EW_county * 100, ax.get_ylim()[1] / EW_county * 100, EW_county
    axi.set_ylim(ax[0].get_ylim()[0] / EW_county * 100,
                 ax[0].get_ylim()[1] / EW_county * 100)
    axi.set_yscale('log')
    import matplotlib.ticker as mtick
    import matplotlib.ticker as ticker
    axi.yaxis.set_major_formatter(ScalarFormatter())
    axi.yaxis.set_major_formatter(
        ticker.FuncFormatter(lambda y, pos: ('{{:.{:1d}f}}%'.format(
            int(np.maximum(-np.log10(y), 0)))).format(y)))
    #axi.yaxis.set_major_formatter(FormatStrFormatter('%4d'))
    #axi.yaxis.set_major_formatter(mtick.PercentFormatter())
    axi.set_ylabel('Prozentualer Anteil zur Gesamteinwohnerzahl (' +
                   str(EW_county) + ') im Kreis')

    ###########
    # plot 2
    ###########
    pass_all = {
        'day': day,
        'fall': np.append(num[0], np.diff(num)),
        'gesund': np.append(num_gesund[0], np.diff(num_gesund)),
        'tod': np.append(num_tod[0], np.diff(num_tod))
    }

    ax[1].set_ylabel('Taeglich gemeldete Fallzahlen')

    # gemittelt ueber 7 Tage
    all_smooth = np.zeros(shape=day[6:].shape)
    tod_smooth = np.zeros(shape=day[6:].shape)
    gesund_smooth = np.zeros(shape=day[6:].shape)

    for z in range(7):
        stop = -6 + z
        #print z, stop
        if stop != 0:
            all_smooth = all_smooth + 1 / 7. * pass_all['fall'][z:stop]
            tod_smooth = tod_smooth + 1 / 7. * pass_all['tod'][z:stop]
            gesund_smooth = gesund_smooth + 1 / 7. * pass_all['gesund'][z:stop]
        else:
            all_smooth = all_smooth + 1 / 7. * pass_all['fall'][z:]
            tod_smooth = tod_smooth + 1 / 7. * pass_all['tod'][z:]
            gesund_smooth = gesund_smooth + 1 / 7. * pass_all['gesund'][z:]

    #all_smooth = 0.25 * (pass_all['fall'][0:-3] + pass_all['fall'][1:-2] + pass_all['fall'][2:-1] + pass_all['fall'][3:0])
    #tod_smooth = 0.25 * (pass_all['tod'][0:-3] + pass_all['tod'][1:-2] + pass_all['tod'][2:-1] + pass_all['tod'][3:0])
    #gesund_smooth = 0.25 * (pass_all['gesund'][0:-3] + pass_all['gesund'][1:-2] + pass_all['gesund'][2:-1] + pass_all['gesund'][3:0])

    ax[1].semilogy(day[6:],
                   all_smooth,
                   'r-',
                   label='neu erkrankt (7-Tagesmittel)')
    ax[1].semilogy(day[6:],
                   tod_smooth,
                   'k-',
                   label='verstorben (7-Tagesmittel)')
    ax[1].semilogy(day[6:],
                   gesund_smooth,
                   'k-',
                   alpha=0.3,
                   label='genesen (7-Tagesmittel)')

    # box
    import matplotlib.patches as patches
    for b in range(len(day)):
        if b == 0:
            label_fall = "neu erkrankt"
            label_gesund = 'genesen'
            label_tod = 'verstorben'
        else:
            label_fall = None
            label_gesund = None
            label_tod = None

        ax[1].add_patch(
            patches.Rectangle((day[b] - 0.45, 0.),
                              0.9,
                              pass_all['fall'][b],
                              linewidth=1,
                              edgecolor='k',
                              facecolor=plt.cm.jet(180),
                              label=label_fall))
        ax[1].add_patch(
            patches.Rectangle((day[b] - 0.45, 0.),
                              0.9,
                              pass_all['gesund'][b],
                              linewidth=1,
                              edgecolor='k',
                              facecolor='None',
                              label=label_gesund,
                              hatch='////'))
        ax[1].add_patch(
            patches.Rectangle((day[b] - 0.45, 0.),
                              0.9,
                              pass_all['tod'][b],
                              linewidth=1,
                              edgecolor='k',
                              facecolor='w',
                              label=label_tod))

    #h = ax[1].hist(pass_all['fall'], bins=np.append(day - 0.5, day[-1] + 0.5))
    #print h
    #print pass_all['fall']
    #ax[1].hist(pass_all['tod'], bins=day)
    #ax[1].hist(pass_all['gesund'], bins=day)

    from matplotlib.ticker import ScalarFormatter
    for axis in [ax[1].xaxis, ax[1].yaxis]:
        axis.set_major_formatter(ScalarFormatter())

    ax[1].set_axisbelow(True)
    ax[1].grid(True, which="both")
    ax[1].set_xticks(np.arange(14, day_max, 4))
    ax[1].set_xticklabels(day_ticks)

    tx1 = ax[1].text(13, 0.3, 'Mar')
    tx2 = ax[1].text(31, 0.3, 'Apr')
    tx3 = ax[1].text(31 + 30, 0.3, 'Mai')
    tx4 = ax[1].text(31 + 30 + 31, 0.3, 'Juni')
    tx5 = ax[1].text(31 + 30 + 31 + 30, 0.3, 'Juli')

    ax[1].annotate('Ausgangssperre',
                   ha='center',
                   xy=(21, ax[1].get_ylim()[0]),
                   xytext=(21, 0.2),
                   arrowprops=dict(arrowstyle='-|>',
                                   color='grey',
                                   lw=2,
                                   ls='-'),
                   alpha=0.6)
    ax[1].annotate('Ostern',
                   ha='center',
                   xy=(31 + 12, ax[1].get_ylim()[0]),
                   xytext=(31 + 12, 0.2),
                   arrowprops=dict(arrowstyle='-|>',
                                   color='grey',
                                   lw=2,
                                   ls='-'),
                   alpha=0.6)
    ax[1].annotate('Ende Ferien',
                   ha='center',
                   xy=(31 + 20, ax[1].get_ylim()[0]),
                   xytext=(31 + 20, 0.2),
                   arrowprops=dict(arrowstyle='-|>',
                                   color='grey',
                                   lw=2,
                                   ls='-'),
                   alpha=0.6)

    ax[1].legend(loc='best')

    ###########
    # plot 3
    ###########
    ax[2].set_ylabel('Verdopplungszeiten in Tage')
    ax[2].plot(ax[2].get_xlim(), [10, 10],
               ':',
               lw=2,
               color='grey',
               label='VZ = 10')
    ax[2].plot(day[7:], np.array(DTs), 'k.-')

    #from scipy.signal import find_peaks
    #peaks, _ = find_peaks(np.array(DTs))
    #print 'peaks', peaks
    #ax[2].plot(peaks, np.array(DTs)[peaks], "Hb")

    #ax[2].plot(day[7:], np.gradient(DTs, day[7:]), 'ko-')
    diff = np.diff(DTs)
    ax[2].plot(day[7:][1:][diff < 0],
               np.array(DTs)[1:][diff < 0],
               '^',
               color=plt.cm.Reds(200),
               label='Achtung: VZ faellt (!!!)')
    #ax[2].plot(day[7:][1:], diff, 'k^-')

    #print 'gradient', gradient
    #print 'diff', np.diff(DTs)

    ax[2].grid(True, which="both")
    ax[2].set_xticks(np.arange(14, day_max, 4))
    ax[2].set_xticklabels(day_ticks)

    ax[2].legend(loc='best')
    offset = ax[2].get_ylim()[0] - (ax[2].get_ylim()[1] -
                                    ax[2].get_ylim()[0]) / 5.
    tx1 = ax[2].text(13, offset, 'Mar')
    tx2 = ax[2].text(31, offset, 'Apr')
    tx3 = ax[2].text(31 + 30, offset, 'Mai')
    tx4 = ax[2].text(31 + 30 + 31, offset, 'Juni')
    tx5 = ax[2].text(31 + 30 + 31 + 30, offset, 'Juli')

    ax[2].annotate('Lock-down',
                   ha='center',
                   xy=(21, ax[2].get_ylim()[0]),
                   xytext=(21, offset),
                   arrowprops=dict(arrowstyle='-|>',
                                   color='grey',
                                   lw=2,
                                   ls='-'),
                   alpha=0.6)
    ax[2].annotate('Ostern',
                   ha='center',
                   xy=(31 + 12, ax[2].get_ylim()[0]),
                   xytext=(31 + 12, offset),
                   arrowprops=dict(arrowstyle='-|>',
                                   color='grey',
                                   lw=2,
                                   ls='-'),
                   alpha=0.6)
    ax[2].annotate('Ende Ferien',
                   ha='center',
                   xy=(31 + 20, ax[2].get_ylim()[0]),
                   xytext=(31 + 20, offset),
                   arrowprops=dict(arrowstyle='-|>',
                                   color='grey',
                                   lw=2,
                                   ls='-'),
                   alpha=0.6)

    ###########
    # plot 4
    ###########

    ########
    # Reproduction number for Rtime notification days (4 days interpoliert)

    minus8 = np.interp(day - 8 - 1, day, num)
    minus4 = np.interp(day - 4 - 1, day, num)
    minus_all = np.interp(np.arange(day[0], day[-1]), day, num)
    #print day - 8 - 1
    #print day
    #print num
    #print day - 4 - 1

    #for i in range(len(np.arange(day[0], day[-1]))):
    #    print np.arange(day[0], day[-1])[i], minus_all[i]

    R_number_interp = (num - minus4) / (minus4 - minus8)
    R_number_interp[day - 8 - 1 < day[0]] = np.nan  # before 1st case
    R_number_interp[day - 4 - 1 < day[0]] = np.nan  # before 1st case

    #for da in day:
    #    if da-4 < day[0]:
    #        new_minus4 = 0
    #    else: new_minus4 = np.interp(da-4, day, num)
    #    if da-8 < day[0]:
    #        new_minus8 = 0
    #    else:
    #        new_minus8 = np.interp(da-8, day, num)

    ax[3].set_ylabel('Interpolierte Reproduktionszahl')

    ax[3].plot(ax[3].get_xlim(), [1, 1],
               ':',
               lw=2,
               color='grey',
               label='R = 1')
    ax[3].plot(day, R_number_interp, 'k.-')
    ax[3].plot(day[R_number_interp >= 1],
               R_number_interp[R_number_interp >= 1],
               '^',
               color=plt.cm.Reds(200),
               label='Achtung: R > 1 (!!!)')

    ax[3].grid(True, which="both")
    ax[3].set_xticks(np.arange(14, day_max, 4))
    ax[3].set_xticklabels(day_ticks)
    ax[3].legend(loc='best')

    offset = ax[3].get_ylim()[0] - (ax[3].get_ylim()[1] -
                                    ax[3].get_ylim()[0]) / 5.
    tx1 = ax[3].text(13, offset, 'Mar')
    tx2 = ax[3].text(31, offset, 'Apr')
    tx3 = ax[3].text(31 + 30, offset, 'Mai')
    tx4 = ax[3].text(31 + 30 + 31, offset, 'Juni')
    tx5 = ax[3].text(31 + 30 + 31 + 30, offset, 'Juli')
    ax[3].annotate('Lock-down',
                   ha='center',
                   xy=(21, ax[3].get_ylim()[0]),
                   xytext=(21, offset),
                   arrowprops=dict(arrowstyle='-|>',
                                   color='grey',
                                   lw=2,
                                   ls='-'),
                   alpha=0.6)
    ax[3].annotate('Ostern',
                   ha='center',
                   xy=(31 + 12, ax[3].get_ylim()[0]),
                   xytext=(31 + 12, offset),
                   arrowprops=dict(arrowstyle='-|>',
                                   color='grey',
                                   lw=2,
                                   ls='-'),
                   alpha=0.6)
    ax[3].annotate('Ende Ferien',
                   ha='center',
                   xy=(31 + 20, ax[3].get_ylim()[0]),
                   xytext=(31 + 20, offset),
                   arrowprops=dict(arrowstyle='-|>',
                                   color='grey',
                                   lw=2,
                                   ls='-'),
                   alpha=0.6)

    ax[3].text(
        ax[3].get_xlim()[1] * 1.02, ax[3].get_ylim()[1] * 1.,
        'zu Abb. 1: \nBei Kreisen mit sehr kurzen Verdopplungszeiten wird \nder Verlauf nicht/kaum flacher; mit sehr langen \nVerdopplungszeiten (wenigen Neuerkrankten) \nist der Verlauf fast horizontal. \n(Ziel: horizontale Linie).'
    )

    ax[3].text(
        ax[3].get_xlim()[1] * 1.02, ax[3].get_ylim()[1] * 0.75,
        'zu Abb. 2: \nBalkendiagramm der taeglich gemeldeten Fallzahlen. \n(Ziel: keine gelben und weissen Balken.)'
    )

    ax[3].text(
        ax[3].get_xlim()[1] * 1.02, ax[3].get_ylim()[1] * 0.35,
        'zu Abb. 3: \nVerdopplungszahl gibt die Zeit an in der sich die \nFallzahlen verdoppeln. Verdopplungszeiten kleiner \nals 10 oder abnehmend sind bedenklich. \n(Ziel: keine verkuerzenden Verdopplungszeiten \nund viel groesser als 10).'
    )

    ax[3].text(
        ax[3].get_xlim()[1] * 1.02, ax[3].get_ylim()[0],
        'zu Abb. 4: \nReproduktionszahl gibt die Anzahl der \nWeiteransteckungen durch einen Infizierten an. \nReproduktionszahl groesser als 1 ist bedenklich. \n(Ziel: Reproduktionszahl viel kleiner als 1).'
    )

    fig.savefig('expert/' + name + '_expert.pdf',
                dpi=300,
                overwrite=True,
                bbox_inches='tight',
                bbox_extra_artists=(lgd, tx1, tx2, tx3, tx4, tx5))

    ##################
    # save plot ax[0]
    ##################

    ax[1].remove()
    ax[2].remove()
    ax[3].remove()
    #for a in ax:
    #    print 'ax'
    #fig.set_size_inches(10, 8)
    #ax[0].set_aspect(aspect=0.5)
    #fig.set_gridspec_kw({'height_ratios': [1, 0, 0, ]})
    #fig.gridspec_kw({'height_ratios': [1]})

    #extent = ax[0].get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    # Pad the saved area by 10% in the x-direction and 20% in the y-direction
    fig.savefig('plots/' + name + '.pdf',
                dpi=300,
                overwrite=True,
                bbox_extra_artists=(lgd, tx1, tx2, tx3, tx4, tx5),
                bbox_inches='tight')

    rates = {
        'death_rate': num_tod / num * 100,
        'recover_rate': num_gesund / num * 100,
        'ill_rate': (num - num_gesund - num_tod) / num * 100,
        'day': day
    }

    return [name, day[7:], DTs, Ntot_today, Ntot_week, rates, R4s, pass_all]
Пример #9
0
                     # plt.text(seis[0].stats.traveltimes[k]-seis[0].stats.traveltimes[phase],np.round(seis[0].stats['az'])-0.5, k)
            
    timewindow = 3*20    
#          w0 = np.argmin(np.abs(seistoplot.times-phase_time+timewindow/3))            
#          w1 = np.argmin(np.abs(seistoplot.times-phase_time-timewindow*2/3))
#          window_wid = seistoplot.times[w1] - seistoplot.times[w0]
#          window_hei = np.max(np.abs(hilbert(seistoplot.data[w0:w1])))/norm
#        #                test_w0 = np.argmin(np.abs(seistoplot.times()-phase_time+(-1)))            
#        #                test_w1 = np.argmin(np.abs(seistoplot.times()-phase_time-149))     
#        #                test_window_hei = np.max(np.abs(hilbert(seistoplot.data[test_w0:test_w1])))/norm
#        #                print('Window difference: '+str( (test_window_hei-window_hei)/window_hei))
#          gca().add_patch(patches.Rectangle((seistoplot.times[w0]-phase_time,np.round(seis[0].stats['az'])-window_hei),window_wid,2*window_hei,alpha = 0.2, color = 'red'))  # width height            
    w0_ref = np.argmin(np.abs(seistoplot.timesarray-phase_time-select_time_min))        # arg of ref, adapative time window     
    w1_ref = np.argmin(np.abs(seistoplot.timesarray-phase_time-select_time_max))   
    A0 = np.max(np.abs(hilbert(seistoplot.data[w0_ref:w1_ref])))/norm                
    gca().add_patch(patches.Rectangle((seistoplot.timesarray[w0_ref]-phase_time,np.round(seis[0].stats['az'])-A0),seistoplot.timesarray[w1_ref]-seistoplot.timesarray[w0_ref],2*A0,alpha = 0.05, color = 'y'))
    threshold = A0 #np.max(seistoplot.data/norm)
    print('NORM VALUE: ' + str(norm)+ ' ; ' + 'threshold = ' + str(threshold))    
    if ((threshold>threshold_max or threshold<threshold_min)):  #(threshold>5 or threshold<0.02):
        strange_trace.append([s,s_name,seis[0].stats['az'],seis[0].stats['dist'],threshold])   
# Put labels on graphs
print('!!!!!!!!!!!!!!!!!!!Stange Traces:----------------------->>>>>>')
print(strange_trace)

plt.ylim(azim_min,azim_max)
plt.xlabel('time around predicted arrival (s)')
plt.ylabel('azimuth (dg)')
if switch_yaxis:
   plt.gca().invert_yaxis()

plt.suptitle('Waveform with Azimuth\n Event %s' % Event)
Пример #10
0
def display_windows_sampling(x, y, window_size, skip=0, method='standard'):
    """ Displays a map of the interrogation points and windows
    
    
    Parameters
    ----------
    x : 2d np.ndarray
        a two dimensional array containing the x coordinates of the 
        interrogation window centers, in pixels.
        
    y : 2d np.ndarray
        a two dimensional array containing the y coordinates of the 
        interrogation window centers, in pixels.

    window_size : the interrogation window size, in pixels
    
    skip : the number of windows to skip on a row during display. 
           Recommended value is 0 or 1 for standard method, can be more for random method
           -1 to not show any window

    method : can be only <standard> (uniform sampling and constant window size)
                         <random> (pick randomly some windows)
    
    Examples
    --------
    
    >>> openpiv.tools.display_windows_sampling(x, y, window_size=32, skip=0, method='standard')

    
    """

    fig = pl.figure()
    if skip < 0 or skip + 1 > len(x[0]) * len(y):
        fig.canvas.set_window_title('interrogation points map')
        pl.scatter(x, y, color='g')  #plot interrogation locations
    else:
        nb_windows = len(x[0]) * len(y) / (skip + 1)
        #standard method --> display uniformly picked windows
        if method == 'standard':
            pl.scatter(x, y,
                       color='g')  #plot interrogation locations (green dots)
            fig.canvas.set_window_title('interrogation window map')
            #plot the windows as red squares
            for i in range(len(x[0])):
                for j in range(len(y)):
                    if j % 2 == 0:
                        if i % (skip + 1) == 0:
                            x1 = x[0][i] - window_size / 2
                            y1 = y[j][0] - window_size / 2
                            pl.gca().add_patch(
                                pt.Rectangle((x1, y1),
                                             window_size,
                                             window_size,
                                             facecolor='r',
                                             alpha=0.5))
                    else:
                        if i % (skip + 1) == 1 or skip == 0:
                            x1 = x[0][i] - window_size / 2
                            y1 = y[j][0] - window_size / 2
                            pl.gca().add_patch(
                                pt.Rectangle((x1, y1),
                                             window_size,
                                             window_size,
                                             facecolor='r',
                                             alpha=0.5))
        #random method --> display randomly picked windows
        elif method == 'random':
            pl.scatter(x, y, color='g')  #plot interrogation locations
            fig.canvas.set_window_title(
                'interrogation window map, showing randomly ' +
                str(nb_windows) + ' windows')
            for i in range(nb_windows):
                k = np.random.randint(len(x[0]))  #pick a row and column index
                l = np.random.randint(len(y))
                x1 = x[0][k] - window_size / 2
                y1 = y[l][0] - window_size / 2
                pl.gca().add_patch(
                    pt.Rectangle((x1, y1),
                                 window_size,
                                 window_size,
                                 facecolor='r',
                                 alpha=0.5))
        else:
            raise ValueError(
                'method not valid: choose between standard and random')
    pl.draw()
    pl.show()
Пример #11
0
            detections = rescale_boxes(detections, opt.img_size, img.shape[:2])
            unique_labels = detections[:, -1].cpu().unique()
            n_cls_preds = len(unique_labels)
            bbox_colors = random.sample(colors, n_cls_preds)
            for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections:

                print("\t+ Label: %s, Conf: %.5f" % (classes[int(cls_pred)], cls_conf.item()))

                box_w = x2 - x1
                box_h = y2 - y1

                detection_file.writelines(str(img_i+1)+",-1,"+str(x1.item())+","+str(y1.item())+","+str(box_w.item())+","+str(box_h.item())+","+str(cls_conf.item())+",-1,-1,-1\n" )

                color = bbox_colors[int(np.where(unique_labels == int(cls_pred))[0])]
                # Create a Rectangle patch
                bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor="none")
                # Add the bbox to the plot
                ax.add_patch(bbox)
                # Add label
                plt.text(
                    x1,
                    y1,
                    s=classes[int(cls_pred)],
                    color="white",
                    verticalalignment="top",
                    bbox={"color": color, "pad": 0},
                )

        # Save generated image with detections
        plt.axis("off")
        plt.gca().xaxis.set_major_locator(NullLocator())
Пример #12
0
def main():
    #load data
    # object_data = np.load('/home/lyn/policies/push-v9/object_data.npy')
    # robot_data = np.load('/home/lyn/policies/push-v9/robot_data.npy')

    # object_data = np.load('/home/lyn/HitLyn/Push/new_data/object_pure_test.npy').reshape(-1, 13)
    # object_data = np.load('/home/lyn/HitLyn/Push/generated_trajectory/new_no_weights_loaded.npy').reshape(-1, 3)
    object_data = np.load(
        '/home/lyn/HitLyn/Push/generated_trajectory_randomized/194/194.npy'
    ).reshape(-1, 101, 3)
    # object_data = np.load('/home/lyn/HitLyn/Push/generated_trajectory_randomized/real/object_data.npy').reshape(-1, 3)
    robot_data = np.load(
        '/home/lyn/HitLyn/Push/new_data_randomized/194/robot_data.npy'
    ).reshape(-1, 101, 6)
    # robot_data = np.load('/home/lyn/HitLyn/Push/generated_trajectory_randomized/real/robot_data.npy').reshape(-1, 3)
    # object_data = object_data[:, :30, :].reshape(-1, 3)
    # robot_data = robot_data[:, :30, :].reshape(-1, 6)
    # object_data = np.load('/home/lyn/HitLyn/Push/imagine_trajectory/object.npy').reshape(-1, 3)
    # robot_data = np.load('/home/lyn/HitLyn/Push/imagine_trajectory/robot.npy').reshape(-1, 2)
    # print(object_data[0], object_data[1], object_data[2])
    # object_data = np.load('/home/lyn/policies/randomized_push_data/randomized_env_0/object_data.npy').reshape(-1, 13)
    # robot_data = np.load('/home/lyn/policies/randomized_push_data/randomized_env_0/robot_data.npy').reshape(-1, 6)

    #data process
    object_position_center = object_data[:, :
                                         2]  # get the left bottom conrner of the object

    # object_rotation_d = np.degrees(np.arccos(object_data[:, 3]) * 2).reshape(-1, 1) # rotation degrees
    # object_rotation_r = (np.arccos(object_data[:, 3]) * 2).reshape(-1, 1)
    #
    object_rotation_d = np.degrees(object_data[:, 2]).reshape(
        -1, 1)  # rotation degrees
    object_rotation_r = (object_data[:, 2]).reshape(-1, 1)

    object_position_left_corner = object_position_center - 0.121 * np.concatenate(
        (np.sin(np.pi / 4 - object_rotation_r),
         np.cos(np.pi / 4 - object_rotation_r)),
        axis=1)

    robot_position = robot_data[:, :2]

    #plot
    fig = plt.figure()
    # ax = plt.axes(xlim = (0.0, 1.0), ylim = (0.0, 1.0))
    ax = plt.axes(xlim=(0.8, 1.8), ylim=(0.2, 1.2))
    patch_object = patches.Rectangle((1, 1), 0.171, 0.171, fc='y')
    patch_robot = patches.Circle((1, 1), 0.003, fc='b')

    def init_object():
        patch_object.set_xy([
            object_position_left_corner[0, 0], object_position_left_corner[0,
                                                                           1]
        ])
        patch_object.angle = object_rotation_d[0, 0]
        ax.add_patch(patch_object)

        patch_robot.center = (robot_position[0, 0], robot_position[0, 1])
        ax.add_patch(patch_robot)

        return patch_object, patch_robot,

    def init_robot():
        patch_robot.center = (robot_position[0, 0], robot_position[0, 1])
        ax.add_patch(patch_robot)
        return patch_robot,

    def animate_object(i):
        x = object_position_left_corner[i, 0]
        y = object_position_left_corner[i, 1]
        patch_object.set_xy([x, y])
        patch_object.angle = object_rotation_d[i, 0]

        x_ = robot_position[i, 0]
        y_ = robot_position[i, 1]
        patch_robot.center = (x_, y_)
        print(i)
        # print(x, y)

        # patch_list = []

        # ax.add_patch(patch_object)

        # patch_list.append(ax.add_patch(patch_robot))
        # ax.add_patch(patch_object)

        return patch_object, patch_robot,
        # return tuple()

    def animate_robot(i):
        x = robot_position[i, 0]
        y = robot_position[i, 1]
        patch_robot.center = (x, y)

        return patch_robot,

    # anim_object = animation.FuncAnimation(fig, animate_object, init_func = init_object, frames = len(object_rotation_d), interval = 200, blit = True)
    # anim_robot = animation.FuncAnimation(fig, animate_robot, init_func = init_robot, frames = len(object_rotation_d), interval = 100, blit = True)
    anim_object = animation.FuncAnimation(fig,
                                          animate_object,
                                          init_func=init_object,
                                          frames=len(object_rotation_d),
                                          interval=500,
                                          blit=True)
    # anim_object.save('example.mp4')

    plt.show()
Пример #13
0
def display_instances_5fps(image,
                           boxes,
                           masks,
                           class_ids,
                           class_names,
                           scores=None,
                           title="",
                           figsize=(16, 16),
                           ax=None,
                           show_mask=True,
                           show_bbox=True,
                           colors=None,
                           captions=None,
                           making_video=False,
                           making_image=False,
                           detect=False,
                           hc=False,
                           real_time=False):
    """
    boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates.
    masks: [height, width, num_instances]
    class_ids: [num_instances]
    class_names: list of class names of the dataset
    scores: (optional) confidence scores for each box
    title: (optional) Figure title
    show_mask, show_bbox: To show masks and bounding boxes or not
    figsize: (optional) the size of the image
    colors: (optional) An array or colors to use with each object
    captions: (optional) A list of strings to use as captions for each object
    """
    # Number of instances
    N = boxes.shape[0]
    if not N:
        print("\n*** No instances to display *** \n")
    else:
        assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]

    # If no axis is passed, create one and automatically call show()
    auto_show = True
    if not ax:
        fig, ax = plt.subplots(1, figsize=figsize)
        canvas = FigureCanvas(fig)

    # Generate random colors
    if not making_video or not real_time:
        colors = colors or random_colors(N)
    # Show area outside image boundaries.
    height, width = image.shape[:2]
    ax.set_ylim(height + 10, -10)
    ax.set_xlim(-10, width + 10)
    ax.axis('off')
    ax.set_title(title)

    masked_image = image.astype(np.uint32).copy()
    for i in range(N):
        class_id = class_ids[i]
        if making_video or real_time:
            # you can also assign a specific color for each class. etc:
            # if class_id == 1:
            #     color = colors[0]
            # elif class_id == 2:
            #     color = colors[1]
            color = colors[class_id - 1]
        elif hc:
            #just for hard-code the mask for paper
            if class_id == 14:
                color = colors[0]
            else:
                color = colors[class_id]
        else:
            color = colors[i]

        # Bounding box
        if not np.any(boxes[i]):
            # Skip this instance. Has no bbox. Likely lost in image cropping.
            continue
        y1, x1, y2, x2 = boxes[i]
        if show_bbox:
            p = patches.Rectangle((x1, y1),
                                  x2 - x1,
                                  y2 - y1,
                                  linewidth=2,
                                  alpha=0.7,
                                  linestyle="dashed",
                                  edgecolor=color,
                                  facecolor='none')
            ax.add_patch(p)

        # Label
        if not captions:
            score = scores[i] if scores is not None else None
            label = class_names[class_id]
            x = random.randint(x1, (x1 + x2) // 2)
            caption = "{} {:.3f}".format(label, score) if score else label
        else:
            caption = captions[i]
        ax.text(x1,
                y1 + 8,
                caption,
                color='w',
                size=14,
                backgroundcolor="none")

        # Mask
        mask = masks[:, :, i]
        if show_mask:
            masked_image = apply_mask(masked_image, mask, color)

        # Mask Polygon
        # Pad to ensure proper polygons for masks that touch image edges.
        padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2),
                               dtype=np.uint8)
        padded_mask[1:-1, 1:-1] = mask
        contours = find_contours(padded_mask, 0.5)
        for verts in contours:
            # Subtract the padding and flip (y, x) to (x, y)
            verts = np.fliplr(verts) - 1
            p = Polygon(verts, facecolor="none", edgecolor=color)
            ax.add_patch(p)
    ax.imshow(masked_image.astype(np.uint8))
    if detect:
        plt.close()
        return canvas
    # To transform the drawn figure into ndarray X
    fig.canvas.draw()
    X = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
    X = X.reshape(fig.canvas.get_width_height()[::-1] + (3, ))
    # open cv's RGB style: BGR
    if not real_time:
        X = X[..., ::-1]
    if making_video or real_time:
        plt.close()
        return X
    elif making_image:
        cv2.imwrite('splash.png', X)
    if auto_show:
        plt.show()
Пример #14
0
def get_masked_image(image,
                     boxes,
                     masks,
                     class_ids,
                     class_names,
                     scores=None,
                     title="",
                     figsize=(16, 16),
                     ax=None,
                     show_mask=True,
                     show_bbox=True,
                     colors=None,
                     captions=None):
    """
    boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates.
    masks: [height, width, num_instances]
    class_ids: [num_instances]
    class_names: list of class names of the dataset
    scores: (optional) confidence scores for each box
    title: (optional) Figure title
    show_mask, show_bbox: To show masks and bounding boxes or not
    figsize: (optional) the size of the image
    colors: (optional) An array or colors to use with each object
    captions: (optional) A list of strings to use as captions for each object
    """
    # Number of instances
    N = boxes.shape[0]
    if not N:
        print("\n*** No instances to display *** \n")
    else:
        assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]

    fig, ax = plt.subplots(1, figsize=figsize)

    # Generate random colors
    colors = colors or random_colors(N)

    # Show area outside image boundaries.
    height, width = image.shape[:2]
    ax.set_ylim(height + 10, -10)
    ax.set_xlim(-10, width + 10)
    ax.axis('off')
    ax.set_title(title)

    masked_image = image.astype(np.uint32).copy()
    for i in range(N):
        color = colors[i]

        # Bounding box
        if not np.any(boxes[i]):
            # Skip this instance. Has no bbox. Likely lost in image cropping.
            continue
        y1, x1, y2, x2 = boxes[i]
        if show_bbox:
            p = patches.Rectangle((x1, y1),
                                  x2 - x1,
                                  y2 - y1,
                                  linewidth=2,
                                  alpha=0.7,
                                  linestyle="dashed",
                                  edgecolor=color,
                                  facecolor='none')
            ax.add_patch(p)

        # Label
        if not captions:
            class_id = class_ids[i]
            score = scores[i] if scores is not None else None
            label = class_names[class_id]
            x = random.randint(x1, (x1 + x2) // 2)
            caption = "{} {:.3f}".format(label, score) if score else label
        else:
            caption = captions[i]
        ax.text(x1,
                y1 + 8,
                caption,
                color='w',
                size=11,
                backgroundcolor="none")

        # Mask
        mask = masks[:, :, i]
        if show_mask:
            masked_image = apply_mask(masked_image, mask, color)

        # Mask Polygon
        # Pad to ensure proper polygons for masks that touch image edges.
        padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2),
                               dtype=np.uint8)
        padded_mask[1:-1, 1:-1] = mask
        contours = find_contours(padded_mask, 0.5)
        for verts in contours:
            # Subtract the padding and flip (y, x) to (x, y)
            verts = np.fliplr(verts) - 1
            p = Polygon(verts, facecolor="none", edgecolor=color)
            ax.add_patch(p)

    ax.imshow(masked_image.astype(np.uint8))
    ax.figure.canvas.draw()

    # convert canvas to image
    canvas = np.fromstring(ax.figure.canvas.tostring_rgb(),
                           dtype=np.uint8,
                           sep='')
    canvas = canvas.reshape(ax.figure.canvas.get_width_height()[::-1] + (3, ))
    canvas = cv2.cvtColor(canvas, cv2.COLOR_RGB2BGR)
    #canvas = cv2.resize(canvas, (1440, 1080))

    return canvas
Пример #15
0
i = 0
dane = []
for line in open("output.txt", "r"):
    line = line[:-1]
    if i == 0:
        i += 1
        continue
    else:
        dane.append([int(l) for l in line.split(" ")])
    i += 1

ax.add_patch(
    patches.Rectangle((0, 0),
                      2800,
                      2070,
                      linewidth=3,
                      edgecolor='blue',
                      facecolor='none',
                      fill=False))
#ax.add_patch(patches.Rectangle((0,0),4096,4096,linewidth=2,edgecolor='gray',facecolor='none', fill=False))

for d in dane:
    if d[2] != -1:
        if d[4]:
            ax.add_patch(
                patches.Rectangle((d[2], d[3]),
                                  d[1],
                                  d[0],
                                  linewidth=1,
                                  edgecolor='red',
                                  facecolor='none',
Пример #16
0
#!/usr/bin/env python

from matplotlib import patches
from matplotlib import pyplot as plt
from math import sin, cos, pi

fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(111)


def star(coord, size, rotate):
    pts = [(size * sin(i * 4 * pi / 5 + rotate) + coord[0],
            size * cos(i * 4 * pi / 5 + rotate) + coord[1]) for i in range(5)]
    return patches.Polygon(pts, fc='yellow', ec='yellow')


ax.add_patch(patches.Rectangle([0, -2], 3, 2, fc='red', ec='red'))
ax.add_patch(star((0.5, -0.5), 0.3, 0.0))
ax.add_patch(star((1.0, -0.2), 0.07, 0.3))
ax.add_patch(star((1.2, -0.4), 0.07, 0.9))
ax.add_patch(star((1.2, -0.7), 0.07, 0.0))
ax.add_patch(star((1.0, -0.9), 0.07, 0.3))
ax.set_axis_off()
plt.axis('scaled')
plt.show()
Пример #17
0
def main():
    file_path = 'sac_7/linear_x_y_no_ra/challenge_fixed/'
    robots = Read_Data(file_path + "log_robot_show.pickle")
    paths = Read_Data(file_path + "log_path_show.pickle")
    obstalces = Read_Data(file_path + "log_obstacle_show.pickle")
    obs_dir = Read_Data("log_direction_show.pickle")
    goals = Read_Data(file_path + "log_goal_show.pickle")
    choise_episode = 3
    print(obs_dir)
    path = paths[choise_episode]
    obstalce = obstalces[choise_episode]
    ob_dir = obs_dir[0]
    goal = goals[choise_episode]

    print(len(paths[0]))
    print(obstalce)
    print(goal)
    """ add plot object """
    ax = plt.gca()
    """ path """
    x = []
    y = []
    for pos in path:
        x.append(pos[0])
        y.append(pos[1])
    plt.plot(x, y, color='blue')
    """ obstacle """
    x = []
    y = []
    for pos in obstalce:
        x.append(pos[0] - 0.225)
        y.append(pos[1] - 0.225)
    # print(x,y)

    for i in range(len(x)):
        center = [x[i] + 0.225, y[i] + 0.225]

        obstacle = patches.Rectangle((x[i], y[i]), 0.45, 0.45, color='black')
        """ obstacle yaw """
        ts = ax.transData
        tr = tf.Affine2D().rotate_deg_around(center[0], center[1], 20)
        t = tr + ts
        obstacle.set_transform(t)
        """ dir """
        if (len(ob_dir)):
            # move_x
            if (ob_dir[i] == 1):
                plt.arrow(center[0], center[1], 0.3, 0, width=0.04, color='r')
                plt.arrow(center[0], center[1], -0.3, 0, width=0.04, color='r')
            # move_y
            elif (ob_dir[i] == 2):
                plt.arrow(center[0], center[1], 0, 0.3, width=0.04, color='r')
                plt.arrow(center[0], center[1], 0, -0.3, width=0.04, color='r')
            # rotate
            elif (ob_dir[i] == 3):
                ax.annotate("",\
                            xy=(center[0], center[1]+0.5),\
                            xycoords='data',\
                            xytext=(center[0]+0.5, center[1]),\
                            textcoords='data',\
                            arrowprops=dict(width=1.5,
                                            headwidth=8,
                                            color='red',
                                            connectionstyle="arc3,rad=0.8"))

        ax.add_patch(obstacle)
    """ obstacle dir """
    # straight
    # plt.arrow(0,0,0.25,0,linewidth=5,color='r')
    # plt.arrow(0,0,-0.25,0,linewidth=5,color='r')
    # rotate
    # ax.annotate("",
    #         xy=(0, 0.5), xycoords='data',
    #         xytext=(0.5, 0), textcoords='data',
    #         arrowprops=dict(arrowstyle="<-",
    #                         connectionstyle="arc3,rad=0.8"))
    """ goal """
    # fix goal
    # left buttom point
    y_goal = patches.Rectangle((-3, -0.75), 0.4, 1.5, color='yellow')
    b_goal = patches.Rectangle((2.6, -0.75), 0.4, 1.5, color='blue')
    ax.add_patch(y_goal)
    ax.add_patch(b_goal)

    # random goal
    random_goal = patches.Rectangle((goal[0] - 0.22, goal[1] - 0.22),
                                    0.44,
                                    0.44,
                                    color='red')
    ax.add_patch(random_goal)

    plt.ylim(-2.5, 2.5)
    plt.xlim(-3.5, 3.5)
    plt.grid()
    plt.show()
    ux = ux / U_inf
    cp[i] = ax[i].contourf(yg, zg, ux, clevel)
    cl[i] = ax[i].contour(yg,
                          zg,
                          ux,
                          clevel,
                          colors='k',
                          linestyles='dashed',
                          linewidths=0.5)

    ax[i].set_xlim(xlim[0], xlim[1])
    ax[i].set_ylim(ylim[0], ylim[1])
    rect = patches.Rectangle((-0.5, -0.5),
                             1,
                             1,
                             linewidth=1,
                             edgecolor='k',
                             facecolor='none',
                             linestyle='dashed')
    ax[i].add_patch(rect)
ax[0].set_ylabel('$\it{Z/R}$')

fig.text(0.5, -0.05, '$\it{X/R}$', ha='center')
fig.text(0, 0.9, r'C\rom{3}')
clb = fig.colorbar(cp[len(planevalue) - 1])

if saveplot:
    plt.savefig(OutPath + casename + '_' + plane + '.png',
                dpi=300,
                bbox_inches="tight")
    plt.savefig(OutPath + casename + '_' + plane + '.png', dpi=300)
Пример #19
0
vmax=1.; vmin=1E-5
umax=2.; umin=1E-5
i_scale=5
nplot=vx_xy.shape[0];t_play=15
for it in range(nplot):
    mappablev = cm.ScalarMappable(cmap=plt.get_cmap('gray'), norm=matplotlib.colors.Normalize(vmin=0, vmax=vmax))
    mappableu = cm.ScalarMappable(cmap=plt.get_cmap('gray'), norm=matplotlib.colors.Normalize(vmin=0, vmax=umax))
    mappablev.set_array(np.sqrt(vx_xy[i_scale,:,:]**2+vy_xy[i_scale,:,:]**2+vz_xy[i_scale,:,:]**2)-vmin)
    mappableu.set_array(np.sqrt(ux_xy[i_scale,:,:]**2+uy_xy[i_scale,:,:]**2+uz_xy[i_scale,:,:]**2)-vmin)
    fig.set_size_inches(height,width, forward=True)
    ax=plt.subplot(gs[0])
    plt.xlabel('x [km]')
    plt.ylabel('y [km]')
    plt.contourf(x,y,np.sqrt(vx_xy[it,:,:]**2+vy_xy[it,:,:]**2+vz_xy[it,:,:]**2)-vmin,40, cmap=plt.get_cmap('gray'), vmax=vmax, vmin=0.)
    ax.xaxis.set_ticks_position('none')
    ax.add_patch(patches.Rectangle((-24., -32.), 48., 64., fill=False,edgecolor="white",linestyle='dotted'))
    if True:
        cbax1 = fig.add_axes([0.08, 1.0, 0.4, 0.02])
        plt.colorbar(mappablev,orientation='horizontal',cax=cbax1,format='%1.2g')
    else:
        plt.axis('off') 
    #ax.add_patch(patches.Rectangle((-1., -.6), 2.0, 1.2, fill=False,edgecolor="white",linestyle='dotted'))
    plt.title(r'$||\mathbf{v}||$ [m/s], t=%1.2f [s]'%(t[it]))
    ax=plt.subplot(gs[1])
    #plt.xlabel('x [km]')
    #plt.ylabel('y [km]')
    plt.contourf(x,y,np.sqrt(ux_xy[it,:,:]**2+uy_xy[it,:,:]**2+uz_xy[it,:,:]**2)-umin,40, cmap=plt.get_cmap('gray'), vmax=umax, vmin=0.)
    if True:
        cbax2 = fig.add_axes([.56, 1.0, 0.4, 0.02])
        plt.colorbar(mappableu,orientation='horizontal',cax=cbax2,format='%1.2g')
    else:
Пример #20
0
def animate(frame):

    # Clear any prior step rects
    for p in rects: p.remove()
    rects.clear()

    if frame < simStepFrames:

        # Main heat map (random walk)
        countResultsGrid = countResults[frame][0]
        im.set_array(countResultsGrid / maxCountForStepSim)
        txtSimulations = str(countResultsGrid[0][0])
        fig.suptitle('Axis and Allies - Simulations ' + txtSimulations, fontsize = titleSize)

        stepAttRem = countResults[frame][1]
        stepDefRem = countResults[frame][2]
        barAnim = countResults[frame][3]
        if barAnim:

            for j in range(totAttUnits + 1):
                rectsAtt[j].set_height(countResultsGrid[-1][totAttUnits-j] * factForStepBar)

            for j in range(totDefUnits + 1):
                rectsDef[j].set_width(countResultsGrid[:,-1][totDefUnits-j] * factForStepBar)

            if stepDefRem == 0:

                stepAttLocX = totAttUnits -stepAttRem - .4
                stepAttLocY = (countResultsGrid[-1][totAttUnits - stepAttRem] - 1) * factForStepBar
                axAttRect = patches.Rectangle(
                    (stepAttLocX, stepAttLocY), .8,  factForStepBar, 
                    linewidth = 3, edgecolor = 'r', facecolor = 'none')
                axAtt.add_patch(axAttRect)
                rects.append(axAttRect)

            if stepAttRem == 0:

                stepDefLocX = totDefUnits -stepDefRem - .4
                stepDefLocY = (countResultsGrid[:,-1][totDefUnits - stepDefRem] - 1) * factForStepBar
                axDefRect = patches.Rectangle(
                    (stepDefLocY, stepDefLocX), factForStepBar, .8, 
                    linewidth = 3, edgecolor = 'r', facecolor = 'none')
                axDef.add_patch(axDefRect)
                rects.append(axDefRect)

        else:
            stepAttLoc = totAttUnits -stepAttRem - .5
            stepDefLoc = totDefUnits - stepDefRem - .5
            rect = patches.Rectangle(
                (stepAttLoc, stepDefLoc), 1, 1, 
                linewidth = 3, edgecolor = 'r', facecolor = 'none')
            axMain.add_patch(rect)
            rects.append(rect)

    elif frame < simStepFrames + pauseFrames1:

        pass

    elif frame < simStepFrames + pauseFrames1 + simXFrames * simXTicks:

        idx = (frame - simStepFrames  - pauseFrames1) // simXTicks
        grid = countGridsX[idx]

        txtSimulations = str(grid[0][0])
        fig.suptitle('Axis and Allies - Simulations ' + txtSimulations, fontsize = titleSize)

        a = MaxExcludeStartCell(grid) * (1.25 if idx == 0 else 1)
        im.set_array(grid / a)

        pGrid = grid.copy()/grid[0][0]
        probsAttAnim = pGrid[-1]  
        probAttAnim = sum(probsAttAnim) - probsAttAnim[-1]
        probsDefAnim = pGrid[:,-1] 
        probDefAnim = sum(probsDefAnim) - probsDefAnim[-1]
        bothLoseProdAnim = probsAttAnim[-1] 
        axAtt.set_ylabel("{:.1%}".format(probAttAnim), fontsize = titleSize)
        axDef.set_xlabel("{:.1%}".format(probDefAnim), fontsize = titleSize)

        for j in range(totAttUnits + 1):
            rectsAtt[j].set_height(pGrid[-1][totAttUnits-j])

        for j in range(totDefUnits + 1):
            rectsDef[j].set_width(pGrid[:,-1][totDefUnits-j])

    elif frame < simStepFrames + pauseFrames1 + simXFrames * simXTicks + pauseFrames2:

        pass

    elif frame < simStepFrames + pauseFrames1 + simXFrames * simXTicks + pauseFrames2 + animFrames * animTicks:

        idx = (frame - simStepFrames  - pauseFrames1 - simXFrames * simXTicks - pauseFrames2) // animTicks

        fig.suptitle('Axis and Allies - Exact Outcomes', fontsize = titleSize)
        
        i = totalUnits - 1 if idx == animFrames - 1 else idx

        # Main heat map (random walk)
        maxProb = np.max(probGrids[i])
        probs = probGrids[i].copy() / maxProb
        im.set_array(probs)

        # Show 
        probsAttAnim = probGrids[i][-1]     # Last row
        probAttAnim = sum(probsAttAnim) - probsAttAnim[-1]
        probsDefAnim = probGrids[i][:,-1]  # Last column
        probDefAnim = sum(probsDefAnim) - probsDefAnim[-1]
        bothLoseProdAnim = probsAttAnim[-1]  # Same as probsDef[-1]
        axAtt.set_ylabel("{:.1%}".format(probAttAnim), fontsize = titleSize)
        axDef.set_xlabel("{:.1%}".format(probDefAnim), fontsize = titleSize)

        textAnim = "{:.1%}".format(bothLoseProdAnim)
        evAnimAtt = sum(np.flip(probsAttAnim) * range(0, totAttUnitsP1)) 
        evAnimDef = sum(np.flip(probsDefAnim) * range(0, totDefUnitsP1))
        evAnim = evAnimAtt - evAnimDef
        evTextAnim = "{:.1f}".format(evAnim)
        txt.set_text(textAnim + ' for 0\nEV = ' + evTextAnim)

        # Set attack outome bar heights
        for j in range(totAttUnits + 1):
            rectsAtt[j].set_height(probGrids[i][-1][totAttUnits-j])

        # Set defendar outcome bar heights
        for j in range(totDefUnits + 1):
            rectsDef[j].set_width(probGrids[i][:,-1][totDefUnits-j])

    else:

        pass

    return [im]
Пример #21
0
def display(model, img_batch, label_batch):
    np_imgs = []
    for k in range(img_batch.shape[0]):
        np_img = img_batch[k].detach().cpu().numpy()
        np_imgs.append(np.stack([np_img[0], np_img[1], np_img[2]], axis=2))
    model.eval()
    softmax = nn.Softmax(dim=1)
    out = model.forward(img_batch)
    for j in range(img_batch.shape[0]):
        label_array = label_batch[j]
        flat_out = out[j]
        class_scores = flat_out[:, :model.num_classes]
        class_scores = softmax(class_scores)
        class_scores, class_labels = torch.max(class_scores, 1)
        index_helper = torch.arange(0,
                                    class_labels.shape[0],
                                    device=model.device,
                                    dtype=torch.long)
        valid_out_mask = class_labels > 0.4
        valid_out_indices = torch.masked_select(index_helper, valid_out_mask)

        raw_boxes = flat_out[:, model.num_classes:]
        reparam_boxes = torch.stack([
            model.wa_vec * raw_boxes[:, 0] + model.xa_vec,
            model.ha_vec * raw_boxes[:, 1] + model.ya_vec,
            model.wa_vec * torch.exp(raw_boxes[:, 2]),
            model.ha_vec * torch.exp(raw_boxes[:, 3])
        ],
                                    dim=1)

        reparam_boxes = torch.stack([
            reparam_boxes[:, 0] - 0.5 * reparam_boxes[:, 2],
            reparam_boxes[:, 1] - 0.5 * reparam_boxes[:, 3],
            reparam_boxes[:, 0] + 0.5 * reparam_boxes[:, 2],
            reparam_boxes[:, 1] + 0.5 * reparam_boxes[:, 3]
        ],
                                    dim=1)

        detected_boxes = reparam_boxes[valid_out_indices]
        detected_scores = class_scores[valid_out_indices]
        detected_labels = class_labels[valid_out_indices]

        good_box_indices = nms(detected_boxes,
                               detected_scores,
                               iou_threshold=0.5)
        detected_boxes = detected_boxes[good_box_indices]
        detected_scores = detected_scores[good_box_indices]
        detected_labels = detected_labels[good_box_indices]

        fig, ax = plt.subplots(1)
        ax.imshow(np_imgs[j])
        print(detected_boxes.shape[0])
        for n in range(detected_boxes.shape[0]):
            x1 = detected_boxes[n, 0]
            y1 = detected_boxes[n, 1]
            x2 = detected_boxes[n, 2]
            y2 = detected_boxes[n, 3]
            rect_corner = x1, y1
            rect = patches.Rectangle(rect_corner,
                                     x2 - x1,
                                     y2 - y1,
                                     linewidth=1,
                                     edgecolor='r',
                                     facecolor='none')
            ax.add_patch(rect)
            #ax.text(x1, y1, "{}, {:.3f}".format(INV_COCO_DICT[int(detected_labels[n])], float(detected_scores[n])), color='r')
            ax.text(x1,
                    y1,
                    "{}, {:.3f}".format(INV_VOC_DICT[int(detected_labels[n])],
                                        float(detected_scores[n])),
                    color='r')

        for n in range(label_array.shape[0]):
            xt = label_array[n, 1]
            yt = label_array[n, 2]
            wt = label_array[n, 3]
            ht = label_array[n, 4]
            trect_corner = xt - 0.5 * wt, yt - 0.5 * ht
            trect = patches.Rectangle(trect_corner,
                                      wt,
                                      ht,
                                      linewidth=1,
                                      edgecolor='g',
                                      facecolor='none')
            ax.add_patch(trect)
        plt.show()
Пример #22
0
def draw_bounding_square(L, p):
    sq = patches.Rectangle(p, L, L, fill=False)
    plt.gca().add_patch(sq)
Пример #23
0
ax.set_xlim(minx - 0.05 * w, maxx + 0.05 * w)
ax.set_ylim(miny - 0.05 * h, maxy + 0.05 * h)
ax.set_aspect(1)
ax.set_xticks([])
ax.set_yticks([])
ax.axis('off')

ax.add_collection(GBRpc)
ax.add_collection(NIpc)

# add  boxes
boxx, boxy = 500000, 880000
ax.add_patch(
    patches.Rectangle((boxx, boxy),
                      50000,
                      50000,
                      facecolor='#d7191c',
                      linewidth=0.3))
ax.text(boxx + 60000, boxy + 16000, 'Zone 1', fontsize=16)

boxx, boxy = 500000, 800000
ax.add_patch(
    patches.Rectangle((boxx, boxy),
                      50000,
                      50000,
                      facecolor='#fdae61',
                      linewidth=0.3))
ax.text(boxx + 60000, boxy + 16000, 'Zone 2', fontsize=16)

boxx, boxy = 500000, 720000
ax.add_patch(
Пример #24
0
plt.imshow(image)

# iterating over the image for different objects
for _, row in train[train.image_names == "00005.jpg"].iterrows():
    xmin = row.xmin
    xmax = row.xmax
    ymin = row.ymin
    ymax = row.ymax

    width = xmax - xmin
    height = ymax - ymin

    # assign different color to different classes of objects
    '''  if row.helmet_color == 'RBC':
        edgecolor = 'r'
        ax.annotate('RBC', xy=(xmax-40,ymin+20))
    elif row.cell_type == 'WBC':
        edgecolor = 'b'
        ax.annotate('WBC', xy=(xmax-40,ymin+20))
    elif row.cell_type == 'Platelets':
        edgecolor = 'g'
        ax.annotate('Platelets', xy=(xmax-40,ymin+20))'''

    # add bounding boxes to the image
    rect = patches.Rectangle((xmin, ymin),
                             width,
                             height,
                             edgecolor='w',
                             facecolor='none')

    ax.add_patch(rect)
Пример #25
0
    postLatency = first_spike_latency_each_trial(spikeData.timestamps,
                                                 eventOnsetTimes, postRange)

    timeRange = [-0.2, 0.2]
    (spikeTimesFromEventOnset, trialIndexForEachSpike,
     indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
         spikeData.timestamps, eventOnsetTimes, timeRange)

    if PLOT == 1:
        plt.clf()
        ax1 = plt.subplot(211)
        plt.plot(spikeTimesFromEventOnset, trialIndexForEachSpike, 'k.', ms=4)
        ax1.add_patch(
            patches.Rectangle((preRange[0], 0),
                              preRange[1] - preRange[0],
                              trialIndexForEachSpike[-1] + 1,
                              color='0.5',
                              alpha=0.5))
        ax1.add_patch(
            patches.Rectangle((postRange[0], 0),
                              postRange[1] - postRange[0],
                              trialIndexForEachSpike[-1] + 1,
                              color='r',
                              alpha=0.5))

        plt.axvline(preRange[0] + np.median(preLatency), color='k')
        plt.axvline(postRange[0] + np.median(postLatency), color='r')
        ax1.set_xlim(timeRange)
        ax1.set_ylim([0, trialIndexForEachSpike[-1]])
        ax1.set_title('{}\nZ-score: {}'.format(cell['brainarea'],
                                               cell['noiseZscore']))
Пример #26
0
def resumeByUsers(data=None, escalaEnAngulos=False, diferencias=False):

    from matplotlib.backends.backend_pdf import PdfPages
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    import datetime

    if data:
        resumen = dataNumerica(data)
    else:
        resumen = dataNumerica()

        # Generamos las etiquetas
        etiquetasTest = [
            'P30', 'P60', 'P120', 'P150', 'A30', 'A60', 'A120', 'A150'
        ]
        etiquetasEntrenamiento = ['Dia1', 'Dia2', 'Dia3', 'Dia4']

    # Creamos el pdf con todos los graficoados
    #pp = PdfPages("./Images/TransferenciaResultados ("+ datetime.date.today().strftime("%B %d, %Y") +").pdf")

    # Creamos un lienzo con todos los graficoados
    f, axarr = plt.subplots(len(resumen.keys()), 2)
    f.set_size_inches(20, 2.5 * len(resumen.keys()))
    #f.tight_layout()
    f.subplots_adjust(left=None,
                      bottom=None,
                      right=None,
                      top=None,
                      wspace=0.4,
                      hspace=0.4)
    f.subplots_adjust(top=1)
    i = 0
    for alias, resultado in resumen.items():

        valoresTestInicial = resultado['TestInicial']
        valoresTestFinal = resultado['TestFinal']
        valoresTestDiferencia = resultado['Evolucion']

        valoresTestInicialEnAngulos = resultado['TestInicialAngulos']
        valoresTestFinalEnAngulos = resultado['TestFinalAngulos']
        valoresTestDiferenciaEnAngulo = resultado['EvolucionAngulos']

        valoresEntrenamientoInicial = resultado['EntrenamientoInicial']
        valoresEntrenamientoIntermedio = resultado['EntrenamientoMedio']
        valoresEntrenamientoFinal = resultado['EntrenamientoFinal']

        valoresEntrenamientoInicialEnAngulos = resultado[
            'EntrenamientoInicialEnAngulos']
        valoresEntrenamientoIntermedioEnAngulos = resultado[
            'EntrenamientoMedioEnAngulos']
        valoresEntrenamientoFinalEnAngulos = resultado[
            'EntrenamientoFinalEnAngulos']

        # Creamos las dos figuras para el usuario
        # fig = axarr[i]
        # fig = plt.figure(figsize=(20,2))
        # fig.set_title("Usuario: " + cts.mapNames[alias] + ". Entrenamiento: " + resultado['Orientacion'], fontsize=12)
        # fig.subplots_adjust(top=0.85)

        if escalaEnAngulos:
            valoresTestInicialUnificado = valoresTestInicialEnAngulos
            valoresTestFinalUnificado = valoresTestFinalEnAngulos
            valoresTestDiferenciaUnificado = valoresTestDiferenciaEnAngulo
        else:
            valoresTestInicialUnificado = valoresTestInicial
            valoresTestFinalUnificado = valoresTestFinal
            valoresTestDiferenciaUnificado = valoresTestDiferencia

        valoresTestDiferenciaUnificadoPos = valoresTestDiferenciaUnificado
        valoresTestDiferenciaUnificadoNeg = [
            -value for value in valoresTestDiferenciaUnificado
        ]

        # Creamos el grafico de test
        #figuraTest = plt.subplot(121)
        figuraTest = axarr[i, 0]
        #figuraTest.set_title("Usuario: " + cts.mapNames[alias], fontsize=12)
        n_groups = 8
        index = np.arange(n_groups)
        if diferencias:
            bar_width = 0.25
        else:
            bar_width = 0.4
        opacity = 0.4
        rects1 = figuraTest.bar(index,
                                valoresTestInicialUnificado,
                                bar_width,
                                alpha=opacity * 0.5,
                                color='b',
                                label='Test Inicial')
        rects2 = figuraTest.bar(index + bar_width,
                                valoresTestFinalUnificado,
                                bar_width,
                                alpha=opacity * 2,
                                color='b',
                                label='TestFinal')
        if diferencias:
            rects3 = figuraTest.bar(index + bar_width * 2,
                                    valoresTestDiferenciaUnificadoPos,
                                    bar_width,
                                    alpha=opacity * 2,
                                    color='g',
                                    label='Evolucion positiva')
            rects4 = figuraTest.bar(index + bar_width * 2,
                                    valoresTestDiferenciaUnificadoNeg,
                                    bar_width,
                                    alpha=opacity * 2,
                                    color='r',
                                    label='Evolucion negativa')
        figuraTest.set_xlabel('Orientacion')

        if escalaEnAngulos:
            figuraTest.set_ylabel('Umbral de detección (angulo)')
        else:
            figuraTest.set_ylabel('Performance (estimulos)')
        figuraTest.set_title('Comparacion test inicial y final ' + '(' +
                             "Usuario: " + alias + ')')
        plt.sca(axarr[i, 0])
        plt.xticks(index + bar_width, etiquetasTest)
        figuraTest.legend(bbox_to_anchor=(0.95, 1), loc=2, borderaxespad=0.)
        if escalaEnAngulos:
            figuraTest.set_ylim([0, 100])
        else:
            figuraTest.set_ylim([0, 200])

        # Remarcamos el entrenamiento
        MaxA = 80
        MaxP = 100
        pasos = 200
        if escalaEnAngulos:
            MaxCuadraditoA = MaxA
            MaxCuadraditoP = MaxP
        else:
            MaxCuadraditoA = pasos
            MaxCuadraditoP = pasos

        if diferencias:
            ancho = 0.75
        else:
            ancho = 0.8

        if resultado['Orientacion'] == 'P30':
            figuraTest.add_patch(
                patches.Rectangle(
                    (0, 0),
                    ancho,
                    MaxCuadraditoP,
                    fill=False,  # remove background
                    edgecolor="red"))
        if resultado['Orientacion'] == 'A30':
            figuraTest.add_patch(
                patches.Rectangle(
                    (4, 0),
                    ancho,
                    MaxCuadraditoA,
                    fill=False,  # remove background
                    edgecolor="red"))

        # Grafico de entreamiento
        figuraEntrenamiento = axarr[i, 1]
        # figuraEntrenamiento = plt.subplot(122)
        n_groups = 4
        index = np.arange(n_groups)
        bar_width = 0.25
        opacity = 0.4

        if escalaEnAngulos:
            valoresEntrenamientoInicial = valoresEntrenamientoInicialEnAngulos
            valoresEntrenamientoIntermedio = valoresEntrenamientoIntermedioEnAngulos
            valoresEntrenamientoFinal = valoresEntrenamientoFinalEnAngulos
        else:
            valoresEntrenamientoInicial = valoresEntrenamientoInicial
            valoresEntrenamientoIntermedio = valoresEntrenamientoIntermedio
            valoresEntrenamientoFinal = valoresEntrenamientoFinal

        rects1 = figuraEntrenamiento.bar(
            index,
            valoresEntrenamientoInicial,
            bar_width,
            alpha=opacity * 0.5,
            color='b',
            label='Entrenamiento inicial con feedback (100 trials)')
        rects2 = figuraEntrenamiento.bar(
            index + bar_width,
            valoresEntrenamientoIntermedio,
            bar_width,
            alpha=opacity,
            color='b',
            label='Entrenamiento intermedio sin feedback (50 trials)')
        rects3 = figuraEntrenamiento.bar(
            index + bar_width * 2,
            valoresEntrenamientoFinal,
            bar_width,
            alpha=opacity * 2,
            color='b',
            label='Entrenamiento final con feedback (100 trials)')

        figuraEntrenamiento.set_xlabel('Sesion')
        if escalaEnAngulos:
            figuraEntrenamiento.set_ylabel('Umbral de detección (angulo)')
        else:
            figuraEntrenamiento.set_ylabel('Performance (estimulos)')
        #plt.ylabel('Performance')

        figuraEntrenamiento.set_title(
            'Evolucion de performance en entrenamiento' + '(' + "Usuario: " +
            alias + ')')
        plt.sca(axarr[i, 1])
        plt.xticks(index + 1.5 * bar_width, etiquetasEntrenamiento)
        #figuraEntrenamiento.set_xticklabels(index + 1.5 * bar_width, etiquetasEntrenamiento)
        figuraEntrenamiento.legend(bbox_to_anchor=(0.95, 1),
                                   loc=2,
                                   borderaxespad=0.)
        if escalaEnAngulos:
            figuraEntrenamiento.set_ylim([0, 100])
        else:
            figuraEntrenamiento.set_ylim([0, 200])

        # pp.savefig(fig, dpi = 300, transparent = True)
        i += 1

    if escalaEnAngulos:
        f.savefig('./Images/TransferenciaResultadosEnAngulos',
                  bbox_inches='tight')
    else:
        f.savefig('./Images/TransferenciaResultados', bbox_inches='tight')
Пример #27
0
def draw_boxes(image,
               boxes=None,
               refined_boxes=None,
               masks=None,
               captions=None,
               visibilities=None,
               title="",
               ax=None):
    """Draw bounding boxes and segmentation masks with different
    customizations.

    boxes: [N, (y1, x1, y2, x2, class_id)] in image coordinates.
    refined_boxes: Like boxes, but draw with solid lines to show
        that they're the result of refining 'boxes'.
    masks: [N, height, width]
    captions: List of N titles to display on each box
    visibilities: (optional) List of values of 0, 1, or 2. Determine how
        prominent each bounding box should be.
    title: An optional title to show over the image
    ax: (optional) Matplotlib axis to draw on.
    """
    # Number of boxes
    assert boxes is not None or refined_boxes is not None
    N = boxes.shape[0] if boxes is not None else refined_boxes.shape[0]

    # Matplotlib Axis
    if not ax:
        _, ax = plt.subplots(1, figsize=(12, 12))

    # Generate random colors
    colors = random_colors(N)

    # Show area outside image boundaries.
    margin = image.shape[0] // 10
    ax.set_ylim(image.shape[0] + margin, -margin)
    ax.set_xlim(-margin, image.shape[1] + margin)
    ax.axis('off')

    ax.set_title(title)

    masked_image = image.astype(np.uint32).copy()
    for i in range(N):
        # Box visibility
        visibility = visibilities[i] if visibilities is not None else 1
        if visibility == 0:
            color = "gray"
            style = "dotted"
            alpha = 0.5
        elif visibility == 1:
            color = colors[i]
            style = "dotted"
            alpha = 1
        elif visibility == 2:
            color = colors[i]
            style = "solid"
            alpha = 1

        # Boxes
        if boxes is not None:
            if not np.any(boxes[i]):
                # Skip this instance. Has no bbox. Likely lost in cropping.
                continue
            y1, x1, y2, x2 = boxes[i]
            p = patches.Rectangle((x1, y1),
                                  x2 - x1,
                                  y2 - y1,
                                  linewidth=2,
                                  alpha=alpha,
                                  linestyle=style,
                                  edgecolor=color,
                                  facecolor='none')
            ax.add_patch(p)

        # Refined boxes
        if refined_boxes is not None and visibility > 0:
            ry1, rx1, ry2, rx2 = refined_boxes[i].astype(np.int32)
            p = patches.Rectangle((rx1, ry1),
                                  rx2 - rx1,
                                  ry2 - ry1,
                                  linewidth=2,
                                  edgecolor=color,
                                  facecolor='none')
            ax.add_patch(p)
            # Connect the top-left corners of the anchor and proposal
            if boxes is not None:
                ax.add_line(lines.Line2D([x1, rx1], [y1, ry1], color=color))

        # Captions
        if captions is not None:
            caption = captions[i]
            # If there are refined boxes, display captions on them
            if refined_boxes is not None:
                y1, x1, y2, x2 = ry1, rx1, ry2, rx2
            ax.text(x1,
                    y1,
                    caption,
                    size=11,
                    verticalalignment='top',
                    color='w',
                    backgroundcolor="none",
                    bbox={
                        'facecolor': color,
                        'alpha': 0.5,
                        'pad': 2,
                        'edgecolor': 'none'
                    })

        # Masks
        if masks is not None:
            mask = masks[:, :, i]
            masked_image = apply_mask(masked_image, mask, color)
            # Mask Polygon
            # Pad to ensure proper polygons for masks that touch image edges.
            padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2),
                                   dtype=np.uint8)
            padded_mask[1:-1, 1:-1] = mask
            contours = find_contours(padded_mask, 0.5)
            for verts in contours:
                # Subtract the padding and flip (y, x) to (x, y)
                verts = np.fliplr(verts) - 1
                p = Polygon(verts, facecolor="none", edgecolor=color)
                ax.add_patch(p)
    ax.imshow(masked_image.astype(np.uint8))
Пример #28
0
def resumeByUsersNuevo(data=None, escalaEnAngulos=True, diferencias=False):

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    import datetime

    if data:
        resumen = dataNumerica(data)
    else:
        resumen = dataNumerica()

        # Generamos las etiquetas
        etiquetasTest = [
            'P30', 'P60', 'P120', 'P150', 'A30', 'A60', 'A120', 'A150'
        ]
        etiquetasEntrenamiento = [
            'Test Inicial', 'Dia1', 'Dia2', 'Dia3', 'Dia4', 'TestFinal'
        ]

    # Creamos un lienzo con todos los graficoados
    f, axarr = plt.subplots(nrows=len(resumen.keys()),
                            ncols=2,
                            sharex=True,
                            sharey=True,
                            figsize=(20, 2.5 * len(resumen.keys())))

    #f.tight_layout()
    f.subplots_adjust(left=None,
                      bottom=None,
                      right=None,
                      top=None,
                      wspace=0,
                      hspace=0)

    # Variables que permiten ordenar las figuras

    par = 0
    ang = 3
    sin = 5

    for alias, resultado in resumen.items():

        if resultado['Orientacion'] == 'CONTROL':
            i = sin
            print('CONTROL' + str(i))
            sin = sin + 1
        if resultado['Orientacion'] == 'P30':
            i = par
            print('P30' + str(i))
            par = par + 1
        if resultado['Orientacion'] == 'A30':
            i = ang
            print('A30' + str(i))
            ang = ang + 1

        valoresTestInicial = resultado['TestInicial']
        valoresTestFinal = resultado['TestFinal']

        valoresTestInicialEnAngulos = resultado['TestInicialAngulos']
        valoresTestFinalEnAngulos = resultado['TestFinalAngulos']

        valoresEntrenamientoInicial = resultado['EntrenamientoInicial']
        valoresEntrenamientoIntermedio = resultado['EntrenamientoMedio']
        valoresEntrenamientoFinal = resultado['EntrenamientoFinal']

        valoresEntrenamientoInicialEnAngulos = resultado[
            'EntrenamientoInicialEnAngulos']
        valoresEntrenamientoIntermedioEnAngulos = resultado[
            'EntrenamientoMedioEnAngulos']
        valoresEntrenamientoFinalEnAngulos = resultado[
            'EntrenamientoFinalEnAngulos']

        if escalaEnAngulos:
            valoresTestInicialUnificado = valoresTestInicialEnAngulos
            valoresTestFinalUnificado = valoresTestFinalEnAngulos
        else:
            valoresTestInicialUnificado = valoresTestInicial
            valoresTestFinalUnificado = valoresTestFinal

        #figuraTest = plt.subplot(121)
        figuraTest = axarr[i, 0]
        n_groups = 8
        index = np.arange(n_groups)
        bar_width = 0.4
        opacity = 0.4

        rects1 = figuraTest.bar(index,
                                valoresTestInicialUnificado,
                                bar_width,
                                alpha=opacity * 0.5,
                                color='b',
                                label='Test Inicial')
        rects2 = figuraTest.bar(index + bar_width,
                                valoresTestFinalUnificado,
                                bar_width,
                                alpha=opacity * 2,
                                color='b',
                                label='TestFinal')
        figuraTest.set_xlabel('Categoría y orientación')

        if escalaEnAngulos:
            figuraTest.set_ylabel('Umbral de detección (ángulo)')
        else:
            figuraTest.set_ylabel('Performance (estímulos)')

        if i == 0:
            figuraTest.set_title(
                'Comparacion test inicial y final según categoria y orientación'
            )
            figuraTest.legend(bbox_to_anchor=(0.95, 1),
                              loc=1,
                              borderaxespad=0.)

        # plt.sca(axarr[i, 0])
        if i == 10:
            figuraTest.xticks(index + bar_width, etiquetasTest)

        if escalaEnAngulos:
            figuraTest.set_ylim([80, 0])
        else:
            figuraTest.set_ylim([0, 200])

        # Remarcamos el entrenamiento
        Max = 80
        pasos = 200
        if escalaEnAngulos:
            MaxCuadradito = Max
        else:
            MaxCuadradito = pasos

        ancho = 0.8

        if resultado['Orientacion'] == 'P30':
            figuraTest.add_patch(
                patches.Rectangle(
                    (0, 0),
                    ancho,
                    MaxCuadradito,
                    fill=False,  # remove background
                    edgecolor="red"))
        if resultado['Orientacion'] == 'A30':
            figuraTest.add_patch(
                patches.Rectangle(
                    (4, 0),
                    ancho,
                    MaxCuadradito,
                    fill=False,  # remove background
                    edgecolor="red"))
Пример #29
0
    def draw(self, filename=None):
        """export a pyplot version of the code :)
        pick your extension with `filename`, or it'll be the
        <code-id>.pdf by default.
        """

        full_size = EAN13Data.full_size
        # then, *relative* dimensions according to pyplot logic
        code_size = EAN13Data.code_size / full_size
        elts_size = EAN13Data.elts_size / full_size
        elt_size = EAN13Data.elt_size / full_size
        label_size = EAN13Data.label_size / full_size
        guard_size = EAN13Data.guard_size / full_size
        before_white = EAN13Data.before_white / full_size.w
        after_white = EAN13Data.after_white / full_size.w
        shift = EAN13Data.shift / full_size.w
        # open new blank figure
        fig, ax = plt.subplots()
        # watch out! the final .svg file size will be *rounded* pts
        # so yeah, we'll basically get a small size error on the overall
        # file size -_-"
        fig.set_size_inches(full_size / XY.inch)
        plt.axis('off')
        # read code and prepare all bars :)
        # draw one full-code-range series of small bars (guards included)
        # then superimpose taller guards bars :P
        x = before_white + shift
        bar_width = elt_size.w
        # iterate over grouped successive identical bits
        g = ((i, sum(1 for _ in it)) for i, it in groupby(self.code))

        # on the way, check whether we stand on a guard on not:
        def guards(g):
            seq = zip((list(elt) for elt in self.elements), self.structure)
            elt, typ = next(seq)
            for bit, number in g:
                for _ in range(number):
                    try:
                        elt.pop(0)
                    except IndexError:
                        elt, typ = next(seq)
                        elt.pop(0)
                yield bit, number, typ

        for bit, number, typ in guards(g):
            width = bar_width * number
            if typ in EAN13Data.guards:
                height = guard_size.h
                y = code_size.h - guard_size.h
            else:
                height = elts_size.h
                y = code_size.h - elts_size.h
            color = 'white' if bit == EAN13Data.white else 'black'
            bar = mpatches.Rectangle(XY(x, y),
                                     width,
                                     height,
                                     ec=None,
                                     fc=color)
            ax.add_patch(bar)
            x += width
        # add label, splat into several parts.. we need them now because one
        shrink = .73  # shrink size coeff so that numbers do not crush ceiling
        spacing = .0079  # horizontal spacing of digits as a `height` factor
        first, second, third = self.id_dashed.split('-')
        height = label_size.h * full_size.h * shrink / XY.pt
        # center between elements and the floor
        y = .5 * (code_size.h - elts_size.h)
        plt.text(before_white,
                 y,
                 first,
                 color='black',
                 size=height,
                 verticalalignment='center')
        normal_guard_length = len(EAN13Data.elements['n'])
        x = before_white + shift + normal_guard_length * bar_width
        for digit in second:
            plt.text(x,
                     y,
                     digit,
                     color='black',
                     size=height,
                     verticalalignment='center')
            x += height * spacing
        x = before_white + shift + elts_size.w - normal_guard_length * bar_width
        for digit in reversed(third):
            plt.text(x,
                     y,
                     digit,
                     color='black',
                     size=height,
                     ha='right',
                     verticalalignment='center')
            x -= height * spacing
        # ah.. there's a kind of `>` at the end..
        last = '>'
        x = before_white + shift + elts_size.w + bar_width
        plt.text(x, y, last, color='black', size=height, ha='left')
        if not filename:
            filename = self.id + '.pdf'
        plt.savefig(filename)
        plt.close()
Пример #30
0
def plot_vrad_w(r_av, U_rad_av, radius_rad_av, v_rad_av, w_av, vel_at_rim,
                ir_vrad_grad_max, time_rad_av, k0_tracer, irmax, trange,
                path_out_figs):
    # r_av[t,k0]:              average radius of tracers
    # radius_rad_av[r]:        radius from azimuthally averaged profiles

    colmap = plt.cm.coolwarm
    colmap = plt.cm.winter

    fig_name = 'w_v_rad_k' + str(k0_tracer) + '_twotimesteps.png'
    fig, axis = plt.subplots(2, 1, figsize=(12, 8), sharex='col')
    ax0 = axis[0]
    ax1 = axis[1]
    for i, t0 in enumerate(trange):
        it = np.int(t0 / dt_fields)
        print('plotting: it, t0', it, t0, tmax)
        if t0 < tmax - 2 * dt_fields:
            print('go', t0, tmax - 2)
            count_color = np.double(i) / (len(trange))
            ir_tracer_0 = np.where(
                radius_rad_av == np.int(np.round(r_av[it,
                                                      k0_tracer], -2)))[0][0]
            ir_tracer_1 = np.where(
                radius_rad_av == np.int(np.round(r_av[it + 1,
                                                      k0_tracer], -2)))[0][0]
            ir_tracer_2 = np.where(
                radius_rad_av == np.int(np.round(r_av[it + 2,
                                                      k0_tracer], -2)))[0][0]
            ir_max_grad = ir_vrad_grad_max[it, k0_tracer]

            for ax in axis:
                ax.plot(
                    [radius_rad_av[ir_tracer_0], radius_rad_av[ir_tracer_0]],
                    [-10, 10],
                    ':',
                    color='0.25',
                    linewidth=1,
                    zorder=0)  # line through tracer
                ax.plot(
                    [radius_rad_av[ir_tracer_1], radius_rad_av[ir_tracer_1]],
                    [-10, 10],
                    ':',
                    color='0.25',
                    linewidth=1,
                    zorder=0)  # line through tracer
                ax.plot(
                    [radius_rad_av[ir_tracer_2], radius_rad_av[ir_tracer_2]],
                    [-10, 10],
                    ':',
                    color='0.25',
                    linewidth=1,
                    zorder=0)  # line through tracer
                ax.plot(
                    [radius_rad_av[ir_max_grad], radius_rad_av[ir_max_grad]],
                    [-10, 10],
                    '--',
                    color='0.25',
                    linewidth=1,
                    zorder=0)  # line through max gradient

            ax0.plot(radius_rad_av, v_rad_av[it, :],
                     color=colmap(count_color))  # , label='t='+str(t0)+'s')
            if i == 0:
                ax0.plot(radius_rad_av[ir_tracer_0],
                         U_rad_av[it, k0_tracer],
                         'gd',
                         label='U tracer: t',
                         markersize=8)  # tracer
                ax0.plot(radius_rad_av[ir_tracer_1],
                         U_rad_av[it + 1, k0_tracer],
                         'kd',
                         label='U tracer: t+1',
                         markersize=8)  # tracer
                ax0.plot(radius_rad_av[ir_tracer_2],
                         U_rad_av[it + 2, k0_tracer],
                         'bd',
                         label='U tracer: t+2',
                         markersize=8)  # tracer
                ax0.plot(radius_rad_av[ir_max_grad],
                         v_rad_av[it, ir_max_grad],
                         'rv',
                         label='max(grad)',
                         markersize=8)
                ax0.plot(radius_rad_av[ir_tracer_0],
                         v_rad_av[it, ir_tracer_0],
                         'go',
                         label='tracer: t')
                ax0.plot(radius_rad_av[ir_tracer_1],
                         v_rad_av[it, ir_tracer_1],
                         'ko',
                         label='tracer: t+1')
                ax0.plot(radius_rad_av[ir_tracer_2],
                         v_rad_av[it, ir_tracer_2],
                         'bo',
                         label='tracer: t+2')
            else:
                ax0.plot(radius_rad_av[ir_tracer_0],
                         U_rad_av[it, k0_tracer],
                         'gd',
                         markersize=8)  # tracer
                ax0.plot(radius_rad_av[ir_tracer_1],
                         U_rad_av[it + 1, k0_tracer],
                         'kd',
                         markersize=8)  # tracer
                ax0.plot(radius_rad_av[ir_tracer_2],
                         U_rad_av[it + 2, k0_tracer],
                         'bd',
                         markersize=8)
                ax0.plot(radius_rad_av[ir_max_grad],
                         v_rad_av[it, ir_max_grad],
                         'rv',
                         markersize=8)
                ax0.plot(radius_rad_av[ir_tracer_0], v_rad_av[it, ir_tracer_0],
                         'go')  # tracer
                ax0.plot(radius_rad_av[ir_tracer_1], v_rad_av[it, ir_tracer_1],
                         'ko')  # tracer
                ax0.plot(radius_rad_av[ir_tracer_2], v_rad_av[it, ir_tracer_2],
                         'bo')  # tracer

            ax1.plot(radius_rad_av,
                     w_av[it, :],
                     color=colmap(count_color),
                     label='t=' + str(t0) + 's')
            ax1.plot(radius_rad_av[ir_max_grad],
                     w_av[it, ir_max_grad],
                     'bv',
                     markersize=7)
            ax1.plot(radius_rad_av[ir_tracer_0], w_av[it, ir_tracer_0],
                     'go')  # tracer
            ax1.plot(radius_rad_av[ir_tracer_1], w_av[it, ir_tracer_1],
                     'ko')  # tracer
            ax1.plot(radius_rad_av[ir_tracer_2], w_av[it, ir_tracer_2],
                     'bo')  # tracer

    ax0.legend(loc='center left', bbox_to_anchor=(.76, 0.6))
    ax1.legend(loc='center left', bbox_to_anchor=(.76, 0.2))  #, frameon=False)
    # rect = mpatches.Rectangle(((irmax*dx-2e3), 2.1), 2.e3, 6.2, fill=True, linewidth=1, edgecolor='k', facecolor='white')
    # ax0.add_patch(rect)
    ax0.set_ylim(np.amin(v_rad_av), np.amax(v_rad_av))
    ax1.set_ylim(-1.2, 1.5)
    for ax in axis.flat:
        ax.set_xlim(0, irmax * dx)
        x_ticks = [np.int(ti * 1e-3) for ti in ax.get_xticks()]
        ax.set_xticklabels(x_ticks)
        # y_ticks = [np.int(ti * 1e-3) for ti in ax.get_yticks()]
        y_ticks = ax.get_yticks()
        ax.set_yticklabels(y_ticks)
        # for label in ax.xaxis.get_ticklabels()[1::2]:
        #     label.set_visible(False)
        # for label in ax.yaxis.get_ticklabels()[1::2]:
        #     label.set_visible(False)
    ax1.set_xlabel('radius r / km')
    ax0.set_ylabel('radial velocity / ms' + r'$^{-1}$')
    ax1.set_ylabel('vertical velocity / ms' + r'$^{-1}$')
    fig.subplots_adjust(top=0.95,
                        bottom=0.1,
                        left=0.1,
                        right=0.9,
                        hspace=0.1,
                        wspace=0.25)
    print('saving at ', os.path.join(path_out_figs, fig_name))
    fig.savefig(os.path.join(path_out_figs, fig_name))
    plt.close(fig)

    fig_name = 'w_v_rad_k' + str(k0_tracer) + '.png'
    fig, axis = plt.subplots(2, 1, figsize=(8, 8), sharex='col')
    ax0 = axis[0]
    ax1 = axis[1]
    for i, t0 in enumerate(trange):
        it = np.int(t0 / dt_fields)
        print('it, t0', it, t0)
        count_color = np.double(i) / (len(trange) - 1)
        # ir_tracer_1 = np.where(radius_rad_av == np.int(np.round(r_av[it + 1, k0_tracer], -2)))[0][0]
        ir_tracer_0 = np.where(
            radius_rad_av == np.int(np.round(r_av[it, k0_tracer], -2)))[0][0]
        ir_max_grad = ir_vrad_grad_max[it, k0_tracer]

        for ax in axis:
            ax.plot([radius_rad_av[ir_tracer_0], radius_rad_av[ir_tracer_0]],
                    [-10, 10],
                    ':',
                    color='0.25',
                    linewidth=1,
                    zorder=0)  # line through tracer
            # ax.plot([radius_rad_av[ir_tracer_1], radius_rad_av[ir_tracer_1]], [-10, 10], ':', color='0.25',
            #      linewidth=1, zorder=0)  # line through tracer
            ax.plot([radius_rad_av[ir_max_grad], radius_rad_av[ir_max_grad]],
                    [-10, 10],
                    '--',
                    color='0.25',
                    linewidth=1,
                    zorder=0)  # line through max gradient

        ax0.plot(radius_rad_av, v_rad_av[it, :],
                 color=colmap(count_color))  # , label='t='+str(t0)+'s')
        ax1.plot(radius_rad_av,
                 w_av[it, :],
                 color=colmap(count_color),
                 label='t=' + str(t0) + 's')

        if i == 0:
            ax0.plot(radius_rad_av[ir_max_grad],
                     v_rad_av[it, ir_max_grad],
                     'bv',
                     label='max(grad)',
                     markersize=7)
            ax0.plot(radius_rad_av[ir_tracer_0],
                     v_rad_av[it, ir_tracer_0],
                     'ko',
                     label='tracer')  # tracer
            # ax0.plot(radius_rad_av[ir_tracer_1], v_rad_av[it, ir_tracer_1], 'ko', label='tracer')  # tracer
            # ax0.plot(radius_rad_av[ir_tracer_1], U_rad_av[it, k0_tracer], 'ko', label='tracer')  # tracer
        else:
            ax0.plot(radius_rad_av[ir_max_grad],
                     v_rad_av[it, ir_max_grad],
                     'bv',
                     markersize=7)
            ax0.plot(radius_rad_av[ir_tracer_0], v_rad_av[it, ir_tracer_0],
                     'ko')  # tracer
            # ax0.plot(radius_rad_av[ir_tracer_1], v_rad_av[it, ir_tracer_1], 'ko')  # tracer

        ax1.plot(radius_rad_av[ir_max_grad],
                 w_av[it, ir_max_grad],
                 'bv',
                 markersize=7)
        ax1.plot(radius_rad_av[ir_tracer_0], w_av[it, ir_tracer_0],
                 'ko')  # tracer
        # ax1.plot(radius_rad_av[ir_tracer_1], w_av[it, ir_tracer_1], 'ko')  # tracer

    ax0.legend(loc='center left', bbox_to_anchor=(.77, 0.89), frameon=False)
    ax1.legend(loc='center left', bbox_to_anchor=(.77, 1.67), frameon=False)
    # irmax = 9e3
    rect = mpatches.Rectangle((6.9e3, 2.4),
                              2.e3,
                              5.9,
                              fill=True,
                              linewidth=1,
                              edgecolor='k',
                              facecolor='white')
    # irmax = 9.5e3
    # rect = mpatches.Rectangle((7.3e3, 2.4), 2.1e3, 5.9, fill=True, linewidth=1, edgecolor='k', facecolor='white')
    ax0.add_patch(rect)

    textprops = dict(facecolor='white', alpha=0.9, linewidth=0.)
    ax0.text(4.9e2, 7.2, 'a)', fontsize=18, bbox=textprops)
    ax1.text(4.9e2, 1.13, 'b)', fontsize=18)

    ax0.set_ylim(np.amin(v_rad_av), np.amax(v_rad_av))
    # ax0.set_ylim(-0.5, 8.)
    ax1.set_ylim(-1., 1.5)
    for ax in axis.flat:
        ax.set_xlim(0, irmax * dx)
        x_ticks = [np.int(ti * 1e-3) for ti in ax.get_xticks()]
        ax.set_xticklabels(x_ticks)
        y_ticks = ax.get_yticks()
        ax.set_yticklabels(y_ticks)
        # for label in ax.xaxis.get_ticklabels()[1::2]:
        #     label.set_visible(False)
        # for label in ax.yaxis.get_ticklabels()[1::2]:
        #     label.set_visible(False)
    ax1.set_xlabel('radius r / km')
    ax0.set_ylabel('radial velocity / ms' + r'$^{-1}$')
    ax1.set_ylabel('vertical velocity / ms' + r'$^{-1}$')
    fig.subplots_adjust(top=0.97,
                        bottom=0.07,
                        left=0.11,
                        right=0.95,
                        hspace=0.1,
                        wspace=0.25)
    fig.savefig(os.path.join(path_out_figs, fig_name))
    plt.close(fig)

    return