-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathschema_generation.py
More file actions
5985 lines (5152 loc) · 227 KB
/
schema_generation.py
File metadata and controls
5985 lines (5152 loc) · 227 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
import json
import multiprocessing
import os
import pathlib
import re
import time
import urllib.request
from copy import deepcopy
from dataclasses import asdict, dataclass, field
from enum import Enum
from inspect import isfunction
from itertools import product
from logging import Logger
from string import whitespace
from typing import (
TYPE_CHECKING,
AbstractSet,
Any,
Callable,
Iterable,
List,
Literal,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
from deprecated import deprecated
from synapseclient import Synapse
from synapseclient.core.typing_utils import DataFrame as DATA_FRAME_TYPE
from synapseclient.core.typing_utils import np, nx
def check_curator_imports() -> None:
"""Attempts to import all necessary packages for the Curator extension.
Raises:
ImportError: If one or more Curator packages are not installed.
"""
try:
import inflection # noqa: F401
import networkx # noqa: F401
import pandarallel # noqa: F401
import pandas # noqa: F401
import rdflib # noqa: F401
except ImportError as exception:
msg = (
"One or more packages needed for the Curator extension are not installed. "
"Please install using 'pip install --upgrade 'synapseclient[curator]'"
)
raise ImportError(msg) from exception
try:
from dataclasses_json import config, dataclass_json
except ImportError:
# dataclasses_json is an optional dependency only available with curator extra
# Provide dummy implementations to avoid import errors
def dataclass_json(cls):
"""Dummy decorator when dataclasses_json is not installed"""
return cls
def config(**kwargs):
"""Dummy config function when dataclasses_json is not installed"""
return None
if TYPE_CHECKING:
NUMPY_INT_64 = np.int64
MULTI_GRAPH_TYPE = nx.MultiDiGraph
GRAPH_TYPE = nx.Graph
DI_GRAPH_TYPE = nx.DiGraph
else:
NUMPY_INT_64 = object
MULTI_GRAPH_TYPE = object
GRAPH_TYPE = object
DI_GRAPH_TYPE = object
X = TypeVar("X")
BLACKLISTED_CHARS = ["(", ")", ".", " ", "-"]
COMPONENT_NAME_DELIMITER = "#"
COMPONENT_RULES_DELIMITER = "^^"
RULE_DELIMITER = "::"
# Characters display names of nodes that are not allowed
BLACKLISTED_CHARACTERS_NODE_NAMES = ["(", ")", ".", "-"]
# Names of nodes that are used internally
RESERVED_NODE_NAMES = {"entityId"}
DisplayLabelType = Literal["class_label", "display_label"]
EntryType = Literal["class", "property"]
Items = dict[str, Union[str, float, list[str]]]
Property = dict[str, Union[str, float, list, dict]]
TypeDict = dict[str, Union[str, Items]]
AllOf = dict[str, Any]
class ColumnType(Enum):
"""Names of values allowed in the columnType column in datamodel csvs."""
class AtomicColumnType(ColumnType):
"""Column Types that are not lists"""
STRING = "string"
NUMBER = "number"
INTEGER = "integer"
BOOLEAN = "boolean"
class ListColumnType(ColumnType):
"""Column Types that are lists"""
STRING_LIST = "string_list"
INTEGER_LIST = "integer_list"
BOOLEAN_LIST = "boolean_list"
ALL_COLUMN_TYPE_VALUES = [member.value for member in AtomicColumnType] + [
member.value for member in ListColumnType
]
# Translates list types to their atomic type
LIST_TYPE_DICT = {
ListColumnType.STRING_LIST: AtomicColumnType.STRING,
ListColumnType.INTEGER_LIST: AtomicColumnType.INTEGER,
ListColumnType.BOOLEAN_LIST: AtomicColumnType.BOOLEAN,
}
class JSONSchemaFormat(Enum):
"""
Allowed formats by the JSON Schema validator used by Synapse: https://github.com/everit-org/json-schema#format-validators
For descriptions see: https://json-schema.org/understanding-json-schema/reference/type#format
"""
DATE_TIME = "date-time"
EMAIL = "email"
HOSTNAME = "hostname"
IPV4 = "ipv4"
IPV6 = "ipv6"
URI = "uri"
URI_REFERENCE = "uri-reference"
URI_TEMPLATE = "uri-template"
JSON_POINTER = "json-pointer"
DATE = "date"
TIME = "time"
REGEX = "regex"
RELATIVE_JSON_POINTER = "relative-json-pointer"
# TODO: remove: https://sagebionetworks.jira.com/browse/SYNPY-1724
class ValidationRuleName(Enum):
"""Names of validation rules that are used to create JSON Schema"""
LIST = "list"
DATE = "date"
URL = "url"
REGEX = "regex"
IN_RANGE = "inRange"
# TODO: remove: https://sagebionetworks.jira.com/browse/SYNPY-1724
class RegexModule(Enum):
"""This enum are allowed modules for the regex validation rule"""
SEARCH = "search"
MATCH = "match"
# TODO: remove: https://sagebionetworks.jira.com/browse/SYNPY-1724
@dataclass
class ValidationRule:
"""
This class represents a Schematic validation rule to be used for creating JSON Schemas
Attributes:
name: The name of the validation rule
incompatible_rules: Other validation rules this rule can not be paired with
parameters: Parameters for the validation rule that need to be collected for the JSON Schema
"""
name: ValidationRuleName
incompatible_rules: list[ValidationRuleName]
parameters: Optional[list[str]] = None
# TODO: remove: https://sagebionetworks.jira.com/browse/SYNPY-1724
_VALIDATION_RULES = {
"list": ValidationRule(
name=ValidationRuleName.LIST,
incompatible_rules=[],
),
"date": ValidationRule(
name=ValidationRuleName.DATE,
incompatible_rules=[
ValidationRuleName.IN_RANGE,
ValidationRuleName.URL,
],
),
"url": ValidationRule(
name=ValidationRuleName.URL,
incompatible_rules=[
ValidationRuleName.IN_RANGE,
ValidationRuleName.DATE,
],
),
"regex": ValidationRule(
name=ValidationRuleName.REGEX,
incompatible_rules=[
ValidationRuleName.IN_RANGE,
],
parameters=["module", "pattern"],
),
"inRange": ValidationRule(
name=ValidationRuleName.IN_RANGE,
incompatible_rules=[
ValidationRuleName.URL,
ValidationRuleName.DATE,
ValidationRuleName.REGEX,
],
parameters=["minimum", "maximum"],
),
}
@dataclass
class Node:
"""A node in graph from the data model."""
name: Any
"""Name of the node."""
fields: dict
"""Fields of the node"""
def __post_init__(self) -> None:
if "displayName" not in self.fields:
raise ValueError(f"Node: {str(self.name)} missing displayName field")
self.display_name = str(self.fields["displayName"])
def load_json(file_path: str) -> Any:
"""Load json document from file path or url
:arg str file_path: The path of the url doc, could be url or file path
"""
# TODO: Can I swap this to HTTPX instead??
if file_path.startswith("http"):
with urllib.request.urlopen(file_path, timeout=200) as url:
data = json.loads(url.read().decode())
return data
# handle file path
else:
with open(file_path, encoding="utf8") as fle:
data = json.load(fle)
return data
def attr_dict_template(key_name: str) -> dict[str, dict[str, dict]]:
"""Create a single empty attribute_dict template.
Args:
key_name (str): Attribute/node to use as the key in the dict.
Returns:
dict[str, dict[str, dict]]: template single empty attribute_relationships dictionary
"""
return {key_name: {"Relationships": {}}}
def check_allowed_values(
dmr: "DataModelRelationships", entry_id: str, value: Any, relationship: str
) -> None:
"""Checks that the entry is in the allowed values if they exist for the relationship
Args:
dmr: DataModelRelationships, the data model relationships object
entry_id: The id of the entry
value: The value to check
relationship (str): The name of the relationship to check for allowed values
Raises:
ValueError: If the value isn't in the list of allowed values
"""
allowed_values = dmr.get_allowed_values(relationship)
if allowed_values and value not in allowed_values:
msg = f"For entry: '{entry_id}', '{value}' not in allowed values: {allowed_values}"
raise ValueError(msg)
def trim_commas_df(
dataframe: DATA_FRAME_TYPE,
allow_na_values: Optional[bool] = False,
) -> DATA_FRAME_TYPE:
"""Removes empty (trailing) columns and empty rows from pandas dataframe (manifest data).
Args:
dataframe: pandas dataframe with data from manifest file.
allow_na_values (bool, optional): If true, allow pd.NA values in the dataframe
Returns:
df: cleaned-up pandas dataframe.
"""
# remove all columns which have substring "Unnamed" in them
dataframe = dataframe.loc[:, ~dataframe.columns.str.contains("^Unnamed")]
# remove all completely empty rows
dataframe = dataframe.dropna(how="all", axis=0)
if allow_na_values is False:
# Fill in nan cells with empty strings
dataframe.fillna("", inplace=True)
return dataframe
def find_and_convert_ints(
dataframe: DATA_FRAME_TYPE,
) -> tuple[DATA_FRAME_TYPE, DATA_FRAME_TYPE]:
"""
Find strings that represent integers and convert to type int
Args:
dataframe: dataframe with nulls masked as empty strings
Returns:
ints: dataframe with values that were converted to type int
is_int: dataframe with boolean values indicating which cells were converted to type int
"""
from pandarallel import pandarallel
from pandas import DataFrame
from pandas.api.types import is_integer
large_manifest_cutoff_size = 1000
# Find integers stored as strings and replace with entries of type np.int64
if (
dataframe.size < large_manifest_cutoff_size
): # If small manifest, iterate as normal for improved performance
ints = dataframe.map( # type: ignore
lambda cell: convert_ints(cell), na_action="ignore"
).fillna(False)
else: # parallelize iterations for large manifests
pandarallel.initialize(verbose=1)
ints = dataframe.parallel_applymap( # type: ignore
lambda cell: convert_ints(cell), na_action="ignore"
).fillna(False)
# Identify cells converted to integers
is_int = ints.map(is_integer) # type: ignore
assert isinstance(ints, DataFrame)
assert isinstance(is_int, DataFrame)
return ints, is_int
def convert_ints(string: str) -> Union[NUMPY_INT_64, bool]:
"""
Lambda function to convert a string to an integer if possible, otherwise returns False
Args:
string: string to attempt conversion to int
Returns:
string converted to type int if possible, otherwise False
"""
from numpy import int64
if isinstance(string, str) and str.isdigit(string):
return int64(string)
return False
def convert_floats(dataframe: DATA_FRAME_TYPE) -> DATA_FRAME_TYPE:
"""
Convert strings that represent floats to type float
Args:
dataframe: dataframe with nulls masked as empty strings
Returns:
float_df: dataframe with values that were converted to type float. Columns are type object
"""
from pandas import to_numeric
# create a separate copy of the manifest
# before beginning conversions to store float values
float_df = deepcopy(dataframe)
# convert strings to numerical dtype (float) if possible, preserve non-numerical strings
for col in dataframe.columns:
float_df[col] = to_numeric(float_df[col], errors="coerce").astype("object")
# replace values that couldn't be converted to float with the original str values
float_df[col].fillna(dataframe[col][float_df[col].isna()], inplace=True)
return float_df
def get_str_pandas_na_values() -> List[str]:
from pandas._libs.parsers import STR_NA_VALUES # type: ignore
STR_NA_VALUES_FILTERED = deepcopy(STR_NA_VALUES)
try:
STR_NA_VALUES_FILTERED.remove("None")
except KeyError:
pass
return STR_NA_VALUES_FILTERED
def read_csv(
path_or_buffer: str,
keep_default_na: bool = False,
encoding: str = "utf8",
**load_args: Any,
) -> DATA_FRAME_TYPE:
"""
A wrapper around pd.read_csv that filters out "None" from the na_values list.
Args:
path_or_buffer: The path to the file or a buffer containing the file.
keep_default_na: Whether to keep the default na_values list.
encoding: The encoding of the file.
**load_args: Additional arguments to pass to pd.read_csv.
Returns:
pd.DataFrame: The dataframe created from the CSV file or buffer.
"""
from pandas import read_csv as pandas_read_csv
STR_NA_VALUES_FILTERED = get_str_pandas_na_values()
na_values = load_args.pop(
"na_values", STR_NA_VALUES_FILTERED if not keep_default_na else None
)
return pandas_read_csv( # type: ignore
path_or_buffer,
na_values=na_values,
keep_default_na=keep_default_na,
encoding=encoding,
**load_args,
)
def load_df(
file_path: str,
preserve_raw_input: bool = True,
data_model: bool = False,
allow_na_values: bool = False,
**load_args: Any,
) -> DATA_FRAME_TYPE:
"""
Universal function to load CSVs and return DataFrames
Parses string entries to convert as appropriate to type int, float, and pandas timestamp
Pandarallel is used for type inference for large manifests to improve performance
Args:
file_path (str): path of csv to open
preserve_raw_input (bool, optional): If false, convert cell datatypes to an inferred type
data_model (bool, optional): bool, indicates if importing a data model
allow_na_values (bool, optional): If true, allow pd.NA values in the dataframe
**load_args(dict): dict of key value pairs to be passed to the pd.read_csv function
Raises:
ValueError: When pd.read_csv on the file path doesn't return as dataframe
Returns:
pd.DataFrame: a processed dataframe for manifests or unprocessed df for data models and
where indicated
"""
from pandas import DataFrame
# Read CSV to df as type specified in kwargs
org_df = read_csv(file_path, encoding="utf8", **load_args) # type: ignore
if not isinstance(org_df, DataFrame):
raise ValueError(
(
"Pandas did not return a dataframe. "
"Pandas will return a TextFileReader if chunksize parameter is used."
)
)
# only trim if not data model csv
if not data_model:
org_df = trim_commas_df(org_df, allow_na_values=allow_na_values)
if preserve_raw_input:
return org_df
ints, is_int = find_and_convert_ints(org_df)
float_df = convert_floats(org_df)
# Store values that were converted to type int in the final dataframe
processed_df = float_df.mask(is_int, other=ints)
return processed_df
class DataModelParser:
"""
This class takes in a path to a data model and will convert it to an
attributes:relationship dictionarythat can then be further converted into a graph data model.
Other data model types may be added in the future.
"""
def __init__(self, path_to_data_model: str, logger: Logger) -> None:
"""
Args:
path_to_data_model, str: path to data model.
"""
self.path_to_data_model = path_to_data_model
self.model_type = self.get_model_type()
self.logger = logger
def get_model_type(self) -> str:
"""
Parses the path to the data model to extract the extension and determine the
data model type.
Args:
path_to_data_model, str: path to data model
Returns:
str: uppercase, data model file extension.
Note: Consider moving this to Utils.
"""
return pathlib.Path(self.path_to_data_model).suffix.replace(".", "").upper()
def parse_model(self) -> dict[str, dict[str, Any]]:
"""Given a data model type, instantiate and call the appropriate data model parser.
Returns:
model_dict, dict:
{Attribute Display Name: {
Relationships: {
CSV Header: Value}}}
Raises:
Value Error if an incorrect model type is passed.
Note: in future will add base model parsing in this step too and extend new model
off base model.
"""
# Call appropriate data model parser and return parsed model.
if self.model_type == "CSV":
csv_parser = DataModelCSVParser(logger=self.logger)
model_dict = csv_parser.parse_csv_model(self.path_to_data_model)
elif self.model_type == "JSONLD":
jsonld_parser = DataModelJSONLDParser()
model_dict = jsonld_parser.parse_jsonld_model(self.path_to_data_model)
else:
raise ValueError(
(
"Only data models of type CSV or JSONLD are accepted, "
"you provided a model type "
f"{self.model_type}, please resubmit in the proper format."
)
)
return model_dict
class DataModelCSVParser:
"""DataModelCSVParser"""
def __init__(self, logger: Optional[Any] = None) -> None:
self.logger = logger
# Instantiate DataModelRelationships
self.dmr = DataModelRelationships()
# Load relationships dictionary.
self.rel_dict = self.dmr.define_data_model_relationships()
# Get edge relationships
self.edge_relationships_dictionary = self.dmr.retrieve_rel_headers_dict(
edge=True
)
# Load required csv headers
self.required_headers = self.dmr.define_required_csv_headers()
# Get the type for each value that needs to be submitted.
# using csv_headers as keys to match required_headers/relationship_types
self.rel_val_types = {
value["csv_header"]: value["type"]
for value in self.rel_dict.values()
if "type" in value
}
def check_schema_definition(self, model_df: DATA_FRAME_TYPE) -> None:
"""Checks if a schema definition data frame contains the right required headers.
Args:
model_df: a pandas dataframe containing schema definition; see example here:
https://docs.google.com/spreadsheets/d/1J2brhqO4kpeHIkNytzlqrdIiRanXDr6KD2hqjOTC9hs/edit#gid=0
Raises: Exception if model_df does not have the required headers.
"""
if "Requires" in list(model_df.columns) or "Requires Component" in list(
model_df.columns
):
raise ValueError(
"The input CSV schema file contains the 'Requires' and/or the 'Requires "
"Component' column headers. These columns were renamed to 'DependsOn' and "
"'DependsOn Component', respectively. Switch to the new column names."
)
if not set(self.required_headers).issubset(set(list(model_df.columns))):
raise ValueError(
f"Schema extension headers: {set(list(model_df.columns))} "
f"do not match required schema headers: {self.required_headers}"
)
if set(self.required_headers).issubset(set(list(model_df.columns))):
self.logger.debug("Schema definition csv ready for processing!")
def parse_entry(self, attr: dict, relationship: str) -> Any:
"""Parse attr entry baed on type
Args:
attr, dict: single row of a csv model in dict form, where only the required
headers are keys. Values are the entries under each header.
relationship, str: one of the header relationships to parse the entry of.
Returns:
parsed_rel_entry, any: parsed entry for downstream processing based on the entry type.
"""
rel_val_type = self.rel_val_types[relationship]
# Parse entry based on type:
# If the entry should be preserved as a bool dont convert to str.
if rel_val_type is bool and isinstance(attr[relationship], bool):
parsed_rel_entry = attr[relationship]
# Move strings to list if they are comma separated. Schema order is preserved,
# remove any empty strings added by trailing commas
elif rel_val_type is list:
parsed_rel_entry = attr[relationship].strip().split(",")
parsed_rel_entry = [r.strip() for r in parsed_rel_entry if r]
# Convert value string if dictated by rel_val_type, strip whitespace.
elif rel_val_type is str:
parsed_rel_entry = str(attr[relationship]).strip()
else:
raise ValueError(
(
"The value type recorded for this relationship, is not currently "
"supported for CSV parsing. Please check with your DCC."
)
)
return parsed_rel_entry
def gather_csv_attributes_relationships(
self, model_df: DATA_FRAME_TYPE
) -> dict[str, dict[str, Any]]:
"""Parse csv into a attributes:relationshps dictionary to be used in downstream efforts.
Args:
model_df: pd.DataFrame, data model that has been loaded into pandas DataFrame.
Returns:
attr_rel_dictionary: dict,
{Attribute Display Name: {
Relationships: {
CSV Header: Value}}}
"""
from pandas import isnull
# Check csv schema follows expectations.
self.check_schema_definition(model_df)
# get attributes from Attribute column
attributes = model_df.to_dict("records")
# Check for presence of optional columns
model_includes_column_type = "columnType" in model_df.columns
model_includes_format = "Format" in model_df.columns
model_includes_pattern = "Pattern" in model_df.columns
# Build attribute/relationship dictionary
relationship_types = self.required_headers
attr_rel_dictionary = {}
for attr in attributes:
attribute_name = attr["Attribute"]
# Add attribute to dictionary
attr_rel_dictionary.update(attr_dict_template(attribute_name))
# Fill in relationship info for each attribute.
for relationship in relationship_types:
if not isnull(attr[relationship]):
parsed_rel_entry = self.parse_entry(
attr=attr, relationship=relationship
)
attr_rel_dictionary[attribute_name]["Relationships"].update(
{relationship: parsed_rel_entry}
)
is_template_dict = self.parse_is_template(attr)
attr_rel_dictionary[attribute_name]["Relationships"].update(
is_template_dict
)
if model_includes_column_type:
column_type_dict = self.parse_column_type(attr)
attr_rel_dictionary[attribute_name]["Relationships"].update(
column_type_dict
)
if model_includes_format:
format_dict = self.parse_format(attr)
attr_rel_dictionary[attribute_name]["Relationships"].update(format_dict)
if "Minimum" in model_df.columns:
minimum_dict = self.parse_minimum_maximum(attr, "Minimum")
attr_rel_dictionary[attribute_name]["Relationships"].update(
minimum_dict
)
if "Maximum" in model_df.columns:
maximum_dict = self.parse_minimum_maximum(attr, "Maximum")
attr_rel_dictionary[attribute_name]["Relationships"].update(
maximum_dict
)
if model_includes_pattern:
pattern_dict = self.parse_pattern(attr)
attr_rel_dictionary[attribute_name]["Relationships"].update(
pattern_dict
)
return attr_rel_dictionary
def parse_column_type(self, attr: dict) -> dict:
"""Parse the attribute type for a given attribute.
Args:
attr (dict): The attribute dictionary.
Returns:
dict: A dictionary containing the parsed column type information if present
else an empty dict
"""
from pandas import isna
column_type = attr.get("columnType")
# If no column type specified, we don't want to add any entry to the dictionary
if isna(column_type):
return {}
# column types should be case agnostic and valid
column_type = str(column_type).strip().lower()
check_allowed_values(
self.dmr,
entry_id=attr["Source"],
value=column_type,
relationship="columnType",
)
return {"ColumnType": column_type}
def parse_minimum_maximum(
self, attr: dict, relationship: str
) -> dict[str, Union[float, int]]:
"""Parse minimum/maximum value for a given attribute.
Args:
attr: single row of a csv model in dict form, where only the required
headers are keys. Values are the entries under each header.
relationship: either "Minimum" or "Maximum"
Returns:
dict[str, Union[float, int]]: A dictionary containing the parsed minimum/maximum value
if present else an empty dict
"""
from numbers import Number
from pandas import isna
value = attr.get(relationship)
# If maximum and minimum are not specified, we don't want to add any entry to the dictionary
if isna(value):
return {}
# Validate that the value is numeric
if not isinstance(value, Number) or isinstance(value, bool):
raise ValueError(
f"The {relationship} value: {attr[relationship]} is not numeric, "
"please correct this value in the data model."
)
# if both maximum and minimum are present, check if maximum > minimum
if attr.get("Minimum") and attr.get("Maximum"):
maximum = attr.get("Maximum")
minimum = attr.get("Minimum")
if maximum < minimum:
raise ValueError(
f"The Maximum value: {maximum} must be greater than the Minimum value: {minimum}"
)
return {relationship: value}
def parse_format(self, attribute_dict: dict) -> dict[str, str]:
"""Finds the format value if it exists and returns it as a dictionary.
Args:
attribute_dict: The attribute dictionary.
Returns:
A dictionary containing the format value if it exists
else an empty dict
"""
from pandas import isna
format_value = attribute_dict.get("Format")
if isna(format_value):
return {}
format_string = str(format_value).strip().lower()
check_allowed_values(
self.dmr,
entry_id=attribute_dict["Format"],
value=format_string,
relationship="format",
)
return {"Format": format_string}
def parse_pattern(self, attribute_dict: dict) -> dict[str, str]:
"""Finds the pattern value if it exists and returns it as a dictionary.
Args:
attribute_dict: The attribute dictionary.
Returns:
A dictionary containing the pattern value if it exists
else an empty dict
"""
from pandas import isna
pattern_value = attribute_dict.get("Pattern")
if isna(pattern_value):
return {}
pattern_string = str(pattern_value).strip()
return {"Pattern": pattern_string}
def parse_csv_model(
self,
path_to_data_model: str,
) -> dict[str, dict[str, Any]]:
"""Load csv data model and parse into an attributes:relationships dictionary
Args:
path_to_data_model, str: path to data model
Returns:
model_dict, dict:{Attribute Display Name: {
Relationships: {
CSV Header: Value}}}
"""
# Load the csv data model to DF
model_df = load_df(file_path=path_to_data_model, data_model=True)
# Gather info from the model
model_dict = self.gather_csv_attributes_relationships(model_df)
return model_dict
def parse_is_template(self, attribute_dict: dict) -> dict[str, bool]:
"""Parse the IsTemplate value for a given attribute.
Args:
attribute_dict: The attribute dictionary.
Returns:
dict: A dictionary containing the parsed IsTemplate value.
Raises:
ValueError: If the IsTemplate value is not a boolean.
"""
from pandas import isna
is_template_value = attribute_dict.get("IsTemplate")
if isna(is_template_value):
template_value = False
elif isinstance(is_template_value, str):
if is_template_value.lower() == "true":
template_value = True
else:
template_value = False
else:
try:
template_value = bool(is_template_value)
except ValueError as exception:
raise ValueError(
f"The IsTemplate value: {is_template_value} is not boolean, "
"please correct this value in the data model."
) from exception
return {"IsTemplate": template_value}
class DataModelJSONLDParser:
"""DataModelJSONLDParser"""
def __init__(
self,
) -> None:
# Instantiate DataModelRelationships
self.dmr = DataModelRelationships()
# Load relationships dictionary.
self.rel_dict = self.dmr.define_data_model_relationships()
def parse_jsonld_dicts(
self, rel_entry: dict[str, str]
) -> Union[str, dict[str, str]]:
"""Parse incoming JSONLD dictionaries, only supported dictionaries are non-edge
dictionaries.
Note:
The only two dictionaries we expect are a single entry dictionary containing
id information and dictionaries where the key is the attribute label
(and it is expected to stay as the label). The individual rules per component are not
attached to nodes but rather parsed later in validation rule parsing.
So the keys do not need to be converted to display names.
Args:
rel_entry, Any: Given a single entry and relationship in a JSONLD data model,
the recorded value
Returns:
str, the JSONLD entry ID
dict, JSONLD dictionary entry returned.
"""
# Retrieve ID from a dictionary recording the ID
if set(rel_entry.keys()) == {"@id"}:
parsed_rel_entry: Union[str, dict[str, str]] = rel_entry["@id"]
# Parse any remaining dictionaries
else:
parsed_rel_entry = rel_entry
return parsed_rel_entry
def parse_entry(
self,
rel_entry: Any,
id_jsonld_key: str,
model_jsonld: list[dict],
) -> Any:
"""Parse an input entry based on certain attributes
Args:
rel_entry: Given a single entry and relationship in a JSONLD data model,
the recorded value
id_jsonld_key: str, the jsonld key for id
model_jsonld: list[dict], list of dictionaries, each dictionary is an entry
in the jsonld data model
Returns:
Any: n entry that has been parsed base on its input type and
characteristics.
"""
# Parse dictionary entries
if isinstance(rel_entry, dict):
parsed_rel_entry: Any = self.parse_jsonld_dicts(rel_entry)
# Parse list of dictionaries to make a list of entries with context stripped (will update
# this section when contexts added.)
elif isinstance(rel_entry, list) and isinstance(rel_entry[0], dict):
parsed_rel_entry = self.convert_entry_to_dn_label(
[r[id_jsonld_key].split(":")[1] for r in rel_entry], model_jsonld
)
# Strip context from string and convert true/false to bool
elif isinstance(rel_entry, str):
# Remove contexts and treat strings as appropriate.
if ":" in rel_entry and "http:" not in rel_entry:
parsed_rel_entry = rel_entry.split(":")[1]
# Convert true/false strings to boolean
if parsed_rel_entry.lower() == "true":
parsed_rel_entry = True
elif parsed_rel_entry.lower == "false":
parsed_rel_entry = False
else:
parsed_rel_entry = self.convert_entry_to_dn_label(
rel_entry, model_jsonld
)
# For anything else get that
else:
parsed_rel_entry = self.convert_entry_to_dn_label(rel_entry, model_jsonld)
return parsed_rel_entry
def label_to_dn_dict(self, model_jsonld: list[dict]) -> dict:
"""
Generate a dictionary of labels to display name, so can easily look up
display names using the label.
Args:
model_jsonld: list of dictionaries, each dictionary is an entry in the jsonld data model
Returns:
dn_label_dict: dict of model labels to display names
"""
jsonld_keys_to_extract = ["label", "displayName"]
label_jsonld_key, dn_jsonld_key = [
self.rel_dict[key]["jsonld_key"] for key in jsonld_keys_to_extract
]
dn_label_dict = {}
for entry in model_jsonld:
dn_label_dict[entry[label_jsonld_key]] = entry[dn_jsonld_key]
return dn_label_dict
def convert_entry_to_dn_label(
self, parsed_rel_entry: Union[str, list], model_jsonld: list[dict]