-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfunctions.py
More file actions
1389 lines (1209 loc) · 48.7 KB
/
functions.py
File metadata and controls
1389 lines (1209 loc) · 48.7 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
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
'''
File: functions.py
Project: opensilex-ws-python-client
Created Date: 01 May 2021
Author: Arnaud Charleroy
-----
Last Modified: Thu Sep 09 2021
Modified By: Gabriel Besombes
-----
HISTORY:
Date By Comments
---------- --- ---------------------------------------------------------
'''
from __future__ import print_function
from os import truncate # Must be here
# TODO : make a class instead
# with a connect method that auto reconnects every x minutes unless signaled to stop
# recurcive method?
# Proper way is probably with an event loop : https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds
"""Custom functions for data imports
TOCHANGE : This script allows the user to print to the console all columns in the
spreadsheet. It is assumed that the first row of the spreadsheet is the
location of the columns.
TOCHANGE : This tool accepts comma separated value files (.csv) as well as excel
(.xls, .xlsx) files.
This script requires that the following packages be installed within
the Python environment you are running this script in :
* `opensilexClientToolsPython`
* `requests`
* `pandas`
* `dateparser`
TOCHANGE : This file can also be imported as a module and contains
the following functions:
* get_spreadsheet_cols - returns the column headers of the file
* main - the main function of the script
"""
# %%
import opensilexClientToolsPython
from pprint import pprint
from datetime import datetime
from opensilexClientToolsPython.models.entity_creation_dto import EntityCreationDTO
import requests
import re
import io
import pandas as pd
from dateparser import parse
import logging
from typing import Union, List
from pydantic import validate_arguments
from functions import *
# %%
# Setup logging file
logging.basicConfig(level=logging.DEBUG, handlers=[
logging.FileHandler("debug.log"),
logging.StreamHandler()
],format='%(asctime)s %(levelname)-8s\
[%(filename)s:%(lineno)d] %(message)s')
# %%
# Define full schema
full_schema = {
'trait':'trait.uri',
'trait_name':'trait.label',
'entity':{
'name':'entity.label',
'uri':'entity.uri',
'description':'entity.comment',
'exact_match':'exact_match',
'close_match':'close_match',
'broad_match':'broad_match',
'narrow_match':'narrow_match'
},
'characteristic':{
'name':'characteristic.label',
'uri':'characteristic.uri',
'description':'characteristic.comment',
'exact_match':'exact_match',
'close_match':'close_match',
'broad_match':'broad_match',
'narrow_match':'narrow_match'
},
'method':{
'name':'method.label',
'uri':'method.uri',
'description':'method.comment',
'exact_match':'exact_match',
'close_match':'close_match',
'broad_match':'broad_match',
'narrow_match':'narrow_match'
},
'unit':{
'name':'unit.label',
'uri':'unit.uri',
'description':'unit.comment',
'symbol':'symbol',
'alternative_symbol':'alternative_symbol',
'exact_match':'exact_match',
'close_match':'close_match',
'broad_match':'broad_match',
'narrow_match':'narrow_match'
},
'uri':'variable.uri',
'name':'variable.label',
'description':'variable.description',
'datatype':'variable.datatype',
'alternative_name':'variable.alternative_name',
'time_interval':'variable.timeinterval',
'sampling_interval':'variable.sampleinterval',
'exact_match':'exact_match',
'close_match':'close_match',
'broad_match':'broad_match',
'narrow_match':'narrow_match'
}
# %%
@validate_arguments(config=dict(arbitrary_types_allowed=True))
def create_experiment(
python_client: opensilexClientToolsPython.ApiClient,
name: str,
objective: str,
start_date: datetime,
end_date: datetime = None,
uri: str = None,
description: str = None,
species: List[str] = None,
variables: List[str] = None,
organisations: List[str] = None,
projects: List[str] = None,
scientific_supervisorslist: str = None,
technical_supervisors: List[str] = None,
groups: List[str] = None,
factors: List[str] = None,
is_public: bool = None
) -> dict:
"""Creates an experiment
Parameters
----------
python_client : opensilexClientToolsPython.ApiClient
The authenticated client to connect to Opensilex
All the following arguments can be unpacked from a dict for easier use.
To do so you just have to call the function as follows :
create_experiment(python_client, **my_dict)
name: str
The name of the experiment (required)
objective: str
The objective of the experiment (required)
start_date: datetime
The starting date of the experiment (required)
end_date: datetime = None
The end date of the experiment
uri: str = None
The uri of the experiment (optional, will be auto-generated if
none is given)
description: str = None
A short description of the experiment
species: List[str] = None
A list of the species in the experiment
variables: List[str] = None
A list of the variables of the experiment
organisations: List[str] = None
A list of the organisations that take part in the experiment (NOT SURE)
projects: List[str] = None
A list of the projects in the experiment (NOT SURE)
scientific_supervisorslist: str = None
The name (or uri) of the supervisor of the experiment (NOT SURE)
technical_supervisors: List[str] = None
The names (or uris) of the supervisors of the experiment (NOT SURE)
groups: List[str] = None
The groups (uris) that have acces to this experiment
factors: List[str] = None
The factors (uris) studied in the experiment (NOT SURE)
is_public: bool = None
Wether or not the experiment is public
Returns
-------
dict
A dictionary representing the experiment (with the
auto-generated uri if none was specified)
"""
# Extract all non-None arguments for experiment as a dictionary
loc = locals()
experiment = {
k: loc[k]
for k in loc.keys()
if(k!="python_client" and loc[k]!=None)
}
# Create an instance of the Experiment Api
experiment_os_api = opensilexClientToolsPython\
.ExperimentsApi(python_client)
# Creating an object of ExperimentCreationDTO class to use for
# experiment creation
new_expriment = opensilexClientToolsPython\
.ExperimentCreationDTO(**experiment)
try:
# Creating an experiment on Opensilex and catching the result
experiment_result = experiment_os_api\
.create_experiment(body=new_expriment)
# Updating the uri in case none was specified
experiment["uri"] = experiment_result.get("result")[0]
logging.info("new experiment " + experiment["name"] + " created")
# Return the updated dict
return experiment
# Catch exceptions to use custom error message if the experiment
# already exists
except Exception as e:
if "exists" not in str(e):
logging.error("Exception : %s\n" % e)
else:
logging.info("experiment " + experiment["name"] + " already exists")
# %%
@validate_arguments(config=dict(arbitrary_types_allowed=True))
def is_empty(value: str) -> bool:
"""Check for emptyness
Parameters
----------
value : either None or str
Returns
-------
bool
True if empty, False if not
"""
# Check for None, or equivalents : "NA", "nan"
if value is None:
return True
if(value == "NA" or value == None or value == "nan"):
return True
return False
@validate_arguments(config=dict(arbitrary_types_allowed=True))
def format_comment(comment: str) -> str:
"""Format comment
Parameters
----------
raw_comment : str
Returns
-------
str
The comment in str type or "No description" if found empty
"""
if(is_empty(comment)):
return "No description"
return comment
# %%
@validate_arguments(config=dict(arbitrary_types_allowed=True))
def migrate_variables_from_googlesheet(
python_client: opensilexClientToolsPython.ApiClient,
spreadsheet_url: str,
gid_number: str,
variables_schema: dict = {
'trait':'trait.uri',
'trait_name':'trait.label',
'entity':{
'name':'entity.label',
'uri':'entity.uri',
'description':'entity.comment'
},
'characteristic':{
'name':'characteristic.label',
'uri':'characteristic.uri',
'description':'characteristic.comment'
},
'method':{
'name':'method.label',
'uri':'method.uri',
'description':'method.comment'
},
'unit':{
'name':'unit.label',
'uri':'unit.uri',
'description':'unit.comment'
},
'uri':'variable.uri',
'name':'variable.label',
'description':'variable.description',
'datatype':'variable.datatype',
'alternative_name':'variable.alternative_name',
'time_interval':'variable.timeinterval',
'sampling_interval':'variable.sampleinterval'
},
update: bool = False
) -> None:
"""Get variables data from googlesheet
Parameters
----------
python_client: opensilexClientToolsPython.ApiClient
The authenticated client to connect to Opensilex
spreadsheet_url: str
The url of the googlesheet to get the variables from
gid_number: str
TODO
variables_schema: dict
Dictionnary that describes the header of the in correspondance
with the names in opensilex.
Format is 'opensilexname':'columnname'
or 'opensilexsubtype':{'opensilexname':'columnname'}
Example : {
'trait':'trait.uri',
'trait_name':'trait.label',
'entity':{
'name':'entity.label',
'uri':'entity.uri',
'description':'entity.comment'
},
'characteristic':{
'name':'characteristic.label',
'uri':'characteristic.uri',
'description':'characteristic.comment'
},
'method':{
'name':'method.label',
'uri':'method.uri',
'description':'method.comment'
},
'unit':{
'name':'unit.label',
'uri':'unit.uri',
'description':'unit.comment'
},
'uri':'variable.uri',
'name':'variable.label',
'description':'variable.description',
'datatype':'variable.datatype',
'alternative_name':'variable.alternative_name',
'time_interval':'variable.timeinterval',
'sampling_interval':'variable.sampleinterval'
}
update: bool = False
TODO (wether or not to update?)
Returns
-------
None
"""
variables_url = spreadsheet_url + "/gviz/tq?tqx=out:csv&gid=" + gid_number
logging.info(variables_url)
variables_csv_string = requests.get(variables_url).content
variables_csv = pd.read_csv(io.StringIO(variables_csv_string.decode('utf-8')))
# Replace nan with None
variables_csv = variables_csv.where(
pd.notnull(variables_csv), None
)
return migrate_variables(
python_client=python_client,
variables_csv=variables_csv,
variables_schema=variables_schema,
update=update
)
@validate_arguments(config=dict(arbitrary_types_allowed=True))
def migrate_variables_from_csv(
python_client: opensilexClientToolsPython.ApiClient,
csv_path: str,
variables_schema: dict = {
'trait':'trait.uri',
'trait_name':'trait.label',
'entity':{
'name':'entity.label',
'uri':'entity.uri',
'description':'entity.comment'
},
'characteristic':{
'name':'characteristic.label',
'uri':'characteristic.uri',
'description':'characteristic.comment'
},
'method':{
'name':'method.label',
'uri':'method.uri',
'description':'method.comment'
},
'unit':{
'name':'unit.label',
'uri':'unit.uri',
'description':'unit.comment'
},
'uri':'variable.uri',
'name':'variable.label',
'description':'variable.description',
'datatype':'variable.datatype',
'alternative_name':'variable.alternative_name',
'time_interval':'variable.timeinterval',
'sampling_interval':'variable.sampleinterval'
},
update: bool = False
) -> None:
"""Get variables data from a csv
Parameters
----------
python_client: opensilexClientToolsPython.ApiClient
The authenticated client to connect to Opensilex
csv_path: str
The path to the csv file to get the variables from
variables_schema: dict
Dictionnary that describes the header of the in correspondance
with the names in opensilex.
Format is 'opensilexname':'columnname'
or 'opensilexsubtype':{'opensilexname':'columnname'}
Example : {
'trait':'trait.uri',
'trait_name':'trait.label',
'entity':{
'name':'entity.label',
'uri':'entity.uri',
'description':'entity.comment'
},
'characteristic':{
'name':'characteristic.label',
'uri':'characteristic.uri',
'description':'characteristic.comment'
},
'method':{
'name':'method.label',
'uri':'method.uri',
'description':'method.comment'
},
'unit':{
'name':'unit.label',
'uri':'unit.uri',
'description':'unit.comment'
},
'uri':'variable.uri',
'name':'variable.label',
'description':'variable.description',
'datatype':'variable.datatype',
'alternative_name':'variable.alternative_name',
'time_interval':'variable.timeinterval',
'sampling_interval':'variable.sampleinterval'
}
update: bool = False
TODO (wether or not to update?)
Returns
-------
None
"""
variables_csv = pd.read_csv(csv_path)
if len(variables_csv.columns) <= 2:
variables_csv = pd.read_csv(csv_path, sep=";")
# Replace nan with None
variables_csv = variables_csv.where(
pd.notnull(variables_csv), None
)
return migrate_variables(
python_client=python_client,
variables_csv=variables_csv,
variables_schema=variables_schema,
update=update
)
# TODO Create a func to exchange heys and values in a dict
@validate_arguments(config=dict(arbitrary_types_allowed=True))
def migrate_variables(
python_client: opensilexClientToolsPython.ApiClient,
variables_csv: pd.DataFrame,
variables_schema: dict = {
'trait':'trait.uri',
'trait_name':'trait.label',
'entity':{
'name':'entity.label',
'uri':'entity.uri',
'description':'entity.comment'
},
'characteristic':{
'name':'characteristic.label',
'uri':'characteristic.uri',
'description':'characteristic.comment'
},
'method':{
'name':'method.label',
'uri':'method.uri',
'description':'method.comment'
},
'unit':{
'name':'unit.label',
'uri':'unit.uri',
'description':'unit.comment',
},
'uri':'variable.uri',
'name':'variable.label',
'description':'variable.description',
'datatype':'variable.datatype',
'alternative_name':'variable.alternative_name',
'time_interval':'variable.timeinterval',
'sampling_interval':'variable.sampleinterval'
},
update: bool = False
) -> None:
"""Create variables from a pandas.DataFrame
Parameters
----------
python_client: opensilexClientToolsPython.ApiClient
The authenticated client to connect to Opensilex
variables_csv: pd.DataFrame
A pandas DataFrame containing the data needed to create the variables
variables_schema: dict
Dictionnary that describes the header of the in correspondance
with the names in opensilex.
Format is 'opensilexname':'columnname'
or 'opensilexsubtype':{'opensilexname':'columnname'}
Example : {
'trait':'trait.uri',
'trait_name':'trait.label',
'entity':{
'name':'entity.label',
'uri':'entity.uri',
'description':'entity.comment'
},
'characteristic':{
'name':'characteristic.label',
'uri':'characteristic.uri',
'description':'characteristic.comment'
},
'method':{
'name':'method.label',
'uri':'method.uri',
'description':'method.comment'
},
'unit':{
'name':'unit.label',
'uri':'unit.uri',
'description':'unit.comment'
},
'uri':'variable.uri',
'name':'variable.label',
'description':'variable.description',
'datatype':'variable.datatype',
'alternative_name':'variable.alternative_name',
'time_interval':'variable.timeinterval',
'sampling_interval':'variable.sampleinterval'
}
update: bool = False
TODO (wether or not to update?)
Returns
-------
None
"""
# The update isn't currently implemented
logging.info("Update mode variable is set to " + str(update) + "\n\n")
# Check if the names given in the schema exist in the DataFrame
cols = []
for val in variables_schema.values():
if type(val)==str:
cols.append(val)
else:
cols = cols + list(val.values())
col_match = [
col
for col in cols
if col not in variables_csv.columns
]
if col_match:
raise ValueError(
"""The following names in the schema couldn't be matched to any columns :
{0}
The actual columns found are :
{1}
""".format(col_match, variables_csv.columns)
)
# DataFrame for results of objects creations
variables_df = pd.DataFrame(
columns=[key for key in full_schema]
)
# DataFrame for objects already existed
already_df = pd.DataFrame(
columns=[key for key in full_schema]
)
# DataFrame for failed objects
failed_df = pd.DataFrame(
columns=[key for key in variables_schema]
)
# Fetch all datatypes for Variable creation
var_api_instance = opensilexClientToolsPython.VariablesApi(python_client)
datatypes = var_api_instance.get_datatypes()
# Create all objects that need to be created on opensilex
for key in variables_schema.keys():
# Create objects on opensilex if needed
if type(variables_schema[key])==dict:
# TODO work from unique values then join the results to get the right format
# Subset of the dataframe with the data needed to create the objects
sub_df = variables_csv[variables_schema[key].values()]
# Change column labels to opensilex labels
col_exchange = {
v:k
for k,v in variables_schema[key].items()
}
sub_df.rename(columns=col_exchange, inplace=True)
# DataFrame for results
df_res = pd.DataFrame(columns=full_schema[key].keys(), dtype=object)
# Create all the objects line by line
for index, row in sub_df.iterrows():
# Check if row is a duplicate of previous rows
duplicate_of = (
sub_df.loc[:index-1].values == row.values
).all(axis=1)
# If it is a duplicate use the data already in df_res
if duplicate_of.any():
# Use the first row of all the duplicates
df_res.loc[index] = df_res.loc[:index-1]\
.loc[duplicate_of].iloc[0]
# Otherwise create the object
else:
try:
object_info = create_base_variable(
python_client=python_client,
row=row,
index=index,
variable_subtype=key,
)
# If failed set the row to False and save it in failed
if object_info[1] == "failed":
failed_df = failed_df.append(row, ignore_index=True)
df_res.loc[index] = False
# If already existed update the info and save it in already existed
elif object_info[1] == "already":
already_df = already_df.append(object_info[0], ignore_index=True)
df_res.loc[index] = object_info[0]
else:
df_res.loc[index] = object_info[0]
except Exception as e:
logging.info(object_info)
logging.error("Exception : %s\n" % e)
failed_df = failed_df.append(row, ignore_index=True)
df_res.loc[index] = False
# The column for the variable subtype is set to contain the uris
variables_df[key] = df_res.uri
# Special case : 'datatype'
elif key == "datatype":
# Subset of the dataframe with the datatypes
sub_df = pd.DataFrame(variables_csv[variables_schema[key]])
# Change column labels to opensilex labels
sub_df.rename(columns={variables_schema[key]:key}, inplace=True)
# DataFrame for results
df_res = pd.DataFrame(columns=full_schema.keys(), dtype=object)
# Set the datatypes line by line
for index, row in sub_df.iterrows():
datatype_matches = [
dt.uri
for dt in datatypes["result"]
if row[key].lower() in dt.name.lower()
]
if any(datatype_matches):
# If multiple matches, keep first one : should never happen
df_res.loc[index, key] = datatype_matches[0]
else:
# If no matches, set to False
df_res.loc[index, key] = False
logging.info(
"""Couldn't find a datatype for : {}\n""".format(
row.loc[key]
)
)
failed_df = failed_df.append(row, ignore_index=True)
df_res.loc[index, key] = False
variables_df[key] = df_res[key]
else:
variables_df[key] = variables_csv[variables_schema[key]]
# Now that all necessary objects were created the Variables can be created
# TODO Should probably be a separate func
for index, row in variables_df.iterrows():
# If at least one object couldn't be created
if (row==False).any():
logging.info(
"""This variable couldn't be created because one or more objects couldn't be created:
{}\n""".format(dict(row))
)
# Save it in the failed and remove it from the successes
failed_df = failed_df.append(row, ignore_index=True)
variables_df.drop(index=index, inplace=True)
else:
try:
# Replace nan with None
r = row.where(pd.notnull(row), None)
# Create the variable
var_info = create_base_variable(
python_client=python_client,
row=r,
index=index,
variable_subtype='variable'
)
if var_info[1] == "failed":
# Save it in the failed and remove it from the successes
failed_df = failed_df.append(row, ignore_index=True)
variables_df.drop(index=index, inplace=True)
elif var_info[1] == "already":
# Save it in the failed and remove it from the successes
already_df = already_df.append(var_info[0], ignore_index=True)
variables_df.drop(index=index, inplace=True)
else:
# Update the values after variable creation
variables_df.loc[index, var_info[0].keys()] = var_info[0]
except Exception as e:
logging.info(dict(r))
logging.error("Exception : %s\n" % e)
# Export variables DataFrame to csv
variables_df.to_csv("variables_created.csv", index=False)
# Export already existed DataFrame to csv
already_df.to_csv("already_existed.csv", index=False)
# Export failed objects DataFrame to csv
failed_df.to_csv("failed.csv", index=False)
return variables_df
# %%
# Create variables or objects on opensilex
@validate_arguments(config=dict(arbitrary_types_allowed=True))
def create_base_variable(
python_client: opensilexClientToolsPython.ApiClient,
row: pd.Series,
index: int,
variable_subtype: str
)-> Union[dict, str]:
"""Create objects in opensilex
Parameters
----------
python_client: opensilexClientToolsPython.ApiClient
The authenticated client to connect to Opensilex
row: pd.Series
The series containing the data to create the object on opensilex
variable_subtype: str
The subtype of the object to be created (entity, unit, etc...)
Returns
-------
created_object: Union[dict, bool]
Returns a dict corresponding to the object created or found that
already existed on opensilex or False if it failed
"""
# Dictionnary of DTO functions to use for each object subtype
dtos = {
"entity": opensilexClientToolsPython.EntityCreationDTO,
"characteristic": opensilexClientToolsPython.CharacteristicCreationDTO,
"unit": opensilexClientToolsPython.UnitCreationDTO,
"method": opensilexClientToolsPython.MethodCreationDTO,
"variable": opensilexClientToolsPython.VariableCreationDTO
}
# Dictionnary of apis to use for each object subtype
apis = {
"entity": opensilexClientToolsPython.VariablesApi(python_client),
"characteristic": opensilexClientToolsPython.VariablesApi(python_client),
"unit": opensilexClientToolsPython.VariablesApi(python_client),
"method": opensilexClientToolsPython.VariablesApi(python_client),
"variable": opensilexClientToolsPython.VariablesApi(python_client)
}
# Dictionnary of creation functions to use for each object subtype
creation_func = {
"entity": apis["entity"].create_entity,
"characteristic": apis["characteristic"].create_characteristic,
"unit": apis["unit"].create_unit,
"method": apis["method"].create_method,
"variable": apis["variable"].create_variable,
}
# Dictionnary of search functions to use for each object subtype
search_func = {
"entity": apis["entity"].search_entities,
"characteristic": apis["characteristic"].search_characteristics,
"unit": apis["unit"].search_units,
"method": apis["method"].search_methods,
"variable": apis["variable"].search_variables
}
# Dictionnary of get functions to use for each object subtype
get_func = {
"entity": apis["entity"].get_entity,
"characteristic": apis["characteristic"].get_characteristic,
"unit": apis["unit"].get_unit,
"method": apis["method"].get_method,
"variable": apis["variable"].get_variable
}
# If no name was given, custom message
if "name" in row.index and row["name"] == None:
# If no uri was given, custom message
if ("uri" in row.index and row["uri"] == None) or "uri" not in row.index:
logging.info(
"""The object {} couldn't be created as no name was given and couldn't be found as no uri was given\n"""\
.format(dict(row))
)
return(dict(row), "failed")
# Trying to match uri
try:
old_object = get_func[variable_subtype](
uri = row["uri"]
)
except:
# If no name was given and the uri doesn't match any object, custom message
logging.info(
"""The object {} couldn't be created as no name was given and couldn't be found as no object with that uri exist\n"""\
.format(dict(row))
)
return(dict(row), "failed")
v = vars(old_object["result"])
return_dict = {
col.replace("_", "", 1): v[col]
for col in v
if "_" in col
}
logging.info(
"""Object {0} at row {1} wasn't created as no name was given and an object with that uri already exists.
That object was skipped and will appear in the "already_existed.csv" file.
The object used instead is {2}\n""".format(dict(row), index, return_dict)
)
# TODO add row to already_existed.csv
return (return_dict, "already")
# Check if the object already exists
try:
# Escape regex for exact match
# TODO : ignore case
escaped_name = re.escape(row["name"])
old_object = search_func[variable_subtype](
name="^" + escaped_name + "$"
)
if len(old_object["result"]) != 0:
# Making sure to have a consistent output
old_object = get_func[variable_subtype](
uri = old_object["result"][0].uri
)
v = vars(old_object["result"])
return_dict = {
col.replace("_", "", 1): v[col]
for col in v
if "_" in col
}
logging.info(
"""Object {0} at row {1} wasn't created as an object with that name already exists.
That object was skipped and will appear in the "already_existed.csv" file.
The object used instead is {2}\n""".format(dict(row), index, return_dict)
)
# TODO add row to already_existed.csv
return (return_dict, "already")
except Exception as e:
logging.error("""Exception on object {0} :
{1}
""".format(dict(row), e))
# TODO add row to failed.csv
return (dict(row), "failed")
# Try to use DTO function
try:
new_dto = dtos[variable_subtype](**row)
# Try to use creation function
try:
new_object = creation_func[variable_subtype](body=new_dto)
new_object = get_func[variable_subtype](
uri = new_object["result"][0]
)
# TODO make this a func to extract and normalize result object's attributes
v = vars(new_object["result"])
return_dict = {
col.replace("_", "", 1): v[col]
for col in v
if "_" in col
}
logging.info("Object created: {}\n".format(return_dict))
# TODO add row to created.csv
return (return_dict, "created")
except Exception as e:
# Catch 'URI already exists' exception separately
if("URI already exists" in str(e)):
old_object = get_func[variable_subtype](
uri = row['uri']
)
v = vars(old_object["result"])
return_dict = {
col.replace("_", "", 1): v[col]
for col in v
if "_" in col
}
logging.info(
"""Object {0} at row {1} couldn't be created as this URI already exists.
That object was skipped and will appear in the "skipped.csv" file.
The object with that URI will be used instead : {2}
For the exact error see the following:
ValueError: {3}\n""".format(dict(row), index, return_dict, e)
)
# TODO add row to already_existed.csv
return (return_dict, "already")
else:
logging.error("""Exception on object{0} :
{1}
""".format(dict(row), e))
# TODO add row to failed.csv
return (dict(row), "failed")
except Exception as e:
logging.error("""Exception on object{0} :
{1}
""".format(dict(row), e))
# TODO add row to failed.csv
return (dict(row), "failed")
# %%
def create_sensor(python_client,sensor):
device_api = opensilexClientToolsPython.DevicesApi(python_client)
sensorTosend = opensilexClientToolsPython.DeviceCreationDTO(