-
Notifications
You must be signed in to change notification settings - Fork 68
/
table.py
2043 lines (1636 loc) · 83.1 KB
/
table.py
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
******
Tables
******
Synapse Tables enable storage of tabular data in Synapse in a form that can be queried using a SQL-like query language.
A table has a :py:class:`Schema` and holds a set of rows conforming to that schema.
A :py:class:`Schema` defines a series of :py:class:`Column` of the following types: STRING, DOUBLE, INTEGER, BOOLEAN,
DATE, ENTITYID, FILEHANDLEID, LINK, LARGETEXT, USERID
~~~~~~~
Example
~~~~~~~
Preliminaries::
import synapseclient
from synapseclient import Project, File, Folder
from synapseclient import Schema, Column, Table, Row, RowSet, as_table_columns
syn = synapseclient.Synapse()
syn.login()
project = syn.get('syn123')
First, let's load some data. Let's say we had a file, genes.csv::
Name,Chromosome,Start,End,Strand,TranscriptionFactor
foo,1,12345,12600,+,False
arg,2,20001,20200,+,False
zap,2,30033,30999,-,False
bah,1,40444,41444,-,False
bnk,1,51234,54567,+,True
xyz,1,61234,68686,+,False
To create a Table::
table = build_table('My Favorite Genes', project, "/path/to/genes.csv")
syn.store(table)
:py:func:`build_table` will set the Table :py:class:`Schema` which defines the columns of the table.
To create a table with a custom :py:class:`Schema`, first create the :py:class:`Schema`::
cols = [
Column(name='Name', columnType='STRING', maximumSize=20),
Column(name='Chromosome', columnType='STRING', maximumSize=20),
Column(name='Start', columnType='INTEGER'),
Column(name='End', columnType='INTEGER'),
Column(name='Strand', columnType='STRING', enumValues=['+', '-'], maximumSize=1),
Column(name='TranscriptionFactor', columnType='BOOLEAN')]
schema = Schema(name='My Favorite Genes', columns=cols, parent=project)
Let's store that in Synapse::
table = Table(schema, "/path/to/genes.csv")
table = syn.store(table)
The :py:func:`Table` function takes two arguments, a schema object and data in some form, which can be:
* a path to a CSV file
* a `Pandas <http://pandas.pydata.org/>`_ \
`DataFrame <http://pandas.pydata.org/pandas-docs/stable/api.html#dataframe>`_
* a :py:class:`RowSet` object
* a list of lists where each of the inner lists is a row
With a bit of luck, we now have a table populated with data. Let's try to query::
results = syn.tableQuery("select * from %s where Chromosome='1' and Start < 41000 and End > 20000"
% table.schema.id)
for row in results:
print(row)
------
Pandas
------
`Pandas <http://pandas.pydata.org/>`_ is a popular library for working with tabular data. If you have Pandas installed,
the goal is that Synapse Tables will play nice with it.
Create a Synapse Table from a `DataFrame <http://pandas.pydata.org/pandas-docs/stable/api.html#dataframe>`_::
import pandas as pd
df = pd.read_csv("/path/to/genes.csv", index_col=False)
table = build_table('My Favorite Genes', project, df)
table = syn.store(table)
:py:func:`build_table` uses pandas DataFrame dtype to set the Table :py:class:`Schema`.
To create a table with a custom :py:class:`Schema`, first create the :py:class:`Schema`::
schema = Schema(name='My Favorite Genes', columns=as_table_columns(df), parent=project)
table = syn.store(Table(schema, df))
Get query results as a `DataFrame <http://pandas.pydata.org/pandas-docs/stable/api.html#dataframe>`_::
results = syn.tableQuery("select * from %s where Chromosome='2'" % table.schema.id)
df = results.asDataFrame()
--------------
Changing Data
--------------
Once the schema is settled, changes come in two flavors: appending new rows and updating existing ones.
**Appending** new rows is fairly straightforward. To continue the previous example, we might add some new genes from
another file::
table = syn.store(Table(table.schema.id, "/path/to/more_genes.csv"))
To quickly add a few rows, use a list of row data::
new_rows = [["Qux1", "4", 201001, 202001, "+", False],
["Qux2", "4", 203001, 204001, "+", False]]
table = syn.store(Table(schema, new_rows))
**Updating** rows requires an etag, which identifies the most recent change set plus row IDs and version numbers for
each row to be modified. We get those by querying before updating. Minimizing changesets to contain only rows that
actually change will make processing faster.
For example, let's update the names of some of our favorite genes::
results = syn.tableQuery("select * from %s where Chromosome='1'" % table.schema.id)
df = results.asDataFrame()
df['Name'] = ['rzing', 'zing1', 'zing2', 'zing3']
Note that we're propagating the etag from the query results. Without it, we'd get an error saying something about an
"Invalid etag"::
table = syn.store(Table(schema, df, etag=results.etag))
The etag is used by the server to prevent concurrent users from making conflicting changes, a technique called
optimistic concurrency. In case of a conflict, your update may be rejected. You then have to do another query and
try your update again.
------------------------
Changing Table Structure
------------------------
Adding columns can be done using the methods :py:meth:`Schema.addColumn` or :py:meth:`addColumns` on the
:py:class:`Schema` object::
schema = syn.get("syn000000")
bday_column = syn.store(Column(name='birthday', columnType='DATE'))
schema.addColumn(bday_column)
schema = syn.store(schema)
Renaming or otherwise modifying a column involves removing the column and adding a new column::
cols = syn.getTableColumns(schema)
for col in cols:
if col.name == "birthday":
schema.removeColumn(col)
bday_column2 = syn.store(Column(name='birthday2', columnType='DATE'))
schema.addColumn(bday_column2)
schema = syn.store(schema)
--------------------
Table attached files
--------------------
Synapse tables support a special column type called 'File' which contain a file handle, an identifier of a file stored
in Synapse. Here's an example of how to upload files into Synapse, associate them with a table and read them back
later::
# your synapse project
project = syn.get(...)
covers_dir = '/path/to/album/covers/'
# store the table's schema
cols = [
Column(name='artist', columnType='STRING', maximumSize=50),
Column(name='album', columnType='STRING', maximumSize=50),
Column(name='year', columnType='INTEGER'),
Column(name='catalog', columnType='STRING', maximumSize=50),
Column(name='cover', columnType='FILEHANDLEID')]
schema = syn.store(Schema(name='Jazz Albums', columns=cols, parent=project))
# the actual data
data = [["John Coltrane", "Blue Train", 1957, "BLP 1577", "coltraneBlueTrain.jpg"],
["Sonny Rollins", "Vol. 2", 1957, "BLP 1558", "rollinsBN1558.jpg"],
["Sonny Rollins", "Newk's Time", 1958, "BLP 4001", "rollinsBN4001.jpg"],
["Kenny Burrel", "Kenny Burrel", 1956, "BLP 1543", "burrellWarholBN1543.jpg"]]
# upload album covers
for row in data:
file_handle = syn.uploadSynapseManagedFileHandle(os.path.join(covers_dir, row[4]))
row[4] = file_handle['id']
# store the table data
row_reference_set = syn.store(RowSet(columns=cols, schema=schema, rows=[Row(r) for r in data]))
# Later, we'll want to query the table and download our album covers
results = syn.tableQuery("select artist, album, year, catalog, cover from %s where artist = 'Sonny Rollins'" \
% schema.id)
cover_files = syn.downloadTableColumns(results, ['cover'])
-------------
Deleting rows
-------------
Query for the rows you want to delete and call syn.delete on the results::
results = syn.tableQuery("select * from %s where Chromosome='2'" % table.schema.id)
a = syn.delete(results)
------------------------
Deleting the whole table
------------------------
Deleting the schema deletes the whole table and all rows::
syn.delete(schema)
~~~~~~~
Queries
~~~~~~~
The query language is quite similar to SQL select statements, except that joins are not supported. The documentation
for the Synapse API has lots of `query examples \
<http://docs.synapse.org/rest/org/sagebionetworks/repo/web/controller/TableExamples.html>`_.
~~~~~~
Schema
~~~~~~
.. autoclass:: synapseclient.table.Schema
:members:
:noindex:
.. autoclass:: synapseclient.table.EntityViewSchema
:members:
:noindex:
~~~~~~
Column
~~~~~~
.. autoclass:: synapseclient.table.Column
:members: __init__
~~~~~~
Row
~~~~~~
.. autoclass:: synapseclient.table.Row
:members: __init__
~~~~~~
RowSet
~~~~~~
.. autoclass:: synapseclient.table.RowSet
:members: __init__
~~~~~~
Table
~~~~~~
.. autoclass:: synapseclient.table.TableAbstractBaseClass
:members:
.. autoclass:: synapseclient.table.RowSetTable
:members:
.. autoclass:: synapseclient.table.TableQueryResult
:members:
.. autoclass:: synapseclient.table.CsvFileTable
:members:
~~~~~~~~~~~~~~~~~~~~
Module level methods
~~~~~~~~~~~~~~~~~~~~
.. autofunction:: as_table_columns
.. autofunction:: build_table
.. autofunction:: Table
See also:
- :py:meth:`synapseclient.Synapse.getColumns`
- :py:meth:`synapseclient.Synapse.getTableColumns`
- :py:meth:`synapseclient.Synapse.tableQuery`
- :py:meth:`synapseclient.Synapse.get`
- :py:meth:`synapseclient.Synapse.store`
- :py:meth:`synapseclient.Synapse.delete`
"""
import collections.abc
import csv
import io
import os
import re
import sys
import tempfile
import copy
import itertools
import collections
import abc
import enum
import json
from builtins import zip
from synapseclient.core.utils import id_of, from_unix_epoch_time
from synapseclient.core.exceptions import SynapseError
from synapseclient.core.models.dict_object import DictObject
from .entity import Entity, entity_type_to_class
from synapseclient.core.constants import concrete_types
aggregate_pattern = re.compile(r'(count|max|min|avg|sum)\((.+)\)')
DTYPE_2_TABLETYPE = {'?': 'BOOLEAN',
'd': 'DOUBLE', 'g': 'DOUBLE', 'e': 'DOUBLE', 'f': 'DOUBLE',
'b': 'INTEGER', 'B': 'INTEGER', 'h': 'INTEGER', 'H': 'INTEGER',
'i': 'INTEGER', 'I': 'INTEGER', 'l': 'INTEGER', 'L': 'INTEGER',
'm': 'INTEGER', 'q': 'INTEGER', 'Q': 'INTEGER',
'S': 'STRING', 'U': 'STRING', 'O': 'STRING',
'a': 'STRING', 'p': 'INTEGER', 'M': 'DATE'}
MAX_NUM_TABLE_COLUMNS = 152
DEFAULT_QUOTE_CHARACTER = '"'
DEFAULT_SEPARATOR = ","
DEFAULT_ESCAPSE_CHAR = "\\"
# This Enum is used to help users determine which Entity types they want in their view
# Each item will be used to construct the viewTypeMask
class EntityViewType(enum.Enum):
FILE = 0x01
PROJECT = 0x02
TABLE = 0x04
FOLDER = 0x08
VIEW = 0x10
DOCKER = 0x20
def _get_view_type_mask(types_to_include):
if not types_to_include:
raise ValueError("Please include at least one of the entity types specified in EntityViewType.")
mask = 0x00
for input in types_to_include:
if not isinstance(input, EntityViewType):
raise ValueError("Please use EntityViewType to specify the type you want to include in a View.")
mask = mask | input.value
return mask
def _get_view_type_mask_for_deprecated_type(type):
if not type:
raise ValueError("Please specify the deprecated type to convert to viewTypeMask")
if type == 'file':
return EntityViewType.FILE.value
if type == 'project':
return EntityViewType.PROJECT.value
if type == 'file_and_table':
return EntityViewType.FILE.value | EntityViewType.TABLE.value
raise ValueError("The provided value is not a valid type: %s", type)
def test_import_pandas():
try:
import pandas as pd # noqa F401
# used to catch ImportError, but other errors can happen (see SYNPY-177)
except: # noqa
sys.stderr.write("""\n\nPandas not installed!\n
The synapseclient package recommends but doesn't require the
installation of Pandas. If you'd like to use Pandas DataFrames,
refer to the installation instructions at:
http://pandas.pydata.org/.
\n\n\n""")
raise
def as_table_columns(values):
"""
Return a list of Synapse table :py:class:`Column` objects that correspond to the columns in the given values.
:params values: an object that holds the content of the tables
- a string holding the path to a CSV file, a filehandle, or StringIO containing valid csv content
- a Pandas `DataFrame <http://pandas.pydata.org/pandas-docs/stable/api.html#dataframe>`_
:returns: A list of Synapse table :py:class:`Column` objects
Example::
import pandas as pd
df = pd.DataFrame(dict(a=[1, 2, 3], b=["c", "d", "e"]))
cols = as_table_columns(df)
"""
test_import_pandas()
import pandas as pd
df = None
# filename of a csv file
# in Python 3, we can check that the values is instanceof io.IOBase
# for now, check if values has attr `read`
if isinstance(values, str) or hasattr(values, "read"):
df = _csv_to_pandas_df(values)
# pandas DataFrame
if isinstance(values, pd.DataFrame):
df = values
if df is None:
raise ValueError("Values of type %s is not yet supported." % type(values))
cols = list()
for col in df:
columnType = DTYPE_2_TABLETYPE[df[col].dtype.char]
if columnType == 'STRING':
maxStrLen = df[col].str.len().max()
if maxStrLen > 1000:
cols.append(Column(name=col, columnType='LARGETEXT', defaultValue=''))
else:
size = int(round(min(1000, max(30, maxStrLen*1.5)))) # Determine the length of the longest string
cols.append(Column(name=col, columnType=columnType, maximumSize=size, defaultValue=''))
else:
cols.append(Column(name=col, columnType=columnType))
return cols
def df2Table(df, syn, tableName, parentProject):
"""Creates a new table from data in pandas data frame.
parameters: df, tableName, parentProject
"""
# Create columns:
cols = as_table_columns(df)
cols = [syn.store(col) for col in cols]
# Create Table Schema
schema1 = Schema(name=tableName, columns=cols, parent=parentProject)
schema1 = syn.store(schema1)
# Add data to Table
for i in range(0, df.shape[0]/1200+1):
start = i*1200
end = min((i+1)*1200, df.shape[0])
rowset1 = RowSet(columns=cols, schema=schema1,
rows=[Row(list(df.ix[j, :])) for j in range(start, end)])
syn.store(rowset1)
return schema1
def to_boolean(value):
"""
Convert a string to boolean, case insensitively,
where true values are: true, t, and 1 and false values are: false, f, 0.
Raise a ValueError for all other values.
"""
if isinstance(value, bool):
return value
if isinstance(value, str):
lower_value = value.lower()
if lower_value in ['true', 't', '1']:
return True
if lower_value in ['false', 'f', '0']:
return False
raise ValueError("Can't convert %s to boolean." % value)
def column_ids(columns):
if columns is None:
return []
return [col.id for col in columns if 'id' in col]
def row_labels_from_id_and_version(rows):
return ["_".join(map(str, row)) for row in rows]
def row_labels_from_rows(rows):
return row_labels_from_id_and_version([(row['rowId'], row['versionNumber'], row['etag'])
if 'etag' in row else (row['rowId'], row['versionNumber'])
for row in rows])
def cast_values(values, headers):
"""
Convert a row of table query results from strings to the correct column type.
See: http://docs.synapse.org/rest/org/sagebionetworks/repo/model/table/ColumnType.html
"""
if len(values) != len(headers):
raise ValueError('The number of columns in the csv file does not match the given headers. %d fields, %d headers'
% (len(values), len(headers)))
result = []
for header, field in zip(headers, values):
columnType = header.get('columnType', 'STRING')
# convert field to column type
if field is None or field == '':
result.append(None)
elif columnType in {'STRING', 'ENTITYID', 'FILEHANDLEID', 'LARGETEXT', 'USERID', 'LINK'}:
result.append(field)
elif columnType == 'DOUBLE':
result.append(float(field))
elif columnType == 'INTEGER':
result.append(int(field))
elif columnType == 'BOOLEAN':
result.append(to_boolean(field))
elif columnType == 'DATE':
result.append(from_unix_epoch_time(field))
elif columnType in {'STRING_LIST', 'INTEGER_LIST', 'BOOLEAN_LIST'}:
result.append(json.loads(field))
elif columnType == 'DATE_LIST':
result.append(json.loads(field, parse_int=from_unix_epoch_time))
else:
# default to string for unknown column type
result.append(field)
return result
def cast_row(row, headers):
row['values'] = cast_values(row['values'], headers)
return row
def cast_row_set(rowset):
for i, row in enumerate(rowset['rows']):
rowset['rows'][i]['values'] = cast_row(row, rowset['headers'])
return rowset
def escape_column_name(column):
"""Escape the name of the given column for use in a Synapse table query statement
:param column: a string or column dictionary object with a 'name' key"""
col_name = column['name'] if isinstance(column, collections.abc.Mapping) else str(column)
escaped_name = col_name.replace('"', '""')
return f'"{escaped_name}"'
def join_column_names(columns):
"""Join the names of the given columns into a comma delimited list suitable for use in a Synapse table query
:param columns: a sequence of column string names or dictionary objets with column 'name' keys"""
return ",".join(escape_column_name(c) for c in columns)
def _csv_to_pandas_df(filepath,
separator=DEFAULT_SEPARATOR,
quote_char=DEFAULT_QUOTE_CHARACTER,
escape_char=DEFAULT_ESCAPSE_CHAR,
contain_headers=True,
lines_to_skip=0,
date_columns=None,
list_columns=None,
rowIdAndVersionInIndex=True):
test_import_pandas()
import pandas as pd
# DATEs are stored in csv as unix timestamp in milliseconds
def datetime_millisecond_parser(milliseconds): return pd.to_datetime(milliseconds, unit='ms', utc=True)
if not date_columns:
date_columns = []
line_terminator = str(os.linesep)
# assign line terminator only if for single character
# line terminators (e.g. not '\r\n') 'cause pandas doesn't
# longer line terminators. See:
# https://github.com/pydata/pandas/issues/3501
# "ValueError: Only length-1 line terminators supported"
df = pd.read_csv(filepath,
sep=separator,
lineterminator=line_terminator if len(line_terminator) == 1 else None,
quotechar=quote_char,
escapechar=escape_char,
header=0 if contain_headers else None,
skiprows=lines_to_skip,
parse_dates=date_columns,
date_parser=datetime_millisecond_parser)
# Turn list columns into lists
if list_columns:
for col in list_columns:
# Fill NA values with empty lists, it must be a string for json.loads to work
df[col].fillna('[]', inplace=True)
df[col] = df[col].apply(json.loads)
if rowIdAndVersionInIndex and "ROW_ID" in df.columns and "ROW_VERSION" in df.columns:
# combine row-ids (in index) and row-versions (in column 0) to
# make new row labels consisting of the row id and version
# separated by a dash.
zip_args = [df["ROW_ID"], df["ROW_VERSION"]]
if "ROW_ETAG" in df.columns:
zip_args.append(df['ROW_ETAG'])
df.index = row_labels_from_id_and_version(zip(*zip_args))
del df["ROW_ID"]
del df["ROW_VERSION"]
if "ROW_ETAG" in df.columns:
del df['ROW_ETAG']
return df
def _create_row_delete_csv(row_id_vers_iterable):
"""
creates a temporary csv used for deleting rows
:param row_id_vers_iterable: an iterable containing tuples with format: (row_id, row_version)
:return: filepath of created csv file
"""
with tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as temp_csv:
csv_writer = csv.writer(temp_csv)
csv_writer.writerow(("ROW_ID", "ROW_VERSION"))
csv_writer.writerows(row_id_vers_iterable)
return temp_csv.name
def _delete_rows(syn, schema, row_id_vers_list):
"""
Deletes rows from a synapse table
:param syn: an instance of py:class:`synapseclient.client.Synapse`
:param row_id_vers_list: an iterable containing tuples with format: (row_id, row_version)
"""
delete_row_csv_filepath = _create_row_delete_csv(row_id_vers_list)
try:
syn._uploadCsv(delete_row_csv_filepath, schema)
finally:
os.remove(delete_row_csv_filepath)
class SchemaBase(Entity, metaclass=abc.ABCMeta):
"""
This is the an Abstract Class for EntityViewSchema and Schema containing the common methods for both.
You can not create an object of this type.
"""
_property_keys = Entity._property_keys + ['columnIds']
_local_keys = Entity._local_keys + ['columns_to_store']
@property
@abc.abstractmethod # forces subclasses to define _synapse_entity_type
def _synapse_entity_type(self):
pass
@abc.abstractmethod
def __init__(self, name, columns, properties, annotations, local_state, parent, **kwargs):
self.properties.setdefault('columnIds', [])
self.__dict__.setdefault('columns_to_store', [])
if name:
kwargs['name'] = name
super(SchemaBase, self).__init__(properties=properties, annotations=annotations, local_state=local_state,
parent=parent, **kwargs)
if columns:
self.addColumns(columns)
def addColumn(self, column):
"""
:param column: a column object or its ID
"""
if isinstance(column, str) or isinstance(column, int) or hasattr(column, 'id'):
self.properties.columnIds.append(id_of(column))
elif isinstance(column, Column):
if not self.__dict__.get('columns_to_store', None):
self.__dict__['columns_to_store'] = []
self.__dict__['columns_to_store'].append(column)
else:
raise ValueError("Not a column? %s" % str(column))
def addColumns(self, columns):
"""
:param columns: a list of column objects or their ID
"""
for column in columns:
self.addColumn(column)
def removeColumn(self, column):
"""
:param column: a column object or its ID
"""
if isinstance(column, str) or isinstance(column, int) or hasattr(column, 'id'):
self.properties.columnIds.remove(id_of(column))
elif isinstance(column, Column) and self.columns_to_store:
self.columns_to_store.remove(column)
else:
ValueError("Can't remove column %s" + str(column))
def has_columns(self):
"""Does this schema have columns specified?"""
return bool(self.properties.get('columnIds', None) or self.__dict__.get('columns_to_store', None))
def _before_synapse_store(self, syn):
if len(self.columns_to_store) + len(self.columnIds) > MAX_NUM_TABLE_COLUMNS:
raise ValueError("Too many columns. The limit is %s columns per table" % MAX_NUM_TABLE_COLUMNS)
# store any columns before storing table
if self.columns_to_store:
self.properties.columnIds.extend(column.id for column in syn.createColumns(self.columns_to_store))
self.columns_to_store = []
class Schema(SchemaBase):
"""
A Schema is an :py:class:`synapseclient.entity.Entity` that defines a set of columns in a table.
:param name: the name for the Table Schema object
:param description: User readable description of the schema
:param columns: a list of :py:class:`Column` objects or their IDs
:param parent: the project in Synapse to which this table belongs
:param properties: A map of Synapse properties
:param annotations: A map of user defined annotations
:param local_state: Internal use only
Example::
cols = [Column(name='Isotope', columnType='STRING'),
Column(name='Atomic Mass', columnType='INTEGER'),
Column(name='Halflife', columnType='DOUBLE'),
Column(name='Discovered', columnType='DATE')]
schema = syn.store(Schema(name='MyTable', columns=cols, parent=project))
"""
_synapse_entity_type = 'org.sagebionetworks.repo.model.table.TableEntity'
def __init__(self, name=None, columns=None, parent=None, properties=None, annotations=None, local_state=None,
**kwargs):
super(Schema, self).__init__(name=name, columns=columns, properties=properties,
annotations=annotations, local_state=local_state, parent=parent, **kwargs)
class ViewBase(SchemaBase):
"""
This is a helper class for EntityViewSchema and SubmissionViewSchema
containing the common methods for both.
"""
_synapse_entity_type = ""
_property_keys = SchemaBase._property_keys + ['viewTypeMask', 'scopeIds']
_local_keys = SchemaBase._local_keys + ['addDefaultViewColumns', 'addAnnotationColumns',
'ignoredAnnotationColumnNames']
def add_scope(self, entities):
"""
:param entities: a Project, Folder, Evaluation object or its ID, can also be a list of them
"""
if isinstance(entities, list):
# add ids to a temp list so that we don't partially modify scopeIds on an exception in id_of()
temp_list = [id_of(entity) for entity in entities]
self.scopeIds.extend(temp_list)
else:
self.scopeIds.append(id_of(entities))
def _filter_duplicate_columns(self, syn, columns_to_add):
"""
If a column to be added has the same name and same type as an existing column, it will be considered a duplicate
and not added.
:param syn: a :py:class:`synapseclient.client.Synapse` object that is logged in
:param columns_to_add: iterable collection of type :py:class:`synapseclient.table.Column` objects
:return: a filtered list of columns to add
"""
# no point in making HTTP calls to retrieve existing Columns if we not adding any new columns
if not columns_to_add:
return columns_to_add
# set up Column name/type tracking
# map of str -> set(str), where str is the column type as a string and set is a set of column name strings
column_type_to_annotation_names = {}
# add to existing columns the columns that user has added but not yet created in synapse
column_generator = itertools.chain(syn.getColumns(self.columnIds),
self.columns_to_store) if self.columns_to_store \
else syn.getColumns(self.columnIds)
for column in column_generator:
column_name = column['name']
column_type = column['columnType']
column_type_to_annotation_names.setdefault(column_type, set()).add(column_name)
valid_columns = []
for column in columns_to_add:
new_col_name = column['name']
new_col_type = column['columnType']
typed_col_name_set = column_type_to_annotation_names.setdefault(new_col_type, set())
if new_col_name not in typed_col_name_set:
typed_col_name_set.add(new_col_name)
valid_columns.append(column)
return valid_columns
def _before_synapse_store(self, syn):
# get the default EntityView columns from Synapse and add them to the columns list
additional_columns = []
view_type = self._synapse_entity_type.split(".")[-1].lower()
mask = self.get("viewTypeMask")
if self.addDefaultViewColumns:
additional_columns.extend(
syn._get_default_view_columns(view_type, view_type_mask=mask)
)
# get default annotations
if self.addAnnotationColumns:
anno_columns = [x for x in syn._get_annotation_view_columns(self.scopeIds, view_type,
view_type_mask=mask)
if x['name'] not in self.ignoredAnnotationColumnNames]
additional_columns.extend(anno_columns)
self.addColumns(self._filter_duplicate_columns(syn, additional_columns))
# set these boolean flags to false so they are not repeated.
self.addDefaultViewColumns = False
self.addAnnotationColumns = False
super(ViewBase, self)._before_synapse_store(syn)
class EntityViewSchema(ViewBase):
"""
A EntityViewSchema is a :py:class:`synapseclient.entity.Entity` that displays all files/projects
(depending on user choice) within a given set of scopes
:param name: the name of the Entity View Table object
:param columns: a list of :py:class:`Column` objects or their IDs. These are optional.
:param parent: the project in Synapse to which this table belongs
:param scopes: a list of Projects/Folders or their ids
:param type: This field is deprecated. Please use `includeEntityTypes`
:param includeEntityTypes: a list of entity types to include in the view. Supported entity types are:
EntityViewType.FILE,
EntityViewType.PROJECT,
EntityViewType.TABLE,
EntityViewType.FOLDER,
EntityViewType.VIEW,
EntityViewType.DOCKER
If none is provided, the view will default to include EntityViewType.FILE.
:param addDefaultViewColumns: If true, adds all default columns (e.g. name, createdOn, modifiedBy etc.)
Defaults to True.
The default columns will be added after a call to
:py:meth:`synapseclient.Synapse.store`.
:param addAnnotationColumns: If true, adds columns for all annotation keys defined across all Entities in
the EntityViewSchema's scope. Defaults to True.
The annotation columns will be added after a call to
:py:meth:`synapseclient.Synapse.store`.
:param ignoredAnnotationColumnNames: A list of strings representing annotation names.
When addAnnotationColumns is True, the names in this list will not be
automatically added as columns to the EntityViewSchema if they exist in any
of the defined scopes.
:param properties: A map of Synapse properties
:param annotations: A map of user defined annotations
:param local_state: Internal use only
Example::
from synapseclient import EntityViewType
project_or_folder = syn.get("syn123")
schema = syn.store(EntityViewSchema(name='MyTable', parent=project, scopes=[project_or_folder_id, 'syn123'],
includeEntityTypes=[EntityViewType.FILE]))
"""
_synapse_entity_type = 'org.sagebionetworks.repo.model.table.EntityView'
def __init__(self, name=None, columns=None, parent=None, scopes=None, type=None, includeEntityTypes=None,
addDefaultViewColumns=True, addAnnotationColumns=True, ignoredAnnotationColumnNames=[],
properties=None, annotations=None, local_state=None, **kwargs):
if includeEntityTypes:
kwargs['viewTypeMask'] = _get_view_type_mask(includeEntityTypes)
elif type:
kwargs['viewTypeMask'] = _get_view_type_mask_for_deprecated_type(type)
elif properties and 'type' in properties:
kwargs['viewTypeMask'] = _get_view_type_mask_for_deprecated_type(properties['type'])
properties['type'] = None
self.ignoredAnnotationColumnNames = set(ignoredAnnotationColumnNames)
super(EntityViewSchema, self).__init__(name=name, columns=columns, properties=properties,
annotations=annotations, local_state=local_state, parent=parent,
**kwargs)
# This is a hacky solution to make sure we don't try to add columns to schemas that we retrieve from synapse
is_from_normal_constructor = not (properties or local_state)
# allowing annotations because user might want to update annotations all at once
self.addDefaultViewColumns = addDefaultViewColumns and is_from_normal_constructor
self.addAnnotationColumns = addAnnotationColumns and is_from_normal_constructor
# set default values after constructor so we don't overwrite the values defined in properties using .get()
# because properties, unlike local_state, do not have nonexistent keys assigned with a value of None
if self.get('viewTypeMask') is None:
self.viewTypeMask = EntityViewType.FILE.value
if self.get('scopeIds') is None:
self.scopeIds = []
# add the scopes last so that we can append the passed in scopes to those defined in properties
if scopes is not None:
self.add_scope(scopes)
def set_entity_types(self, includeEntityTypes):
"""
:param includeEntityTypes: a list of entity types to include in the view. This list will replace the previous
settings. Supported entity types are:
EntityViewType.FILE,
EntityViewType.PROJECT,
EntityViewType.TABLE,
EntityViewType.FOLDER,
EntityViewType.VIEW,
EntityViewType.DOCKER
"""
self.viewTypeMask = _get_view_type_mask(includeEntityTypes)
class SubmissionViewSchema(ViewBase):
"""
A SubmissionViewSchema is a :py:class:`synapseclient.entity.Entity` that displays all files/projects
(depending on user choice) within a given set of scopes
:param name: the name of the Entity View Table object
:param columns: a list of :py:class:`Column` objects or their IDs. These are optional.
:param parent: the project in Synapse to which this table belongs
:param scopes: a list of Evaluation Queues or their ids
:param addDefaultViewColumns: If true, adds all default columns (e.g. name, createdOn, modifiedBy etc.)
Defaults to True.
The default columns will be added after a call to
:py:meth:`synapseclient.Synapse.store`.
:param addAnnotationColumns: If true, adds columns for all annotation keys defined across all Entities in
the SubmissionViewSchema's scope. Defaults to True.
The annotation columns will be added after a call to
:py:meth:`synapseclient.Synapse.store`.
:param ignoredAnnotationColumnNames: A list of strings representing annotation names.
When addAnnotationColumns is True, the names in this list will not be
automatically added as columns to the SubmissionViewSchema if they exist in
any of the defined scopes.
:param properties: A map of Synapse properties
:param annotations: A map of user defined annotations
:param local_state: Internal use only
Example::
from synapseclient import SubmissionViewSchema
project = syn.get("syn123")
schema = syn.store(SubmissionViewSchema(name='My Submission View', parent=project, scopes=['9614543']))
"""
_synapse_entity_type = 'org.sagebionetworks.repo.model.table.SubmissionView'
def __init__(self, name=None, columns=None, parent=None, scopes=None,
addDefaultViewColumns=True, addAnnotationColumns=True,
ignoredAnnotationColumnNames=[],
properties=None, annotations=None, local_state=None, **kwargs):
self.ignoredAnnotationColumnNames = set(ignoredAnnotationColumnNames)
super(SubmissionViewSchema, self).__init__(
name=name, columns=columns, properties=properties,
annotations=annotations, local_state=local_state, parent=parent,
**kwargs
)
# This is a hacky solution to make sure we don't try to add columns to schemas that we retrieve from synapse
is_from_normal_constructor = not (properties or local_state)
# allowing annotations because user might want to update annotations all at once
self.addDefaultViewColumns = addDefaultViewColumns and is_from_normal_constructor
self.addAnnotationColumns = addAnnotationColumns and is_from_normal_constructor
if self.get('scopeIds') is None:
self.scopeIds = []
# add the scopes last so that we can append the passed in scopes to those defined in properties
if scopes is not None:
self.add_scope(scopes)
# add Schema to the map of synapse entity types to their Python representations
entity_type_to_class[Schema._synapse_entity_type] = Schema
entity_type_to_class[EntityViewSchema._synapse_entity_type] = EntityViewSchema
entity_type_to_class[SubmissionViewSchema._synapse_entity_type] = SubmissionViewSchema
class SelectColumn(DictObject):
"""
Defines a column to be used in a table :py:class:`synapseclient.table.Schema`.
:var id: An immutable ID issued by the platform
:param columnType: Can be any of: "STRING", "DOUBLE", "INTEGER", "BOOLEAN", "DATE", "FILEHANDLEID", "ENTITYID"
:param name: The display name of the column
:type id: string
:type columnType: string
:type name: string
"""
def __init__(self, id=None, columnType=None, name=None, **kwargs):
super(SelectColumn, self).__init__()
if id:
self.id = id
if name:
self.name = name
if columnType:
self.columnType = columnType
# Notes that this param is only used to support forward compatibility.
self.update(kwargs)