/
seerpy.py
1928 lines (1678 loc) · 73.5 KB
/
seerpy.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
"""
Define a client class for interacting with the GraphQL API endpoint.
Copyright 2017 Seer Medical Pty Ltd, Inc. or its affiliates. All Rights Reserved.
Concepts
--------
- study: A defined period of time monitoring a patient, typically with EEG-ECG-video.
A patient may have multiple studies, and a given study may or may not be
attached to a patient.
- diary: Use of the Seer app by a patient to record events such as seizures
("labels") and "alerts" for medication use
- diary study: A patient study which is not time-bound. May include data from
devices such as smart phones or watches. A diary study must be attached to
a patient, and there can only be one diary study per patient.
- channel group: A mode of monitoring data, dependent on the study type.
Study: EEG, ECG, video
Diary study: Wearable data, e.g. heart rate, step count
- channel: A channel group may have multiple channels. E.g. The different
electrodes for EEG: Fz, C4, Fp1 etc.
- label group: Categories of labels relevant to a study. Depends on the study type.
Study: clinical annotations, e.g. Abnormal / Epileptiform, Normal / Routine
Diary: self-reported annotations of events, e.g. Seizure / Other
Diary study: labels from a wearable device, e.g. Sleep annotations
- label: Belongs to a label group. Labels typically involve the following fields:
id, startTime, duration, timezone, note, tags, confidence, createdAt, createdBy
- tag: An ontology of "attributes" that may be atached to a label to provide
info or clarifications, e.g. Jaw clenching, Beta, Exemplar, Generalised, Sleep.
Tags are arranged into categories, e.g. Band, Brain area, Channel, Seizure type, Sleep
- segment: A duration of recording for a given channel group. Segments lengths
are variable, though generally capped at 135 minutes (at least for EEG)
- data chunk: Segments are saved to disk as 10-second data chunks, which must be
reassembled to yield a complete segment
- party ID: The ID associated with e.g. an organisation, which will filter the
values returned
- API response: Data returned from the GraphQL endpoint, as a dictionary with
string-type keys, and values that may be strings, numbers, bools, dictionaries,
lists of dicts etc.
"""
from datetime import datetime
import math
import time
import json
from gql import gql, Client as GQLClient
from gql.transport.requests import RequestsHTTPTransport
import pandas as pd
from pandas.io.json import json_normalize
import requests
from .auth import SeerAuth
from . import utils
from . import graphql
class SeerConnect: # pylint: disable=too-many-public-methods
graphql_client = None
def __init__(self, api_url='https://api.seermedical.com/api', email=None, password=None,
auth=None):
"""Creates a GraphQL client able to interact with
the Seer database, handling login and authorisation
Parameters
----------
api_url : str, optional
Base URL of API endpoint
email : str, optional
The email address for a user's Seer account
password : str, optional
User password associated with Seer account
dev : bool, optional
dev: Flag to query the development rather than production endpoint
"""
if auth is None:
self.seer_auth = SeerAuth(api_url, email, password)
else:
self.seer_auth = auth
self.create_client()
self.last_query_time = time.time()
self.api_limit_expire = 300
self.api_limit = 580
def create_client(self):
"""
Create a GraphQL client with parameters from the current SeerAuth object.
"""
def graphql_client(party_id=None):
connection_params = self.seer_auth.get_connection_parameters(party_id)
return GQLClient(transport=RequestsHTTPTransport(**connection_params))
self.graphql_client = graphql_client
self.last_query_time = time.time()
def execute_query(self, query_string, party_id=None, invocations=0, variable_values=None):
"""
Execute a GraphQL query and return response. Handle retrying upon
failure and rate limiting requests.
Parameters
----------
query_string: str
The formatted GraphQL query
party_id : str, optional
The organisation/entity to specify for the query
invocations : int, optional
Used for recursive calls; don't set directly
Returns
-------
graphql_results : dict
Query results as a dictionary matching the structure of the query
Notes
-----
See queries in graphql.py for structure of results returned
"""
resolvable_api_errors = [
'502 Server Error', '503 Server Error', '504 Server Error', 'Read timed out.',
'NOT_AUTHENTICATED'
]
try:
time.sleep(
max(0, ((self.api_limit_expire / self.api_limit) -
(time.time() - self.last_query_time))))
response = self.graphql_client(party_id).execute(gql(query_string),
variable_values=variable_values)
self.last_query_time = time.time()
return response
except Exception as ex:
if invocations > 4:
print('Too many failed query invocations. raising error')
raise
error_string = str(ex)
if any(api_error in error_string for api_error in resolvable_api_errors):
if 'NOT_AUTHENTICATED' in error_string:
self.seer_auth.logout()
else:
print('"', error_string, '" raised, trying again after a short break')
time.sleep(
min(30 * (invocations + 1)**2,
max(self.last_query_time + self.api_limit_expire - time.time(), 0)))
invocations += 1
self.seer_auth.login()
return self.execute_query(query_string, party_id, invocations=invocations,
variable_values=variable_values)
raise
def get_paginated_response(self, query_string, limit, object_path, iteration_path=None,
party_id=None):
"""
For queries expecting a large number of objects returned, split query into iterative calls
to `execute_query()`.
The object_path parameter controls which part of the query response is returned, and the
iteration_path parameter indicates where the response can vary for each iteration.
Parameters
----------
query_string : str
The formatted GraphQL query
limit : int
Batch size for repeated API calls
object_path : list of str
One or more levels of key giving the path to the object to be returned
e.g. ['userCohort', 'users'] for a query response of
{"userCohort": {"users": [{"id": "user1"}, {"id": "user2"}]}}
would give [{"id": "user1"}, {"id": "user2"}]
iteration_path : list of str, optional
None (default), one, or more levels of key giving the path to the node where the
response can vary with each query iteration. If None then the response varies at the
path given by object_path
party_id : str, optional
The organisation/entity to specify for the query
Returns
-------
responses: list of dict
List of query result dictionaries
"""
offset = 0
result = []
while True:
formatted_query_string = query_string.format(limit=limit, offset=offset)
response = self.execute_query(formatted_query_string, party_id)
# select the part of the response we are interested in
for key in object_path:
response = response[key]
# select the part of the response which can vary. if iteration_path is None this will be
# the same as the part of the response we are interested in
response_increment = response
if iteration_path:
for key in iteration_path:
response_increment = response_increment[key]
if not response_increment:
# if the part of the response which varies is empty, we are finished iterating
break
if not result:
# if this is the first response, save it
result = response
else:
# otherwise add the response increment to the existing result at the correct level
result_increment_container = result
if iteration_path:
for key in iteration_path:
result_increment_container = result_increment_container[key]
result_increment_container.extend(response_increment)
offset += limit
return result
@staticmethod # maybe this could move to a utility class
def pandas_flatten(parent, parent_name, child_name):
"""
Take a DataFrame with at least 2 columns:
- A column named like f"{parent_name}id"
- A `child_name` column, where each cell is a list of dicts.
Return a new DataFrame that retains the ID column and creates new
columns from the dictionary keys.
Parameters
----------
parent : pd.DataFrame
A DataFrame with f"{parent_name}id" and `child_name` columns
parent_name : str
Any prefix to the 'id' and `child_name` columns in the parent DataFrame
child_name : str
The name of the column with list of dict values
Returns
-------
expanded_df : pd.DataFrame
DataFrame wih columns derived from the `child_name` dicts
Example
-------
>>> df
start.id start.nested
0 A [{'key1': 5, 'key2': 6}, {'key1': 7}]
1 B [{'key2': 8}]
>>> pandas_flatten(df, 'top.', 'nested')
nested.key1 nested.key2 start.id
0 5.0 6.0 A
1 7.0 NaN A
2 NaN 8.0 B
"""
child_list = []
for i in range(len(parent)):
parent_id = parent[parent_name + 'id'][i]
cell_to_flatten = parent[parent_name + child_name][i]
if isinstance(cell_to_flatten, list):
child = json_normalize(cell_to_flatten).sort_index(axis=1)
child.columns = [child_name + '.' + str(col) for col in child.columns]
child[parent_name + 'id'] = parent_id
child_list.append(child)
if child_list:
child = pd.concat(child_list, sort=True).reset_index(drop=True)
if not child_list or child.empty:
columns = [parent_name + 'id', child_name + '.id']
child = pd.DataFrame(columns=columns)
return child
def add_label_group(self, study_id, name, description, label_type=None, party_id=None):
"""
Add a new label group to a study.
Parameters
----------
study_id : str
A unique ID identifying a study
name : str
Name of the new label group
description : str
Free text description of the label group
label_type : str, optional
Label type ID
party_id : str, optional
The organisation/entity to specify for the query
Returns
-------
label_group_id : str
ID of the newly created label group
"""
query_string = graphql.get_add_label_group_mutation_string(study_id, name, description,
label_type)
response = self.execute_query(query_string, party_id)
return response['addLabelGroupToStudy']['id']
def del_label_group(self, group_id):
"""
Delete a label group from a study.
Parameters
----------
group_id : str
Label group ID to delete
Returns
-------
label_group_id : str
ID of the deleted label group
"""
query_string = graphql.get_remove_label_group_mutation_string(group_id)
return self.execute_query(query_string)
def add_labels_batched(self, label_group_id, labels, batch_size=500):
"""
Add labels to label group in batches.
Parameters
----------
label_group_id : str
Label group ID
labels: pd.DateFrame or list of dict
Should include columns/keys as per `add_labels()`
batch_size: int, optional
Number of labels to include per batch
Returns
-------
None
"""
number_of_batches = math.ceil(len(labels) / batch_size)
for i in range(number_of_batches):
start = i * batch_size
end = start + batch_size
self.add_labels(label_group_id, labels[start:end])
def add_labels(self, group_id, labels):
"""
Add labels to label group.
Parameters
----------
group_id : str
Label group ID
labels : pd.DateFrame or list of dict
Should include the following columns/keys:
- note : str
Label note
- startTime : float
Label start time in epoch time
- duration : float
Duration of event in milliseconds
- timezone : float
Offset from UTC time in hours (eg. Melbourne = 11.0)
- tagIds : list of str
Tag IDs
- confidence : float
Confidence given to label between 0 and 1
Returns
-------
labels_added : dict
A dict with a single key, 'addLabelsToLabelGroup', that maps to a
list of dicts, each with an 'id' key indicating an added label
"""
if isinstance(labels, pd.DataFrame):
labels = labels.to_dict('records')
query_string = graphql.get_add_labels_mutation_string()
return self.execute_query(query_string,
variable_values={"groupId": group_id, "labels": labels})
def add_document(self, study_id, document_name, document_path):
"""
Upload a document and associate it with a study.
Parameters
----------
study_id : str
A unique ID identifying a study
document_name : str
Name to assign document after upload
document_path : str
Path to document
Returns
-------
url : str
URL of the uploaded document.
"""
query_string = graphql.get_add_document_mutation_string(study_id, document_name)
response_add = self.execute_query(query_string)['createStudyDocuments'][0]
with open(document_path, 'rb') as f:
response_put = requests.put(response_add['uploadFileUrl'], data=f)
if response_put.status_code == 200:
query_string = graphql.get_confirm_document_mutation_string(
study_id, response_add['id'])
response_confirm = self.execute_query(query_string)
return response_confirm['confirmStudyDocuments'][0]['downloadFileUrl']
else:
raise RuntimeError('Error uploading document: status code '
+ str(response_put.status_code))
def get_tag_ids(self):
"""
Get details of all tag types.
Returns
-------
tags : list of dict
Descriptions of each tag, with keys:
- id
- value
- category
- forDiary
- forStudy
"""
query_string = graphql.get_tag_id_query_string()
response = self.execute_query(query_string)
return response['labelTags']
def get_tag_ids_dataframe(self):
"""
Get details of all tag types as a DataFrame. See `get_tag_ids()` for
details.
Returns
-------
tags_df : pd.DataFrame
DataFrame with tag details
"""
tag_ids = self.get_tag_ids()
tag_ids = json_normalize(tag_ids).sort_index(axis=1)
return tag_ids
def get_study_ids(self, limit=50, search_term='', party_id=None):
"""
Get the IDs of all available studies.
Parameters
----------
limit : int, optional
Batch size for repeated API calls
search_term : str, optional
Filter results to studies that match this string on their study name,
study description, study code, and/or patient name
party_id : str, optional
The organisation/entity to specify for the query
Returns
-------
study_ids : list of str
Unique IDs, each identifying a study
"""
studies = self.get_studies(limit, search_term, party_id)
return [study['id'] for study in studies]
def get_studies(self, limit=50, search_term='', party_id=None):
"""
Get a list of study dicts, with each having keys: 'id', 'name' and 'patient'.
Parameters
----------
limit : int
Batch size for repeated API calls
search_term : str
Filter results to studies including this string, either in the study
name or patient name. Not case sensitive.
party_id : str
The organisation/entity to specify for the query
Returns
-------
studies : list of dict
Study details, each having keys:
- id
- name
- patient
"""
studies_query_string = graphql.get_studies_by_search_term_paged_query_string(search_term)
return self.get_paginated_response(studies_query_string, limit, ['studies'],
party_id=party_id)
def get_studies_dataframe(self, limit=50, search_term='', party_id=None):
"""
Get details of study IDs, names and patient info as a DataFrame. See
`get_studies()` for details.
Parameters
----------
limit : int, optional
Batch size for repeated API calls
search_term : str, optional
A string used to filter the studies returned
party_id : str, optional
The organisation/entity to specify for the query
Returns
-------
study_df: pd.DataFrame
DataFrame with details of all matching studies
"""
studies = self.get_studies(limit, search_term, party_id)
studies_dataframe = json_normalize(studies).sort_index(axis=1)
return studies_dataframe.drop('patient', errors='ignore', axis='columns')
def get_study_ids_from_names_dataframe(self, study_names, party_id=None):
"""
Get the IDs of all available studies as a DataFrame. See `get_studies()`
for details.
Parameters
----------
study_names : str or list of str
Study names to retrieve
party_id : str, optional
The organisation/entity to specify for the query
Returns
-------
study_ids_df : pd.DataFrame
A DataFrarme wihth study names and IDs
"""
if isinstance(study_names, str):
study_names = [study_names]
studies = json_normalize([
study for study_name in study_names
for study in self.get_studies(search_term=study_name, party_id=party_id)
])
if studies.empty:
return studies.assign(id=None)
return studies[['name', 'id']].reset_index(drop=True)
def get_study_ids_from_names(self, study_names, party_id=None):
"""
Get the IDs of studies corresponding to given study names.
See `get_studies()` for details.
Parameters
----------
study_names : str or list of str
Study name or names to look up
party_id : str, optional
The organisation/entity to specify for the query
Returns
-------
study_ids: list of str
Unique IDs, each identifying a study
"""
return self.get_study_ids_from_names_dataframe(study_names, party_id)['id'].tolist()
def get_studies_by_id(self, study_ids, limit=50):
"""
Get a dict of study details for each study ID provided.
Parameters
----------
study_ids : str or list of str
One or more unique IDs, each identifying a study
limit : int, optional
Batch size for repeated API calls
Returns
-------
study_dicts: list of dict
Details for each study (name, ID etc)
"""
if isinstance(study_ids, str):
study_ids = [study_ids]
studies_query_string = graphql.get_studies_by_study_id_paged_query_string(study_ids)
return self.get_paginated_response(studies_query_string, limit, ['studies'])
def get_channel_groups(self, study_id):
"""
Get details of each channel group for a given study.
Parameters
----------
study_id : str
A unique ID identifying a study
Returns
-------
channel_groups : list of dict
Details for each channel group, with dicts including keys:
- name
- sampleRate
- segments
"""
query_string = graphql.get_channel_groups_query_string(study_id)
response = self.execute_query(query_string)
return response['study']['channelGroups']
def get_segment_urls(self, segment_ids, limit=10000):
"""
Get a DataFrame with segment IDs and URLs from which to download them.
Parameters
----------
segment_ids : list of str
Iterable of segment IDs
limit : int, optional
Batch size for repeated API calls
Returns
-------
segment_url_df : pd.DataFrame
DataFrame with columns 'baseDataChunkUrl' and 'segments.id'
"""
if not segment_ids:
return pd.DataFrame(columns=['baseDataChunkUrl', 'segments.id'])
segments = []
counter = 0
while int(counter * limit) < len(segment_ids):
segment_ids_batch = segment_ids[int(counter * limit):int((counter + 1) * limit)]
query_string = graphql.get_segment_urls_query_string(segment_ids_batch)
response = self.execute_query(query_string)
segments.extend([
segment for segment in response['studyChannelGroupSegments'] if segment is not None
])
counter += 1
segment_urls = pd.DataFrame(segments)
segment_urls = segment_urls.rename(columns={'id': 'segments.id'})
return segment_urls
def get_data_chunk_urls(self, study_metadata, s3_urls=True, from_time=0, to_time=9e12,
limit=10000):
"""
Get a DataFrame containing download details of all data chunks that
comprise the segments in a provided metadata DataFrame.
Parameters
----------
study_metadata : pd.DataFrame
Study metadata as returned by `get_all_study_metadata_dataframe_by_*()`
s3_urls : bool, optional
Return download URLs for S3 (otherwise return URLs for Cloudfront)
from_time : int, optional
Timestamp in msec - only retrieve data from this point onward
to_time : int, optional
Timestamp in msec - only retrieve data up until this point
limit : int, options
Batch size for repeated API calls
Returns
-------
data_chunk_df : pd.DataFrame
The returned DataFrame has columns:
- segments.id
- chunkIndex
- chunk_start
- chunk_end
- chunk_url
"""
if study_metadata.empty:
return pd.DataFrame(
columns=['segments.id', 'chunkIndex', 'chunk_start', 'chunk_end', 'chunk_url'])
study_metadata = study_metadata.drop_duplicates('segments.id')
study_metadata = study_metadata[study_metadata['segments.startTime'] <= to_time]
study_metadata = study_metadata[study_metadata['segments.startTime']
+ study_metadata['segments.duration'] >= from_time]
data_chunks = []
chunk_metadata = []
for row in zip(study_metadata['channelGroups.chunkPeriod'],
study_metadata['segments.duration'], study_metadata['segments.startTime'],
study_metadata['segments.id']):
chunk_period = row[0]
num_chunks = int(math.ceil(row[1] / chunk_period / 1000.))
for i in range(num_chunks):
chunk_start = row[2] + chunk_period * i
chunk_end = chunk_start + chunk_period
if chunk_start >= from_time and chunk_end <= to_time:
data_chunks.append({'segmentId': row[3], 'chunkIndex': i})
chunk_metadata.append({
'segments.id': row[3],
'chunkIndex': i,
'chunk_start': chunk_start,
'chunk_end': chunk_end
})
if not data_chunks:
return pd.DataFrame(
columns=['segments.id', 'chunkIndex', 'chunk_start', 'chunk_end', 'chunk_url'])
chunks = []
counter = 0
while int(counter * limit) < len(data_chunks):
data_chunks_batch = data_chunks[int(counter * limit):int((counter + 1) * limit)]
query_string = graphql.get_data_chunk_urls_query_string(data_chunks_batch, s3_urls)
response = self.execute_query(query_string)
chunks.extend([
chunk for chunk in response['studyChannelGroupDataChunkUrls'] if chunk is not None
])
counter += 1
data_chunk_urls = pd.DataFrame(chunk_metadata)
data_chunk_urls['chunk_url'] = chunks
return data_chunk_urls
# pylint:disable=too-many-arguments
def get_labels(self, study_id, label_group_id, from_time=0, to_time=9e12, limit=200, offset=0):
"""
Get labels for a given study and label group.
Parameters
----------
study_id : str
A unique ID identifying a study
label_group_id : str
Label group ID
from_time : int, optional
Timestamp in msec - only retrieve data from this point onward
to_time : int, optional
Timestamp in msec - only retrieve data up until this point
limit : int, optional
Batch size for repeated API calls
offset : int, optional
Index of first label to retrieve
Returns
-------
labels : dict
Has a 'labelGroup' key which indexes to a nested dict with a 'labels' key
"""
query_string = graphql.get_labels_paged_query_string(study_id, label_group_id, from_time,
to_time)
return self.get_paginated_response(query_string, limit, ['study'], ['labelGroup', 'labels'])
# pylint:disable=too-many-arguments
def get_labels_dataframe(self, study_id, label_group_id, from_time=0, to_time=9e12, limit=200,
offset=0):
"""
Get all labels for a given study and label group as a DataFrame.
See `get_labels()` for details.
Returns
-------
labels_df : pd.DataFrame
Details of all matching labels
"""
label_results = self.get_labels(study_id, label_group_id, from_time, to_time, limit, offset)
if label_results is None:
return label_results
label_group = json_normalize(label_results).sort_index(axis=1)
labels = self.pandas_flatten(label_group, 'labelGroup.', 'labels')
tags = self.pandas_flatten(labels, 'labels.', 'tags')
label_group = label_group.drop('labelGroup.labels', errors='ignore', axis='columns')
labels = labels.drop('labels.tags', errors='ignore', axis='columns')
label_group = label_group.merge(labels, how='left', on='labelGroup.id', suffixes=('', '_y'))
label_group = label_group.merge(tags, how='left', on='labels.id', suffixes=('', '_y'))
return label_group
def get_labels_string(self, study_id, label_group_id, from_time=0, to_time=9e12):
"""
Get all labels for a given study and label group as an abridged string
representation. Because the GraphQL response is unvalidated, it can
perform significantly faster for larger datasets.
Parameters
----------
study_id : str
A unique ID identifying a study
label_group_id : str
Label group ID
from_time : int, optional
Timestamp in msec - only retrieve data from this point onward
to_time : int, optional
Timestamp in msec - only retrieve data up until this point
Returns
-------
labels_str : dict
Has a key 'labelString' which indexes a JSON-like string with only
3 keys per label: 'id', 's' (for startTime), and 'd' (for duration)
"""
query_string = graphql.get_labels_string_query_string(study_id, label_group_id, from_time,
to_time)
response = self.execute_query(query_string)
return response['study']
# pylint:disable=too-many-arguments
def get_labels_string_dataframe(self, study_id, label_group_id, from_time=0, to_time=9e12):
"""
Get all labels for a given study and label group in an abridged string
representation, as a DataFrame. See `get_labels_string()` for details.
Returns
-------
labels_str_df : pd.DataFrame
Columns include 'labels.id', 'labels.startTime' and 'labels.duration'
"""
label_results = self.get_labels_string(study_id, label_group_id, from_time=from_time,
to_time=to_time)
if label_results is None:
return label_results
label_group = json_normalize(label_results).sort_index(axis=1)
label_group['labelGroup.labelString'] = (label_group['labelGroup.labelString'].apply(
json.loads))
labels = self.pandas_flatten(label_group, 'labelGroup.', 'labelString')
label_group = label_group.drop('labelGroup.labelString', errors='ignore', axis='columns')
label_group = label_group.merge(labels, how='left', on='labelGroup.id', suffixes=('', '_y'))
label_group = label_group.rename(
columns={
'labelString.d': 'labels.duration',
'labelString.id': 'labels.id',
'labelString.s': 'labels.startTime'
})
return label_group
def get_label_groups_for_studies(self, study_ids, limit=50):
"""
Get label group information for all provided study IDs.
Parameters
----------
study_ids : str or list of str
One or more unique IDs, each identifying a study
limit : int, optional
Batch size for repeated API calls
Returns
-------
label_groups : list of dict
Keys included: 'id', 'labelGroups' and 'name'
"""
if isinstance(study_ids, str):
study_ids = [study_ids]
labels_query_string = graphql.get_label_groups_for_study_ids_paged_query_string(study_ids)
return self.get_paginated_response(labels_query_string, limit, ['studies'])
def get_label_groups_for_studies_dataframe(self, study_ids, limit=50):
"""
Get label group information for all provided study IDs as a DataFrame.
See `get_label_groups_for_studies()`.
Returns
-------
label_groups_df : pd.DataFrame
Columns with details on name, id, type, and number of labels, as
well as study ID and name
"""
label_groups = []
for study in self.get_label_groups_for_studies(study_ids, limit):
for label_group in study['labelGroups']:
label_group['labelGroup.id'] = label_group.pop('id')
label_group['labelGroup.name'] = label_group.pop('name')
label_group['labelGroup.labelType'] = label_group.pop('labelType')
label_group['labelGroup.numberOfLabels'] = label_group.pop('numberOfLabels')
label_group['id'] = study['id']
label_group['name'] = study['name']
label_groups.append(label_group)
return pd.DataFrame(label_groups)
def get_viewed_times_dataframe(self, study_id, limit=250, offset=0):
"""
Get timestamp info about all parts of a study that have been viewed by
various users.
Parameters
----------
study_id : str
A unique ID identifying a study
limit : int, optional
Batch size for repeated API calls
offset : int, optional
Index of first record to return
Returns
-------
times_df : pd.DataFrame
Includes columns 'id', 'startTime', 'duration' and 'user'
"""
views = []
while True:
query_string = graphql.get_viewed_times_query_string(study_id, limit, offset)
response = self.execute_query(query_string)
response = json_normalize(response['viewGroups']).sort_index(axis=1)
non_empty_views = False
for i in range(len(response)):
view = json_normalize(response.at[i, 'views']).sort_index(axis=1)
view['user'] = response.at[i, 'user.fullName']
if not view.empty:
non_empty_views = True
views.append(view)
if not non_empty_views:
break
offset += limit
if views:
views = pd.concat(views).reset_index(drop=True)
views['createdAt'] = pd.to_datetime(views['createdAt'])
views['updatedAt'] = pd.to_datetime(views['updatedAt'])
else:
views = None
return views
def get_organisations(self):
"""
Get details of all available organisations.
Returns
-------
organisations : list of dict
Dictionaries with organisation 'id' and 'name' keys
"""
query_string = graphql.get_organisations_query_string()
response = self.execute_query(query_string)
return response['organisations']
def get_organisations_dataframe(self):
"""
Get details of all available organisations as a DataFrame.
Returns
-------
orgs_df : pd.DataFrame
Organisations DataFrame with 'id' and 'name' columns
"""
orgs = self.get_organisations()
if orgs is None:
return orgs
return pd.DataFrame(orgs)
def get_user_from_patient(self, patient_id):
"""
Get user ID and info from patient ID.
Parameters
----------
patient_id : str
The patient ID
Returns
-------
patient : dict
Patient details, with keys 'id' and 'user'
"""
query_string = graphql.get_user_from_patient_query_string(patient_id)
response = self.execute_query(query_string)
return response['patient']
def get_user_from_patient_dataframe(self, patient_id):
"""
Get user ID and info from patient ID.
Parameters
----------
patient_id : str
The patient ID
Returns
-------
patient : pd.DataFrame
Patient details as pandas DataFrame
"""
patient = self.get_user_from_patient(patient_id)
if not patient:
return pd.DataFrame()
return json_normalize(patient).sort_index(axis=1)
def get_patients(self, party_id=None):
"""
Get available patient IDs and user names.
Parameters
----------
party_id : str, optional
The organisation/entity to specify for the query
Returns
-------
patients : list of dict
Patient details, with keys 'id' and 'user'
"""
query_string = graphql.get_patients_query_string()
response = self.execute_query(query_string, party_id)
return response['patients']
def get_patients_dataframe(self, party_id=None):
"""
Get available patient IDs and user names as a DataFrame.
Parameters
----------
party_id : str, optional
The organisation/entity to specify for the query
Returns
-------
patient_df : pd.DataFrame
Patient details, with columns 'id' and 'user'
"""
patients = self.get_patients(party_id)