Пример #1
0
def invert_qubits_state(state: coo_matrix, length: int) -> coo_matrix:
    new_idx = range(2**length)
    result = np.array(list(
        map(lambda i: aux.to_decimal(aux.decimal_to_binary(i, length)[::-1]),
            new_idx)),
                      dtype=np.int64)
    return state.toarray().reshape((2**length), )[result]
Пример #2
0
def plot_binarized_vs_weighted_roi(
        weighted_mask: coo_matrix, binary_mask: coo_matrix,
        weighted_trace: np.ndarray,
        binary_trace: np.ndarray) -> matplotlib.figure.Figure:
    fig = plt.figure(constrained_layout=True)
    gs = fig.add_gridspec(nrows=3, ncols=6)

    # Plot ROIs
    binary_roi_ax = fig.add_subplot(gs[:-1, -3:])
    weighted_roi_ax = fig.add_subplot(gs[:-1, :-3],
                                      sharex=binary_roi_ax,
                                      sharey=binary_roi_ax)

    weighted_roi_ax.set_xticks([])
    weighted_roi_ax.set_yticks([])
    weighted_roi_ax.set_title("Native Suite2P (weighted) ROI")
    weighted_roi_ax.imshow(weighted_mask.toarray())
    xmin, xmax, ymin, ymax = weighted_roi_ax.axis()

    binary_roi_ax.set_xticks([])
    binary_roi_ax.set_yticks([])
    binary_roi_ax.set_title("Binarized Suite2P ROI")
    binary_roi_ax.imshow(binary_mask.toarray())
    binary_roi_ax.set_xlim(xmin, xmax)
    binary_roi_ax.set_ylim(ymin, ymax)

    # Plot traces
    binary_trace_ax = fig.add_subplot(gs[-1, -3:])
    weighted_trace_ax = fig.add_subplot(gs[-1, :-3],
                                        sharex=binary_trace_ax,
                                        sharey=binary_trace_ax)

    weighted_trace_ax.set_ylabel("Weighted F")
    weighted_trace_ax.set_xlabel("Frame Number")
    weighted_trace_ax.plot(range(len(weighted_trace)),
                           weighted_trace,
                           linewidth=0.5)

    binary_trace_ax.set_ylabel("Binarized F")
    binary_trace_ax.set_xlabel("Frame Number")
    binary_trace_ax.plot(range(len(binary_trace)),
                         binary_trace,
                         linewidth=0.25)

    return fig
Пример #3
0
def col_compress(matrix_in: coo_matrix, indices: bool = False) -> csr_matrix:
    matrix = np.sort(matrix_in.toarray(), axis=1)
    indices_out = []
    for col_index in range(matrix.shape[1] - 1):
        if np.array_equal(matrix[:, col_index], matrix[:, col_index + 1]):
            indices_out.append(col_index)
    if indices:
        return indices_out
    return csr_matrix(
        matrix[:, list(set(range(matrix.shape[1])) - set(indices_out))],
        dtype=np.uint8)
Пример #4
0
    def _hu_moments(roi: coo_matrix) -> np.ndarray:
        """Returns the 7 Hu moments for an ROI image. See 
        https://scikit-image.org/docs/0.17.x/api/skimage.measure.html#moments-hu        # noqa
        for more information.

        Returns
        -------
        7-element, 1d np.array of Hu's image moments

        References
        ----------
        M. K. Hu, “Visual Pattern Recognition by Moment Invariants”, 
        IRE Trans. Info. Theory, vol. IT-8, pp. 179-187, 1962
        """
        roi_image = roi.toarray()
        mu = moments_central(roi_image)
        nu = moments_normalized(mu)
        return moments_hu(nu)
Пример #5
0
def stage_data(
        spots: pd.DataFrame,
        coo: coo_matrix) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
    """
    Reads the spots and the label image that are passed in and calculates which cell (if any) encircles any
    given spot within its boundaries. It also retrieves the coordinates of the cell boundaries, the cell
    centroids and the cell area
    """
    logger.info(' Number of spots passed-in: %d' % spots.shape[0])
    logger.info(' Number of segmented cells: %d' % len(set(coo.data)))
    logger.info(
        ' Segmentation array implies that image has width: %dpx and height: %dpx'
        % (coo.shape[1], coo.shape[0]))
    mask_x = (spots.x >= 0) & (spots.x <= coo.shape[1])
    mask_y = (spots.y >= 0) & (spots.y <= coo.shape[0])
    spots = spots[mask_x & mask_y]

    # Debugging code!
    # resuffle
    # spots = spots.sample(frac=1).reset_index(drop=True)

    # _point = [5471-14, 110]
    # logger.info('label at (y, x): (%d, %d) is %d' % (_point[0], _point[1], coo.toarray()[_point[0], _point[1]]))

    # coo = remap_labels(coo)
    # logger.info('remapped label at (y, x): (%d, %d) is %d' % (_point[0], _point[1], coo.toarray()[_point[0], _point[1]]))

    # 1. Find which cell the spots lie within
    yx_coords = spots[['y', 'x']].values.T
    inc = inside_cell(coo.tocsr(), yx_coords)
    spots = spots.assign(label=inc)

    # 2. Get cell centroids and area
    props = skmeas.regionprops(coo.toarray().astype(np.int32))
    props_df = pd.DataFrame(data=[
        (d.label, d.area, d.centroid[1], d.centroid[0]) for d in props
    ],
                            columns=['label', 'area', 'x_cell', 'y_cell'])

    # 3. Get the cell boundaries
    cell_boundaries = extract_borders_dip(coo.toarray().astype(np.uint32), 0,
                                          0, [0])

    assert props_df.shape[0] == cell_boundaries.shape[0] == coo.data.max()
    assert set(spots.label[spots.label > 0]) <= set(props_df.label)

    cells = props_df.merge(cell_boundaries)
    cells.sort_values(by=['label', 'x_cell', 'y_cell'])
    assert cells.shape[0] == cell_boundaries.shape[0] == props_df.shape[0]

    # join spots and cells on the cell label so you can get the x,y coords of the cell for any given spot
    spots = spots.merge(cells, how='left', on=['label'])

    _cells = cells[['label', 'area', 'x_cell', 'y_cell']].rename(columns={
        'x_cell': 'x',
        'y_cell': 'y'
    })
    _cell_boundaries = cells[['label', 'coords']]
    _spots = spots[['x', 'y', 'label', 'Gene', 'x_cell',
                    'y_cell']].rename(columns={
                        'Gene': 'target',
                        'x': 'x_global',
                        'y': 'y_global'
                    })

    return _cells, _cell_boundaries, _spots