Skip to content

Find Spots

view_find_spots

This viewer shows how spots are detected in an image. There are sliders to vary the parameters used for spot detection so the effect of them can be seen.

Can also view points from ±z_thick z-planes on current z-plane using the z thickness slider. Initially, z thickness will be 1.

Requires access to nb.file_names.input_dir or nb.file_names.tile_dir

Parameters:

Name Type Description Default
nb Optional[Notebook]

Notebook for experiment. If no Notebook exists, pass config_file instead. In this case, the raw images will be loaded and then filtered according to parameters in config['extract'].

None
t int

npy (as opposed to nd2 fov) tile index to view. For an experiment where the tiles are arranged in a 4 x 3 (ny x nx) grid, tile indices are indicated as below:

| 2 | 1 | 0 |

| 5 | 4 | 3 |

| 8 | 7 | 6 |

| 11 | 10 | 9 |

0
r int

round to view

0
c int

Channel to view.

0
show_isolated bool

Spots which are identified as isolated in the anchor round/channel are used to compute the bleed_matrix. Can see which spots are isolated by setting this to True. Note, this is very slow in 3D, around 300s for a 2048 x 2048 x 50 image.

False
config_file Optional[str]

path to config file for experiment.

None
Source code in coppafish/plot/find_spots/viewer.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def __init__(self, nb: Optional[Notebook] = None, t: int = 0, r: int = 0, c: int = 0,
             show_isolated: bool = False, config_file: Optional[str] = None):
    """
    This viewer shows how spots are detected in an image.
    There are sliders to vary the parameters used for spot detection so the effect of them can be seen.

    Can also view points from `±z_thick` z-planes on current z-plane using the z thickness slider. Initially,
    z thickness will be 1.

    !!! warning "Requires access to `nb.file_names.input_dir` or `nb.file_names.tile_dir`"

    Args:
        nb: *Notebook* for experiment. If no *Notebook* exists, pass `config_file` instead. In this case,
            the raw images will be loaded and then filtered according to parameters in `config['extract']`.
        t: npy (as opposed to nd2 fov) tile index to view.
            For an experiment where the tiles are arranged in a 4 x 3 (ny x nx) grid, tile indices are indicated as
            below:

            | 2  | 1  | 0  |

            | 5  | 4  | 3  |

            | 8  | 7  | 6  |

            | 11 | 10 | 9  |
        r: round to view
        c: Channel to view.
        show_isolated: Spots which are identified as *isolated* in the anchor round/channel are used to compute
            the `bleed_matrix`. Can see which spots are isolated by setting this to `True`.
            Note, this is very slow in *3D*, around 300s for a 2048 x 2048 x 50 image.
        config_file: path to config file for experiment.
    """
    if nb is None:
        nb = Notebook(config_file=config_file)
    add_basic_info_no_save(nb)  # deal with case where there is no notebook yet

    if r == nb.basic_info.anchor_round:
        if c != nb.basic_info.anchor_channel:
            raise ValueError(f'No spots are found on round {r}, channel {c} in the pipeline.\n'
                             f'Only spots on anchor_channel = {nb.basic_info.anchor_channel} used for the '
                             f'anchor round.')
    if r == nb.basic_info.ref_round and c == nb.basic_info.ref_channel:
        if show_isolated:
            self.show_isolated = True
        else:
            self.show_isolated = False
    else:
        if show_isolated:
            warnings.warn(f'Not showing isolated spots as slow and isolated status not used for round {r},'
                          f' channel {c}')
        self.show_isolated = False

    self.is_3d = nb.basic_info.is_3d
    if self.is_3d:
        tile_file = nb.file_names.tile[t][r][c]
    else:
        tile_file = nb.file_names.tile[t][r]
    if not os.path.isfile(tile_file):
        warnings.warn(f"The file {tile_file}\ndoes not exist so loading raw image and filtering it")
        self.image = get_filtered_image(nb, t, r, c)
    else:
        self.image = utils.npy.load_tile(nb.file_names, nb.basic_info, t, r, c)
        scale = 1  # Can be any value as not actually used but needed as argument in get_extract_info

    # Get auto_threshold value used to detect spots
    if nb.has_page('extract'):
        self.auto_thresh = nb.extract.auto_thresh[t, r, c]
    else:
        config = nb.get_config()['extract']
        z_info = int(np.floor(nb.basic_info.nz / 2))
        hist_values = np.arange(-nb.basic_info.tile_pixel_value_shift,
                                np.iinfo(np.uint16).max - nb.basic_info.tile_pixel_value_shift + 2, 1)
        hist_bin_edges = np.concatenate((hist_values - 0.5, hist_values[-1:] + 0.5))
        max_npy_pixel_value = np.iinfo(np.uint16).max - nb.basic_info.tile_pixel_value_shift
        self.auto_thresh = extract.get_extract_info(self.image, config['auto_thresh_multiplier'], hist_bin_edges,
                                                    max_npy_pixel_value, scale, z_info)[0]

    config = nb.get_config()['find_spots']
    self.r_xy = config['radius_xy']
    if self.is_3d:
        self.r_z = config['radius_z']
    else:
        self.r_z = None
    if config['isolation_thresh'] is None:
        config['isolation_thresh'] = self.auto_thresh * config['auto_isolation_thresh_multiplier']
    self.isolation_thresh = config['isolation_thresh']
    self.r_isolation_inner = config['isolation_radius_inner']
    self.r_isolation_xy = config['isolation_radius_xy']
    self.normal_color = np.array([1, 0, 0, 1]) # red
    self.isolation_color = np.array([0, 1, 0, 1])  # green
    self.neg_neighb_color = np.array([0, 0, 1, 1])  # blue
    self.point_size = 9
    self.z_thick = 1  # show +/- 1 plane initially
    self.z_thick_list = np.arange(1, 1 + 15 * 2, 2)  # only odd z-thick make any difference
    if self.is_3d:
        self.r_isolation_z = config['isolation_radius_z']
    else:
        self.r_isolation_z = None

    self.small = 1e-6  # for computing local maxima: shouldn't matter what it is (keep below 0.01 for int image).
    # perturb image by small amount so two neighbouring pixels that did have the same value now differ slightly.
    # hence when find maxima, will only get one of the pixels not both.
    rng = np.random.default_rng(0)   # So shift is always the same.
    # rand_shift must be larger than small to detect a single spot.
    rand_im_shift = rng.uniform(low=self.small*2, high=0.2, size=self.image.shape)
    self.image = self.image + rand_im_shift

    self.dilate = None
    self.spot_zyx = None
    self.image_isolated = None
    self.no_negative_neighbour = None
    self.update_dilate()
    if self.show_isolated:
        self.update_isolated_image()
    self.viewer = napari.Viewer()
    name = f"Tile {t}, Round {r}, Channel {c}"
    if self.is_3d:
        self.viewer.add_image(np.moveaxis(np.rint(self.image).astype(np.int32), 2, 0), name=name)
    else:
        self.viewer.add_image(np.rint(self.image).astype(np.int32), name=name)

    self.thresh_slider = QSlider(Qt.Orientation.Horizontal)
    self.thresh_slider.setRange(0, 3 * self.auto_thresh)
    self.thresh_slider.setValue(self.auto_thresh)
    # When dragging, status will show auto_thresh value
    self.thresh_slider.valueChanged.connect(lambda x: self.show_thresh(x))
    # On release of slider, filtered / smoothed images updated
    self.thresh_slider.sliderReleased.connect(self.update_spots)
    self.viewer.window.add_dock_widget(self.thresh_slider, area="left", name='Intensity Threshold')
    if self.show_isolated:
        self.isolation_thresh_slider = QSlider(Qt.Orientation.Horizontal)
        self.isolation_thresh_slider.setRange(-2 * np.abs(self.isolation_thresh), 0)
        self.isolation_thresh_slider.setValue(self.isolation_thresh)
        # When dragging, status will show auto_thresh value
        self.isolation_thresh_slider.valueChanged.connect(lambda x: self.show_isolation_thresh(x))
        # On release of slider, filtered / smoothed images updated
        self.isolation_thresh_slider.sliderReleased.connect(self.update_isolated_spots)
    self.update_spots()

    self.r_xy_slider = QSlider(Qt.Orientation.Horizontal)
    self.r_xy_slider.setRange(2, 10)
    self.r_xy_slider.setValue(self.r_xy)
    # When dragging, status will show r_xy value
    self.r_xy_slider.valueChanged.connect(lambda x: self.show_radius_xy(x))
    # On release of slider, filtered / smoothed images updated
    self.r_xy_slider.sliderReleased.connect(self.radius_slider_func)
    self.viewer.window.add_dock_widget(self.r_xy_slider, area="left", name='Detection Radius YX')

    if self.is_3d:
        self.r_z_slider = QSlider(Qt.Orientation.Horizontal)
        self.r_z_slider.setRange(2, 12)
        self.r_z_slider.setValue(self.r_xy)
        # When dragging, status will show r_z value
        self.r_z_slider.valueChanged.connect(lambda x: self.show_radius_z(x))
        # On release of slider, filtered / smoothed images updated
        self.r_z_slider.sliderReleased.connect(self.radius_slider_func)
        self.viewer.window.add_dock_widget(self.r_z_slider, area="left", name='Detection Radius Z')

        self.z_thick_slider = QSlider(Qt.Orientation.Horizontal)
        self.z_thick_slider.setRange(0, int((self.z_thick_list[-1] - 1) / 2))
        self.z_thick_slider.setValue(self.z_thick)
        # When dragging, status will show r_z value
        self.z_thick_slider.valueChanged.connect(lambda x: self.change_z_thick(x))
        self.viewer.window.add_dock_widget(self.z_thick_slider, area="left", name='Z Thickness')

    if self.show_isolated:
        self.viewer.window.add_dock_widget(self.isolation_thresh_slider, area="left", name='Isolation Threshold')
    # set image as selected layer so can see intensity values in status
    self.viewer.layers.selection.active = self.viewer.layers[0]
    napari.run()

