-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdictionary.py
More file actions
1525 lines (1283 loc) · 50.5 KB
/
dictionary.py
File metadata and controls
1525 lines (1283 loc) · 50.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
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
######################################################################################
# Copyright (c) 2023-2025 Orange. All rights reserved. #
# This software is distributed under the BSD 3-Clause-clear License, the text of #
# which is available at https://spdx.org/licenses/BSD-3-Clause-Clear.html or #
# see the "LICENSE.md" file for more details. #
######################################################################################
"""Classes to manipulate Khiops Dictionary files
.. note::
To have a complete illustration of the access to the information of all classes in
this module look at their ``write`` methods which write them in Khiops Dictionary
file format (``.kdic``).
"""
import io
import os
import re
import warnings
import khiops.core.internals.filesystems as fs
from khiops.core import api
from khiops.core.exceptions import KhiopsJSONError
from khiops.core.internals.common import (
deprecation_message,
is_string_like,
type_error_message,
)
from khiops.core.internals.io import (
KhiopsJSONObject,
KhiopsOutputWriter,
flexible_json_load,
)
from khiops.core.internals.runner import get_runner
def _format_name(name):
"""Formats a name of a dictionary or variable to a valid ``.kdic`` file identifier
Returns unchanged the names that contain only "identifier" characters:
- underscore
- alphanumeric
Otherwise, it returns the name between backquoted (backquotes within are doubled)
"""
# Check that the type of name is string or bytes
if not is_string_like(name):
raise TypeError(type_error_message("name", name, "string-like"))
# Check if the name is an identifier
# Python isalnum is not used because of utf-8 encoding (accentuated chars
# are considered alphanumeric)
# Return original name if is an identifier, otherwise between backquotes
identifier_pattern = r"^[a-zA-Z][a-zA-Z0-9_]*"
str_identifier_regex = re.compile(identifier_pattern)
bytes_identifier_regex = re.compile(bytes(identifier_pattern, encoding="ascii"))
if isinstance(name, str):
if str_identifier_regex.fullmatch(name) is not None:
formatted_name = name
else:
formatted_name = "`" + name.replace("`", "``") + "`"
else:
assert isinstance(name, bytes)
if bytes_identifier_regex.fullmatch(name) is not None:
formatted_name = name
else:
formatted_name = b"`" + name.replace(b"`", b"``") + b"`"
return formatted_name
def _quote_value(value):
"""Double-quotes a string
Categorical, Text and metadata values are quoted with this method.
"""
if isinstance(value, str):
quoted_value = '"' + value.replace('"', '""') + '"'
else:
assert isinstance(value, bytes)
quoted_value = b'"' + value.replace(b'"', b'""') + b'"'
return quoted_value
class DictionaryDomain(KhiopsJSONObject):
"""Main class containing the information of a Khiops dictionary file
A DictionaryDomainain is a collection of `Dictionary` objects. These dictionaries
usually represent either a database schema or a predictor model.
Parameters
----------
json_data : dict, optional
Python dictionary representing the data of a Khiops Dictionary JSON file. If not
specified it returns an empty instance.
.. note::
Prefer the `.read_dictionary_file` function from the core API to obtain an
instance of this class from a Khiops Dictionary file (``kdic`` or
``kdicj``).
Attributes
----------
tool : str
Name of the Khiops tool that generated the dictionary file.
version : str
Version of the Khiops tool that generated the dictionary file.
dictionaries : list of `Dictionary`
The domain's dictionaries.
"""
def __init__(self, json_data=None):
"""See class docstring"""
# Check the type of json_data
if json_data is not None and not isinstance(json_data, dict):
raise TypeError(type_error_message("json_data", json_data, dict))
# Initialize base attributes
super().__init__(json_data=json_data)
# Transform to an empty dictionary if json_data is not specified
if json_data is None:
json_data = {}
# Otherwise check if the tool field is the proper one
else:
if self.tool != "Khiops Dictionary":
raise KhiopsJSONError(
f"'tool' value must be 'Khiops Dictionary' not '{self.tool}'"
)
# Initialize the Khiops dictionary objects
self.dictionaries = []
self._dictionaries_by_name = {}
for json_dictionary in json_data.get("dictionaries", []):
dictionary = Dictionary(json_dictionary)
self.add_dictionary(dictionary)
def __repr__(self):
"""Returns a human readable string representation"""
if len(self.dictionaries) == 0:
return "Dictionaries ()"
if len(self.dictionaries) == 1:
return f"Dictionaries ({self.dictionaries[0].name})"
return f"Dictionaries ({self.dictionaries[0].name},...)"
def __str__(self):
stream = io.BytesIO()
writer = KhiopsOutputWriter(stream)
self.write(writer)
return str(stream.getvalue(), encoding="utf8", errors="replace")
def copy(self):
"""Copies this domain instance
Returns
-------
`DictionaryDomain`
A copy of this instance.
"""
dictionary_domain_copy = DictionaryDomain()
dictionary_domain_copy.tool = self.tool
dictionary_domain_copy.version = self.version
dictionary_domain_copy.khiops_encoding = self.khiops_encoding
dictionary_domain_copy.ansi_chars = self.ansi_chars
dictionary_domain_copy.colliding_utf8_chars = self.colliding_utf8_chars
for dictionary in self.dictionaries:
dictionary_domain_copy.add_dictionary(dictionary.copy())
return dictionary_domain_copy
def get_dictionary(self, dictionary_name):
"""Returns the specified dictionary
Parameters
----------
dictionary_name : str
Name of the dictionary.
Returns
-------
`Dictionary`
The specified dictionary.
Raises
------
`KeyError`
If no dictionary with the specified name exist.
"""
return self._dictionaries_by_name[dictionary_name]
def add_dictionary(self, dictionary):
"""Adds a dictionary to this domain
Parameters
----------
dictionary : `DictionaryDomain`
The dictionary to be added.
Raises
------
`TypeError`
If ``dictionary`` is not of type ``Dictionary``.
"""
if not isinstance(dictionary, Dictionary):
raise TypeError(type_error_message("dictionary", dictionary, Dictionary))
self.dictionaries.append(dictionary)
self._dictionaries_by_name[dictionary.name] = dictionary
def remove_dictionary(self, dictionary_name):
"""Removes a dictionary from the domain
Returns
-------
`Dictionary`
The removed dictionary.
Raises
------
`KeyError`
If no dictionary with the specified name exists.
"""
dictionary = self._dictionaries_by_name.pop(dictionary_name)
self.dictionaries.remove(dictionary)
return dictionary
def extract_data_paths(self, source_dictionary_name):
"""Extracts the data paths for a dictionary in a multi-table schema
See :doc:`/multi_table_primer` for more details about data paths.
Parameters
----------
source_dictionary_name : str
Name of a dictionary.
Returns
-------
list of str
The additional data paths for the secondary tables of the specified
dictionary.
"""
# List of entity names found in the exploration of _extract_data_paths
entity_dictionary_names = []
# List of data paths found in the exploration of _extract_data_paths
data_paths = []
def _extract_data_paths(
current_dictionary, current_data_path, current_dictionary_alias=None
):
"""Builds the path for secondary tables and updates the entity list
`current_dictionary_alias` contains:
- in the traversal, the name of the dictionary as it was named by
the variable that referenced it;
- or, otherwise, the name of an external dictionary (for Entity tables).
"""
# Update the data paths
if current_dictionary_alias:
current_data_path.append(current_dictionary_alias)
else:
current_data_path.append(current_dictionary.name)
data_paths.append(current_data_path)
# Analyze variables to extract additional data paths
for variable in current_dictionary.variables:
if variable.is_relational():
# Case of a table: Deep-first exploration of the referenced dicts.
# Explore only non rule tables
if variable.rule == "" and variable.variable_block is None:
_extract_data_paths(
self.get_dictionary(variable.object_type),
current_data_path.copy(),
variable.name,
)
# Case of an entity: update the list of unique entity dictionaries
elif variable.is_reference_rule():
if variable.object_type not in entity_dictionary_names:
entity_dictionary_names.append(variable.object_type)
# == End of inner function _extract_data_paths ==
# Extract all the data paths from the source dictionary
source_dictionary = self.get_dictionary(source_dictionary_name)
_extract_data_paths(source_dictionary, [])
# Remove the source dictionary from the found data paths
for i, data_path in enumerate(data_paths):
data_paths[i] = data_path[1:]
# Remove source dictionary from the entity list
if source_dictionary.name in entity_dictionary_names:
entity_dictionary_names.remove(source_dictionary.name)
# Extract the data paths recursively for the entity dictionaries found during
# the first extraction
# Recall that _extract_data_paths modifies the 'entity_dictionary_names' list;
# that's why we loop with a 'while' statement
name_index = 0
while name_index < len(entity_dictionary_names):
entity_dictionary_name = entity_dictionary_names[name_index]
entity_dictionary = self.get_dictionary(entity_dictionary_name)
name_index += 1
# Provide custom dictionary alias for Entity tables
_extract_data_paths(entity_dictionary, [], f"/{entity_dictionary.name}")
# Remove first data path (that of the source dictionary) before returning
return ["/".join(data_path) for data_path in data_paths[1:]]
def get_dictionary_at_data_path(self, data_path):
"""Returns the dictionary name for the specified data path
Parameters
----------
data_path : str
A data path for the specified table. Usually the output of
`extract_data_paths`.
Returns
-------
`Dictionary`
The dictionary object pointed by this data path.
Raises
------
`ValueError`
If the path is not found.
"""
# If data_path includes "`" and starts with an existing dictionary,
# assume legacy data path
if "`" in data_path:
data_path_parts = data_path.split("`")
source_dictionary_name = data_path_parts[0]
if any(kdic.name == source_dictionary_name for kdic in self.dictionaries):
warnings.warn(
deprecation_message(
"'`'-based dictionary data path convention",
"11.0.1",
replacement="'/'-based dictionary data path convention",
quote=False,
)
)
return self._get_dictionary_at_data_path_legacy(data_path)
return self._get_dictionary_at_data_path(data_path)
def _get_dictionary_at_data_path_legacy(self, data_path):
# Legacy data-path convention support
data_path_parts = data_path.split("`")
source_dictionary_name = data_path_parts[0]
try:
dictionary = self.get_dictionary(source_dictionary_name)
except KeyError as error:
raise ValueError(
f"Source dictionary not found: '{source_dictionary_name}'"
) from error
for table_variable_name in data_path_parts[1:]:
try:
table_variable = dictionary.get_variable(table_variable_name)
except KeyError as error:
raise ValueError(
f"Table variable '{table_variable_name}' in data path not found"
) from error
if table_variable.type not in ["Table", "Entity"]:
raise ValueError(
f"Table variable '{table_variable_name}' "
f"in data path is of type '{table_variable.type}'"
)
try:
dictionary = self.get_dictionary(table_variable.object_type)
except KeyError as error:
raise ValueError(
f"Table variable '{table_variable_name}' in data path "
f"points to unknown dictionary '{table_variable.object_type}'"
) from error
return dictionary
def _get_dictionary_at_data_path(self, data_path):
# Obtain the parts of the data path
data_path_parts = data_path.lstrip("/").split("/")
# Attempt to get the first dictionary from the data path:
# - either it is found as such,
# - or it is a Table or Entity variable whose table needs to be looked-up
first_table_variable_name = data_path_parts[0]
try:
dictionary = self.get_dictionary(first_table_variable_name)
except KeyError as error:
for a_dictionary in self.dictionaries:
try:
table_variable = a_dictionary.get_variable(
first_table_variable_name
)
if table_variable.type not in ["Table", "Entity"]:
raise ValueError from error
dictionary = self.get_dictionary(table_variable.object_type)
break
except (KeyError, ValueError):
continue
else:
raise ValueError(
f"Dictionary not found in data path: '{data_path}'"
) from error
for table_variable_name in data_path_parts[1:]:
try:
table_variable = dictionary.get_variable(table_variable_name)
except KeyError as error:
raise ValueError(
f"Table variable '{table_variable_name}' in data path not found"
) from error
if table_variable.type not in ["Table", "Entity"]:
raise ValueError(
f"Table variable '{table_variable_name}' "
f"in data path is of type '{table_variable.type}'"
)
try:
dictionary = self.get_dictionary(table_variable.object_type)
except KeyError as error:
raise ValueError(
f"Table variable '{table_variable_name}' in data path "
f"points to unknown dictionary '{table_variable.object_type}'"
) from error
return dictionary
def export_khiops_dictionary_file(self, kdic_file_path):
"""Exports the domain in ``.kdic`` format
Parameters
----------
kdic_file_path : str
Path of the output dictionary file (``.kdic``).
"""
with io.BytesIO() as kdic_contents_stream:
kdic_file_writer = self.create_output_file_writer(kdic_contents_stream)
self.write(kdic_file_writer)
fs.write(kdic_file_path, kdic_contents_stream.getvalue())
def write(self, stream_or_writer):
"""Writes the domain to a file writer in ``.kdic`` format
Parameters
----------
stream_or_writer : `io.IOBase` or `.KhiopsOutputWriter`
Output stream or writer.
"""
if isinstance(stream_or_writer, io.IOBase):
writer = self.create_output_file_writer(stream_or_writer)
elif isinstance(stream_or_writer, KhiopsOutputWriter):
writer = stream_or_writer
else:
raise TypeError(
type_error_message(
"stream_or_writer",
stream_or_writer,
io.IOBase,
KhiopsOutputWriter,
)
)
writer.write("#Khiops ")
writer.writeln(self.version)
for dictionary in self.dictionaries:
dictionary.write(writer)
def read_dictionary_file(dictionary_file_path):
"""Reads a Khiops dictionary file
Parameters
----------
dictionary_file : str
Path of the file to be imported. The file can be either Khiops Dictionary
(extension ``kdic``) or Khiops JSON Dictionary (extension ``.json`` or
``.kdicj``).
Returns
-------
`.DictionaryDomain`
An dictionary domain representing the information in the dictionary file.
Raises
------
`ValueError`
When the file has an extension other than ``.kdic``, ``.kdicj`` or ``.json``.
Examples
--------
See the following functions of the ``samples.py`` documentation script:
- `samples.export_dictionary_files()`
- `samples.train_predictor_with_cross_validation()`
- `samples.multiple_train_predictor()`
- `samples.deploy_model_expert()`
"""
# Check the extension of the input dictionary file
extension = os.path.splitext(dictionary_file_path)[1].lower()
if extension not in [".kdic", ".kdicj", ".json"]:
raise ValueError(
f"Input file must have extension 'kdic', 'kdicj' or 'json'."
f"It has extension: '{extension}'."
)
# Import dictionary file: Translate to JSON first if it is 'kdic'
if extension == ".kdic":
# Create a temporary file
tmp_dictionary_file_path = get_runner().create_temp_file(
"_read_dictionary_file_", ".kdicj"
)
# Transform the .kdic file to .kdicj (JSON)
api.export_dictionary_as_json(dictionary_file_path, tmp_dictionary_file_path)
json_dictionary_file_path = tmp_dictionary_file_path
else:
json_dictionary_file_path = dictionary_file_path
# Read the JSON dictionary file into a dictionary domain object
domain = DictionaryDomain(json_data=flexible_json_load(json_dictionary_file_path))
# Clean the temporary file if the input file was .kdic
if extension == ".kdic":
fs.remove(tmp_dictionary_file_path)
return domain
class Dictionary:
"""A Khiops Dictionary
A Khiops Dictionary is a description of a table transformation. Common uses in the
Khiops framework are :
- Describing the schema of an input table: In this case it is the identity
transformation of the table(s).
- Describing a predictor (classifier or regressor): In this case it is the
transformation between the original table(s) and the prediction values or
probabilities.
Parameters
----------
json_data : dict, optional
Python dictionary representing an element of the list at the ``dictionaries``
field of a Khiops Dictionary JSON file. If not specified returns an empty
instance.
Attributes
----------
name : str
Dictionary name.
label : str
Dictionary label/comment.
root : bool
True if the dictionary is the root of an dictionary hierarchy.
key : list of str
Names of the key variables.
meta_data : `MetaData`
MetaData object of the dictionary.
variables : list of `Variable`
The dictionary variables.
variable_blocks : list of `VariableBlock`
The dictionary variable blocks.
"""
def __init__(self, json_data=None):
"""See class docstring"""
# Check the type of json_data
if json_data is not None and not isinstance(json_data, dict):
raise TypeError(type_error_message("json_data", json_data, dict))
# Transform to an empty dictionary if json_data is not specified
if json_data is None:
json_data = {}
# Otherwise check the type of the json data and its integrity
else:
if "name" not in json_data:
raise KhiopsJSONError("'name' key not found")
# Initialize main attributes
self.name = json_data.get("name", "")
self.label = json_data.get("label", "")
self.root = json_data.get("root", False)
# Initialize names of key variable
self.key = json_data.get("key", [])
# Initialize the metadata
json_meta_data = json_data.get("metaData")
if json_meta_data is None:
self.meta_data = MetaData()
else:
self.meta_data = MetaData(json_meta_data)
# Initialize variables and blocks
self.variables = []
self.variable_blocks = []
self._variables_by_name = {}
self._variable_blocks_by_name = {}
for json_variable in json_data.get("variables", []):
# Case of a simple variable
if "name" in json_variable:
variable = Variable(json_variable)
self.add_variable(variable)
# Case of a variable block
elif "blockName" in json_variable:
variable_block = VariableBlock(json_variable)
self.add_variable_block(variable_block)
else:
raise KhiopsJSONError(
f"Variable/block name not found. JSON data: {json_variable}"
)
def __repr__(self):
"""Returns a human readable string representation"""
return f"Dictionary ({self.name})"
def __str__(self):
stream = io.BytesIO()
writer = KhiopsOutputWriter(stream)
self.write(writer)
return str(stream.getvalue(), encoding="utf8", errors="replace")
def copy(self):
"""Returns a copy of this instance
Returns
-------
`Dictionary`
A copy of this instance.
"""
# Create an empty dictionary
dictionary_copy = Dictionary()
# Copy dictionary main features
dictionary_copy.name = self.name
dictionary_copy.label = self.label
dictionary_copy.root = self.root
dictionary_copy.key = self.key.copy()
dictionary_copy.meta_data = self.meta_data.copy()
# Copy variables
i = 0
while i < len(self.variables):
variable = self.variables[i]
# Simple variable case
if variable.variable_block is None:
variable_copy = variable.copy()
dictionary_copy.add_variable(variable_copy)
i += 1
# Variable block case
else:
variable_block = variable.variable_block
variable_block_copy = VariableBlock()
variable_block_copy.name = variable.variable_block.name
variable_block_copy.label = variable.variable_block.label
variable_block_copy.rule = variable.variable_block.rule
variable_block_copy.meta_data = variable_block.meta_data.copy()
for variable in variable_block.variables:
variable_block_copy.add_variable(variable.copy())
dictionary_copy.add_variable_block(variable_block_copy)
i += len(variable_block.variables)
return dictionary_copy
def get_value(self, key):
"""Returns the metadata value associated to the specified key
Raises
------
`KeyError`
If the key is not found
"""
return self.meta_data.get_value(key)
def use_all_variables(self, is_used):
"""Sets the ``used`` flag of all dictionary variables to the specified value
Parameters
----------
is_used : bool
Sets the ``used`` field to ``is_used`` for all the `Variable` objects in
this dictionary.
"""
for variable in self.variables:
variable.used = is_used
def get_variable(self, variable_name):
"""Returns the specified variable
Parameters
----------
variable_name : str
A name of a variable.
Returns
-------
`Variable`
The specified variable.
Raises
------
`KeyError`
If no variable with the specified name exists.
"""
return self._variables_by_name[variable_name]
def get_variable_block(self, variable_block_name):
"""Returns the specified variable block
Parameters
----------
variable_block_name : str
A name of a variable block.
Returns
-------
`VariableBlock`
The specified variable.
Raises
------
`KeyError`
If no variable block with the specified name exists.
"""
return self._variable_blocks_by_name[variable_block_name]
def add_variable(self, variable):
"""Adds a variable to this dictionary
Parameters
----------
variable : `Variable`
The variable to be added.
Raises
------
`TypeError`
If variable is not of type `Variable`
`ValueError`
If the name is empty or if there is already a variable with that name.
"""
if not isinstance(variable, Variable):
raise TypeError(type_error_message("variable", variable, Variable))
if not variable.name:
raise ValueError(
"Cannot add to dictionary unnamed variable "
f"(variable.name = '{variable.name}')"
)
if variable.name in self._variables_by_name:
raise ValueError(
f"Dictionary already has a variable named '{variable.name}'"
)
self.variables.append(variable)
self._variables_by_name[variable.name] = variable
def remove_variable(self, variable_name):
"""Removes the specified variable from this dictionary
Parameters
----------
variable_name : str
Name of the variable to be removed.
Returns
-------
`Variable`
The removed variable.
Raises
------
`KeyError`
If no variable with the specified name exists.
"""
variable = self._variables_by_name.pop(variable_name)
self.variables.remove(variable)
if variable.variable_block is not None:
variable.variable_block.remove_variable(variable)
if not variable.variable_block.variables:
self.remove_variable_block(variable.variable_block.name)
return variable
def add_variable_block(self, variable_block):
"""Adds a variable block to this dictionary
Parameters
----------
variable_block : `VariableBlock`
The variable block to be added.
Raises
------
`TypeError`
If variable is not of type `VariableBlock`
`ValueError`
If the name is empty or if there is already a variable block with that name.
"""
if not isinstance(variable_block, VariableBlock):
raise TypeError(
type_error_message("variable_block", variable_block, VariableBlock)
)
if variable_block.name is None or variable_block.name == "":
raise ValueError(
"Cannot add to dictionary unnamed variable block; "
f"block.name = '{variable_block.name}'"
)
if variable_block.name in self._variable_blocks_by_name:
raise ValueError(
f"Dictionary already has a variable block named '{variable_block.name}'"
)
self.variable_blocks.append(variable_block)
self._variable_blocks_by_name[variable_block.name] = variable_block
for variable in variable_block.variables:
self.add_variable(variable)
def remove_variable_block(
self, variable_block_name, keep_native_block_variables=True
):
"""Removes the specified variable block from this dictionary
.. note::
Non-native block variables (those created from block rules) are never kept
in the dictionary.
Parameters
----------
variable_name : str
Name of the variable block to be removed.
keep_native_block_variables : bool, default ``True``
If ``True`` and the block is native then only the block structure is
removed from the dictionary but the variables are kept in it; neither the
variables point to the block nor the removed block points to the variables.
If ``False`` the variables are removed from the dictionary; the block
preserves the references to their variables.
Returns
-------
`VariableBlock`
The removed variable block.
Raises
------
`KeyError`
If no variable block with the specified name exists.
"""
removed_block = self.get_variable_block(variable_block_name)
# Only eliminate variable->block and block->variable references when:
# - It is a native block and
# - keep_native_block_variables is True
if removed_block.rule == "" and keep_native_block_variables:
for variable in removed_block.variables:
variable.variable_block = None
removed_block.variables = []
# Otherwise: Eliminate variables from the dictionary and keep refs. on block
else:
for variable in removed_block.variables:
self._variables_by_name.pop(variable.name)
self.variables.remove(variable)
# Remove block and its indexing
del self._variable_blocks_by_name[removed_block.name]
self.variable_blocks.remove(removed_block)
return removed_block
def is_key_variable(self, variable):
"""Returns ``True`` if a variable belongs to this dictionary's key
Parameters
----------
variable : `Variable`
The variable for the query.
Returns
-------
bool
``True`` if the variable belong to the key.
"""
return variable.name in self.key
def write(self, writer):
"""Writes the dictionary to a file writer in ``.kdic`` format
Parameters
----------
writer : `.KhiopsOutputWriter`
Output dictionary file.
"""
# Check file object type
if not isinstance(writer, KhiopsOutputWriter):
raise TypeError(type_error_message("writer", writer, KhiopsOutputWriter))
# Write dictionary header
writer.writeln("")
if self.label:
writer.write("// ")
writer.writeln(self.label)
if self.root:
writer.write("Root\t")
writer.write("Dictionary\t")
writer.write(_format_name(self.name))
if self.key:
writer.write("\t(")
for i, variable_name in enumerate(self.key):
if i > 0:
writer.write(", ")
writer.write(_format_name(variable_name))
writer.write(")")
writer.writeln("")
# Write metadata if available
if not self.meta_data.is_empty():
self.meta_data.write(writer)
writer.writeln("")
# Write variables and variable blocks
writer.writeln("{")
i = 0
while i < len(self.variables):
variable = self.variables[i]
if variable.variable_block is None:
variable.write(writer)
i += 1
else:
variable.variable_block.write(writer)
i += len(variable.variable_block.variables)
writer.writeln("};")
class Variable:
"""A variable of a Khiops dictionary
Parameters
----------
json_data : dict, optional
Python dictionary representing an element of the list at the ``variables`` field
of dictionaries found in a Khiops Dictionary JSON file. If not specified it
returns an empty instance.
Attributes
----------
name : str
Variable name.
label : str
Variable label/comment.
used : bool
True if the variable is used.
type : str
Variable type.
object_type : str
Type complement for the ``Table`` and ``Entity`` types.
structure_type : str
Type complement for the ``Structure`` type. Set to "" for other types.
rule : str
Derivation rule. Set to "" if there is no rule associated to this variable.
meta_data : `MetaData`
Variable metadata.
variable_block : `VariableBlock`
Block to which the variable belongs. Not set if the variable does not belong to
a block.
"""
def __init__(self, json_data=None):
"""See class docstring"""
# Check the type of json_data
if json_data is not None and not isinstance(json_data, dict):
raise TypeError(type_error_message("json_data", json_data, dict))
# Main attributes
self.name = ""
self.label = ""
self.used = True
self.type = ""
# Type complement attributes
self.object_type = ""
self.structure_type = ""
# Derivation rule
self.rule = ""
# Metadata
self.meta_data = MetaData()
# Reference to parent variable block
self.variable_block = None
# Return empty instance if no JSON data
if json_data is None:
return
# Check the type of the json data and its integrity
if not isinstance(json_data, dict):
raise KhiopsJSONError(
type_error_message("json data for variable", json_data, dict)