-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathadat_meta_helpers.py
More file actions
544 lines (439 loc) · 18.5 KB
/
adat_meta_helpers.py
File metadata and controls
544 lines (439 loc) · 18.5 KB
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
from __future__ import annotations
import logging
import warnings
from typing import Dict, List, Set, Tuple, Union
import numpy as np
import pandas as pd
from somadata.errors import AdatKeyError, AdatMetaError
from somadata.tools.pandas import get_pd_axis
logger = logging.getLogger(__name__)
class AdatMetaHelpers:
"""A collection of methods to help with altering the adat metadata and the adat based on the metadata."""
def _filter_on_meta(
self,
axis: int,
name: str,
values: Union[List[str], Set[str], Tuple[str]],
include: bool = True,
) -> Adat:
# Check to see if values is the right variable type
if not isinstance(values, (list, tuple, set)):
raise TypeError('"values" must be a list, tuple, or set.')
else:
values = set(values)
# Setup array and get appropriate multiindex
keep = []
metadata = get_pd_axis(self, axis)
# Check to ensure all values are in the metadata
metadata_values = set(metadata.get_level_values(name))
if not metadata_values.issuperset(values):
raise KeyError(
f'Some or all provided values not found in metadata column, {name}.'
)
# Iterate over the selected multiindex and fill the keep array
for value in metadata.get_level_values(name):
if value in values:
keep.append(True)
else:
keep.append(False)
# Invert the keep array if we are excluding the chosen values
if not include:
keep = np.invert(keep)
# Subset the adat
if axis == 0:
adat = self.loc[keep]
elif axis == 1:
adat = self.loc[:, keep]
# Return the subsetted adat (default) or modify the current adat in place
return adat.copy()
def _filter_meta(
self, axis: int, names: Union[List[str], Set[str], Tuple[str]], include: bool
) -> Adat:
# Check to see if names is the right variable type
if not isinstance(names, (list, tuple, set)):
raise TypeError('"values" must be a list, tuple, or set.')
else:
names = set(names)
# Make a copy of the df (what we will eventually return) & grab the multiindex
adat = self.copy()
metadata = get_pd_axis(adat, axis)
# Double check to make sure names exist in multiindex
for name in names:
if name not in metadata.names:
raise AdatKeyError(f'Name, "{name}", not found in multiindex')
# Filter down the metadata
for name in metadata.names:
if name not in names and include:
metadata = metadata.droplevel(name)
if name in names and not include:
metadata = metadata.droplevel(name)
# Assign the metadata to the appropriate place
if axis == 0:
adat.index = metadata
else:
adat.columns = metadata
return adat
def _insert_meta(
self, axis: int, name: str, values: Union[List[str], Tuple[str]], replace: bool
) -> Adat:
adat = self.copy()
if axis == 0:
if not replace and name in adat.index.names:
raise AdatKeyError(
'Name already exists in index, use `adat.replace_meta` instead.'
)
elif replace and name not in adat.index.names:
raise AdatKeyError(
'Name does not exists in index, use `adat.insert_meta` instead.'
)
index_df = adat.index.to_frame()
index_df[name] = values
adat.index = pd.MultiIndex.from_frame(index_df)
elif axis == 1:
if not replace and name in adat.columns.names:
raise AdatKeyError(
'Name already exists in columns, use `adat.replace_meta` instead.'
)
elif replace and name not in adat.columns.names:
raise AdatKeyError(
'Name does not exists in columns, use `adat.insert_meta` instead.'
)
columns_df = adat.columns.to_frame()
columns_df.loc[:, name] = values
adat.columns = pd.MultiIndex.from_frame(columns_df)
return adat
def exclude_on_meta(
self, axis: int, name: str, values: Union[List[str], Set[str], Tuple[str]]
) -> Adat:
"""Returns an adat with rfu rows or columns excluded given the multiindex name and values to exclude on.
Parameters
----------
axis : int
The metadata/multiindex to operate on:
0 - row metadata,
1 - column metadata
name : str
The name of the metadata/multiindex row/column to filter based on.
values : List[str] | Set[str] | Tuple[str]
The values to filter on. Can be a tuple, list, or set.
Returns
-------
adat : Adat
Examples
--------
>>> new_adat = adat.exclude_on_meta(axis=0, name='Barcode', values=['00001'])
>>> new_adat = adat.exclude_on_meta(axis=1, name='SeqId', values=['10000-01', '12345-10'])
>>> new_adat = adat.exclude_on_meta(axis=1, name='Type', values=['Spuriomer'])
"""
return self._filter_on_meta(axis, name, values, include=False)
def pick_on_meta(
self, axis: int, name: str, values: Union[List[str], Set[str], Tuple[str]]
) -> Adat:
"""Returns an adat with rfu rows or columns excluded given the multiindex name and values to keep.
Parameters
----------
axis : int
The metadata/multiindex to operate on:
0 - row metadata,
1 - column metadata
name : str
The name of the metadata/multiindex row/column to filter based on.
values : List[str] | Set[str] | Tuple[str]
The values to filter on. Can be a tuple, list, or set.
Returns
-------
adat : Adat
Examples
--------
>>> new_adat = adat.pick_on_meta(axis=0, name='Barcode', values=['00001'])
>>> new_adat = adat.pick_on_meta(axis=1, name='SeqId', values=['10000-01', '12345-10'])
>>> new_adat = adat.pick_on_meta(axis=1, name='Type', values=['Spuriomer'])
"""
return self._filter_on_meta(axis, name, values, include=True)
def pick_meta(
self, axis: int, names: Union[List[str], Set[str], Tuple[str]]
) -> Adat:
"""Returns an adat with excluded metadata/multiindices given the names to keep.
Parameters
----------
axis : int
The metadata/multiindex to operate on:
0 - row metadata,
1 - column metadata
names : List[str] | Set[str] | Tuple[str]
The names to filter on. Can be a tuple, list, or set.
Returns
-------
adat : Adat
Examples
--------
>>> new_adat = adat.pick_meta(axis=0, names=['Barcode'])
>>> new_adat = adat.pick_meta(axis=1, names=['SeqId'])
"""
return self._filter_meta(axis, names, include=True)
def exclude_meta(
self, axis: int, names: Union[List[str], Set[str], Tuple[str]]
) -> Adat:
"""Returns an adat with excluded metadata/multiindices given the names to exclude.
Parameters
----------
axis : int
The metadata/multiindex to operate on:
0 - row metadata,
1 - column metadata
names : List[str] | Set[str] | Tuple[str]
The names to filter on. Can be a tuple, list, or set.
Returns
-------
adat : Adat
Examples
--------
>>> new_adat = adat.exclude_meta(axis=0, names=['Barcode'])
>>> new_adat = adat.exclude_meta(axis=1, names=['SeqId'])
"""
return self._filter_meta(axis, names, include=False)
def insert_meta(
self, axis: int, name: str, values: Union[List[str], Tuple[str]]
) -> Adat:
"""Returns an adat with the given metadata/multiindices added.
Metadata/multiindex name must not already exist in the adat.
Parameters
----------
axis : int
The metadata/multiindex to operate on:
0 - row metadata,
1 - column metadata
name : str
The name of the index to be added.
values : List[str] | Tuple[str]
Values to be added to the metadata/multiindex. Can be a tuple or list
Returns
-------
adat : Adat
Examples
--------
>>> new_adat = adat.insert_meta(axis=0, name='NewBarcode', values=[1, 2, 3, 4])
>>> new_adat = adat.insert_meta(axis=1, name='NewType', values=['Protein', 'Protein'])
"""
return self._insert_meta(axis, name, values, replace=False)
def replace_meta(
self, axis: int, name: str, values: Union[List[str], Tuple[str]]
) -> Adat:
"""Returns an adat with the given metadata/multiindices added.
Metadata/multiindex must already exist in the adat.
Parameters
----------
axis : int
The metadata/multiindex to operate on:
0 - row metadata,
1 - column metadata
name : str
The name of the index to be added.
values : List[str] | Tuple[str]
Values to be added to the metadata/multiindex. Can be a tuple or list
Returns
-------
adat : Adat
Examples
--------
>>> new_adat = adat.replace_meta(axis=0, name='Barcode', values=[1, 2, 3, 4])
>>> new_adat = adat.replace_meta(axis=1, name='Type', values=['Protein', 'Protein'])
"""
return self._insert_meta(axis, name, values, replace=True)
def insert_keyed_meta(
self,
axis: int,
inserted_meta_name: str,
key_meta_name: str,
values_dict: Dict[str, str],
) -> Adat:
"""Inserts metadata into Adat given a dictionary of values keyed to existing metadata.
If a key does not exist in values_dict, the function will fill in missing data with empty strings
values and create a warning to notify the user.
Parameters
----------
axis : int
The metadata/multiindex to operate on:
0 - row metadata,
1 - column metadata
inserted_meta_name : str
The name of the index to be added.
key_meta_name : str
The name of the index to use as the key-map.
values_dict : Dict[str, str]
Values to be added to the metadata/multiindex keyed to the existing values in `key_meta_name`.
Returns
-------
adat : Adat
Examples
--------
>>> new_adat = adat.insert_keyed_meta(axis=0, inserted_meta_name='NewBarcode', key_meta_name='Barcode', values_dict={"J12345": "1"})
>>> new_adat = adat.insert_keyed_meta(axis=1, inserted_meta_name='NewProteinType', key_meta_name='Type', values_dict={"Protein": "Buffer"})
"""
values = []
metadata = get_pd_axis(self, axis)
key_meta = metadata.get_level_values(key_meta_name)
if inserted_meta_name in metadata.names:
raise AdatKeyError(
'Name already exists in index, use `adat.replace_keyed_meta` instead.'
)
for key in key_meta:
if key in values_dict:
values.append(values_dict[key])
else:
values.append('')
if None in values:
warnings.warn(
'Empty string values inserted into metadata.', category=Warning
)
return self.insert_meta(axis, inserted_meta_name, values)
def replace_keyed_meta(
self,
axis: int,
replaced_meta_name: str,
values_dict: Dict[str, str],
key_meta_name: str = None,
) -> Adat:
"""Updates metadata in an Adat given a dictionary of values keyed to existing metadata.
If a key does not exist in values_dict, the function will fill in missing data with pre-existing
values and create a warning to notify the user.
Parameters
----------
axis : int
The metadata/multiindex to operate on:
0 - row metadata,
1 - column metadata
replaced_meta_name : str
The name of the index to be added.
key_meta_name : str, optional
The name of the index to use as the key-map. Will default to `replaced_meta_name` if None.
values_dict : Dict[str, str]
Values to be added to the metadata/multiindex keyed to the existing values in `key_meta_name`.
Returns
-------
adat : Adat
Examples
--------
>>> new_adat = adat.replace_keyed_meta(axis=0, replaced_meta_name='Barcode', key_meta_name='SampleType', values_dict={"J12345": "Calibrator"})
>>> new_adat = adat.replace_keyed_meta(axis=1, replaced_meta_name='Type', key_meta_name='SeqId', values_dict={"12345-6": "ProteinSet1"})
"""
key_meta_name = key_meta_name or replaced_meta_name
values = []
metadata = get_pd_axis(self, axis)
key_meta = metadata.get_level_values(key_meta_name)
values_to_update = metadata.get_level_values(replaced_meta_name)
if replaced_meta_name not in metadata.names:
raise AdatKeyError(
'Name does not exists in index, use `adat.insert_keyed_meta` instead.'
)
warning_str = 'Some keys not provided, using original values for those keys'
warnings.filterwarnings('once', message=warning_str)
for key, value in zip(key_meta, values_to_update):
if key in values_dict:
values.append(values_dict[key])
else:
warnings.warn(warning_str)
values.append(value)
return self.replace_meta(axis, replaced_meta_name, values)
def update_somamer_metadata_from_adat(self, adat: Adat) -> Adat:
"""Given an Adat with different SOMAmer reagent metadata, returns this adat with that somamer metadata.
An adat method that updates adats with disparate somamer metadata by unifying their somamer column
metadata. Useful for concatenating since the concatenator requires select column metadata fields to match.
This is required for concatenation if there has been a change in protein effective date across adats.
Parameters
----------
adat : Adat
An Adat object with the metadata you want to use
Returns
-------
modified_adat : Adat
This Adat whose somamer column metadata has been modified to match the provided adat's.
Examples
--------
>>> new_adat = adat.update_somamer_metadata_from_adat(other_adat)
"""
# Check to make sure seq_ids & order are identical
if list(adat.columns.get_level_values('SeqId')) != list(
self.columns.get_level_values('SeqId')
):
raise AdatMetaError(
'SeqIds do not match the provided adat. Unable to perform metadata substitution'
)
columns_to_overwrite = [
'SeqIdVersion',
'SomaId',
'TargetFullName',
'Target',
'UniProt',
'EntrezGeneID',
'EntrezGeneSymbol',
'Organism',
'Units',
'Type',
'Dilution',
]
new_meta_adat = self.copy()
# Modify adat for each name in columns_to_overwrite
for column_name in columns_to_overwrite:
# Check to see if the column exists. If it doesn't, throw a warning & move on to the next one
if column_name not in new_meta_adat.columns.names:
logger.warning(
f'Standard column, {column_name}, not found in column metadata. Continuing to next.'
)
continue
# If it does exist in the source adat but not in the provided adat, we have problems!
elif column_name not in adat.columns.names:
AdatMetaError(
f'Standard column, {column_name}, not found in provided column metadata but exists in source adat.'
)
# Replace metadata
new_meta_adat = new_meta_adat.replace_meta(
axis=1,
name=column_name,
values=adat.columns.get_level_values(column_name),
)
return new_meta_adat
def reorder_on_metadata(self, axis: int, name: str, source_adat: Adat) -> Adat:
"""Given an Adat with matching metadata in a different order, returns this adat reorganized to match that order.
An adat method that updates adats with mis-aligned metadata by unifying the order of the columns or rows by the metadata.
Parameters
----------
axis : int
The metadata/multiindex to operate on:
0 - row metadata,
1 - column metadata
name : str
The name of the index to be added.
source_adat : Adat
An Adat object with the metadata order you want
Returns
-------
modified_adat : Adat
This Adat whose rows or columns has been reordered to match the provided adat's.
Examples
--------
>>> new_adat = adat.reorder_on_metadata(axis=1, name='SeqId', source_adat=other_adat)
"""
reorder_index = []
adat = self.copy()
if axis == 0:
metadata_order = list(source_adat.index.get_level_values(name))
for metadata in adat.index.get_level_values(name):
try:
reorder_index.append(metadata_order.index(metadata))
except ValueError:
raise AdatMetaError(
f'Source metadata, {metadata}, not found in adat index, {name}'
)
adat = adat.iloc[reorder_index]
elif axis == 1:
metadata_order = list(source_adat.columns.get_level_values(name))
for metadata in adat.columns.get_level_values(name):
try:
reorder_index.append(metadata_order.index(metadata))
except ValueError:
raise AdatMetaError(
f'Source metadata, {metadata}, not found in adat column, {name}'
)
adat = adat.iloc[:, reorder_index]
return adat