n_spots_grid(nb, n_spots_thresh=None)

Plots a grid indicating the number of spots detected on each tile, round and channel.

Parameters:

Name Type Description Default
nb Notebook

Notebook containing find_spots page.

required
n_spots_thresh Optional[int]

tiles/rounds/channels with fewer spots than this will be highlighted. If None, will use n_spots_warn_fraction from config file.

None
Source code in coppafish/plot/find_spots/n_spots.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def n_spots_grid(nb: Notebook, n_spots_thresh: Optional[int] = None):
    """
    Plots a grid indicating the number of spots detected on each tile, round and channel.

    Args:
        nb: *Notebook* containing `find_spots` page.
        n_spots_thresh: tiles/rounds/channels with fewer spots than this will be highlighted.
            If `None`, will use `n_spots_warn_fraction` from config file.
    """
    if n_spots_thresh is None:
        config = nb.get_config()['find_spots']
        if nb.basic_info.is_3d:
            n_spots_thresh = config['n_spots_warn_fraction'] * config['max_spots_3d'] * nb.basic_info.nz
        else:
            n_spots_thresh = config['n_spots_warn_fraction'] * config['max_spots_2d']
        n_spots_thresh = int(np.ceil(n_spots_thresh))
    use_tiles = np.asarray(nb.basic_info.use_tiles)
    use_rounds = np.asarray(nb.basic_info.use_rounds)  # don't consider anchor in this analysis
    if len(use_rounds) > 0:
        use_channels = np.asarray(nb.basic_info.use_channels)
        spot_no = nb.find_spots.spot_no[np.ix_(use_tiles, use_rounds, use_channels)]
        spot_no = np.moveaxis(spot_no, 1, 2)  # put rounds last
        spot_no = spot_no.reshape(len(use_tiles), -1).T  # spot_no[n_rounds, t] is now spot_no[t, r=0, c=1]
        n_round_channels = len(use_rounds) * len(use_channels)
        y_labels = np.tile(use_rounds, len(use_channels))
        vmax = spot_no.max()  # clip colorbar at max of imaging rounds/channels because anchor can be a lot higher
    else:
        # Deal with case where only anchor round
        use_channels = np.asarray([])
        spot_no = np.zeros((0, len(use_tiles)), dtype=np.int32)
        n_round_channels = 0
        y_labels = np.zeros(0, dtype=int)
        vmax = None
    if nb.basic_info.use_anchor:
        anchor_spot_no = nb.find_spots.spot_no[use_tiles, nb.basic_info.anchor_round,
                                               nb.basic_info.anchor_channel][np.newaxis]
        spot_no = np.append(spot_no, anchor_spot_no, axis=0)
        y_labels = y_labels.astype(str).tolist()
        y_labels += ['Anchor']
        n_round_channels += 1
        if vmax is None:
            vmax = spot_no.max()
    fig, ax = plt.subplots(1, 1, figsize=(np.clip(5+len(use_tiles)/2, 3, 18), 12))
    subplot_adjust = [0.12, 1, 0.07, 0.9]
    fig.subplots_adjust(left=subplot_adjust[0], right=subplot_adjust[1],
                        bottom=subplot_adjust[2], top=subplot_adjust[3])
    im = ax.imshow(spot_no, aspect='auto', vmax=vmax)
    fig.colorbar(im, ax=ax)
    ax.set_yticks(np.arange(n_round_channels))
    ax.set_yticklabels(y_labels)
    ax.set_xticks(np.arange(len(use_tiles)))
    ax.set_xticklabels(use_tiles)
    ax.set_xlabel('Tile')

    for c in range(len(use_channels)):
        y_ind = 1 - c * 1/(len(use_channels))
        ax.text(-0.1, y_ind, f"Channel {use_channels[c]}", va="top", ha="left", transform=ax.transAxes,
                rotation='vertical')
    fig.supylabel('Channel/Round', transform=ax.transAxes, x=-0.15)
    plt.xticks(rotation=90)
    low_spots = np.where(spot_no<n_spots_thresh)
    for j in range(len(low_spots[0])):
        rectangle = plt.Rectangle((low_spots[1][j] - 0.5, low_spots[0][j] - 0.5), 1, 1,
                                  fill=False, ec="r", linestyle=':', lw=2)
        ax.add_patch(rectangle)
    plt.suptitle(f"Number of Spots Found on each Tile, Round and Channel")
    plt.show()