File size: 8,626 Bytes
64212e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import os
import numpy as np
from PIL import Image, ImageSequence
import json
import pandas as pd

import torch
from torch.utils.data import Dataset
from torchvision import transforms
import torchvision.transforms.functional as TF

from celle.utils import replace_outliers

def simple_conversion(seq):
    """Create 26-dim embedding"""
    chars = [
        "-",
        "M",
        "R",
        "H",
        "K",
        "D",
        "E",
        "S",
        "T",
        "N",
        "Q",
        "C",
        "U",
        "G",
        "P",
        "A",
        "V",
        "I",
        "F",
        "Y",
        "W",
        "L",
        "O",
        "X",
        "Z",
        "B",
        "J",
    ]

    nums = range(len(chars))

    seqs_x = np.zeros(len(seq))

    for idx, char in enumerate(seq):

        lui = chars.index(char)

        seqs_x[idx] = nums[lui]

    return torch.tensor([seqs_x]).long()


class CellLoader(Dataset):
    """imports mined opencell images with protein sequence"""

    def __init__(
        self,
        data_csv=None,
        dataset=None,
        split_key=None,
        resize=600,
        crop_size=600,
        crop_method="random",
        sequence_mode="simple",
        vocab="bert",
        threshold="median",
        text_seq_len=0,
        pad_mode="random",
    ):
        self.data_csv = data_csv
        self.dataset = dataset
        self.image_folders = []
        self.crop_method = crop_method
        self.resize = resize
        self.crop_size = crop_size
        self.sequence_mode = sequence_mode
        self.threshold = threshold
        self.text_seq_len = int(text_seq_len)
        self.vocab = vocab
        self.pad_mode = pad_mode

        if self.sequence_mode == "embedding" or self.sequence_mode == "onehot":


            if self.vocab == "esm1b" or self.vocab == "esm2":
                from esm import Alphabet

                self.tokenizer = Alphabet.from_architecture(
                    "ESM-1b"
                ).get_batch_converter()
                self.text_seq_len += 2

        if data_csv:

            data = pd.read_csv(data_csv)

            self.parent_path = os.path.dirname(data_csv).split(data_csv)[0]

            if split_key == "train":
                self.data = data[data["split"] == "train"]
            elif split_key == "val":
                self.data = data[data["split"] == "val"]
            else:
                self.data = data

            self.data = self.data.reset_index(drop=True)
            
                

    def __len__(self):
        return len(self.data)

    def __getitem__(
        self,
        idx,
        get_sequence=True,
        get_images=True,
    ):
        if get_sequence and self.text_seq_len > 0:

            protein_vector = self.get_protein_vector(idx)

        else:
            protein_vector = torch.zeros((1, 1))

        if get_images:

            nucleus, target, threshold = self.get_images(idx, self.dataset)
        else:
            nucleus, target, threshold = torch.zeros((3, 1))

        data_dict = {
            "nucleus": nucleus.float(),
            "target": target.float(),
            "threshold": threshold.float(),
            "sequence": protein_vector.long(),
        }

        return data_dict

    def get_protein_vector(self, idx):

        if "protein_sequence" not in self.data.columns:

            metadata = self.retrieve_metadata(idx)
            protein_sequence = metadata["sequence"]
        else:
            protein_sequence = self.data.iloc[idx]["protein_sequence"]

        protein_vector = self.tokenize_sequence(protein_sequence)

        return protein_vector

    def get_images(self, idx, dataset):

        if dataset == "HPA":

            nucleus = Image.open(
                os.path.join(
                    self.parent_path, self.data.iloc[idx]["nucleus_image_path"]
                )
            )

            target = Image.open(
                os.path.join(self.parent_path, self.data.iloc[idx]["target_image_path"])
            )

            nucleus = TF.to_tensor(nucleus)[0]
            target = TF.to_tensor(target)[0]

            image = torch.stack([nucleus, target], axis=0)

            normalize = (0.0655, 0.0650), (0.1732, 0.1208)

        elif dataset == "OpenCell":
            image = Image.open(
                os.path.join(self.parent_path, self.data.iloc[idx]["image_path"])
            )
            nucleus, target = [page.copy() for page in ImageSequence.Iterator(image)]

            nucleus = replace_outliers(torch.divide(TF.to_tensor(nucleus), 65536))[0]
            target = replace_outliers(torch.divide(TF.to_tensor(target), 65536))[0]

            image = torch.stack([nucleus, target], axis=0)

            normalize = (
                (0.0272, 0.0244),
                (0.0486, 0.0671),
            )

        # # from https://discuss.pytorch.org/t/how-to-apply-same-transform-on-a-pair-of-picture/14914

        t_forms = [transforms.Resize(self.resize, antialias=None)]

        if self.crop_method == "random":

            t_forms.append(transforms.RandomCrop(self.crop_size))
            t_forms.append(transforms.RandomHorizontalFlip(p=0.5))
            t_forms.append(transforms.RandomVerticalFlip(p=0.5))

        elif self.crop_method == "center":

            t_forms.append(transforms.CenterCrop(self.crop_size))

        t_forms.append(transforms.Normalize(normalize[0], normalize[1]))

        image = transforms.Compose(t_forms)(image)

        nucleus, target = image

        nucleus /= torch.abs(nucleus).max()
        target -= target.min()
        target /= target.max()

        nucleus = nucleus.unsqueeze(0)
        target = target.unsqueeze(0)

        threshold = target

        if self.threshold == "mean":

            threshold = 1.0 * (threshold > (torch.mean(threshold)))

        elif self.threshold == "median":

            threshold = 1.0 * (threshold > (torch.median(threshold)))

        elif self.threshold == "1090_IQR":

            p10 = torch.quantile(threshold, 0.1, None)
            p90 = torch.quantile(threshold, 0.9, None)
            threshold = torch.clip(threshold, p10, p90)

        nucleus = torch.nan_to_num(nucleus, 0.0, 1.0, 0.0)
        target = torch.nan_to_num(target, 0.0, 1.0, 0.0)
        threshold = torch.nan_to_num(threshold, 0.0, 1.0, 0.0)

        return nucleus, target, threshold

    def retrieve_metadata(self, idx):
        with open(
            os.path.join(self.parent_path, self.data.iloc[idx]["metadata_path"])
        ) as f:
            metadata = json.load(f)

        return metadata

    def tokenize_sequence(self, protein_sequence):

        pad_token = 0

        if self.sequence_mode == "simple":
            protein_vector = simple_conversion(protein_sequence)

        elif self.sequence_mode == "center":
            protein_sequence = protein_sequence.center(self.text_seq_length, "-")
            protein_vector = simple_conversion(protein_sequence)

        elif self.sequence_mode == "alternating":
            protein_sequence = protein_sequence.center(self.text_seq_length, "-")
            protein_sequence = protein_sequence[::18]
            protein_sequence = protein_sequence.center(
                int(self.text_seq_length / 18) + 1, "-"
            )
            protein_vector = simple_conversion(protein_sequence)


        elif self.sequence_mode == "embedding":

            if self.vocab == "esm1b" or self.vocab == "esm2":
                pad_token = 1
                protein_vector = self.tokenizer([("", protein_sequence)])[-1]

        if protein_vector.shape[-1] < self.text_seq_len:

            diff = self.text_seq_len - protein_vector.shape[-1]

            if self.pad_mode == "end":
                protein_vector = torch.nn.functional.pad(
                    protein_vector, (0, diff), "constant", pad_token
                )
            elif self.pad_mode == "random":
                split = diff - np.random.randint(0, diff + 1)

                protein_vector = torch.cat(
                    [torch.ones(1, split) * 0, protein_vector], dim=1
                )

                protein_vector = torch.nn.functional.pad(
                    protein_vector, (0, diff - split), "constant", pad_token
                )

        elif protein_vector.shape[-1] > self.text_seq_len:
            start_int = np.random.randint(
                0, protein_vector.shape[-1] - self.text_seq_len
            )

            protein_vector = protein_vector[
                :, start_int : start_int + self.text_seq_len
            ]

        return protein_vector.long()