/
configuration_parser.py
1573 lines (1301 loc) · 54.8 KB
/
configuration_parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Classes related to parsing configuration files
and creating configuration objects.
:author: Jeremy Biggs (jbiggs@ets.org)
:author: Anastassia Loukina (aloukina@ets.org)
:author: Nitin Madnani (nmadnani@ets.org)
:organization: ETS
"""
import functools
import json
import logging
import re
import warnings
from copy import copy, deepcopy
from collections import Counter
from configparser import ConfigParser
from os import getcwd, makedirs
from os.path import (abspath,
basename,
dirname,
join,
splitext)
from pathlib import Path
from ruamel import yaml
from rsmtool import HAS_RSMEXTRA
from rsmtool.utils import parse_json_with_comments
from rsmtool.utils import (DEFAULTS,
CHECK_FIELDS,
CONTEXT_TO_FUNCTION,
LIST_FIELDS,
BOOLEAN_FIELDS,
MODEL_NAME_MAPPING,
FIELD_NAME_MAPPING,
ID_FIELDS,
is_skll_model)
from skll import Learner
from skll.metrics import SCORERS
if HAS_RSMEXTRA:
from rsmextra.settings import (default_feature_subset_file,
default_feature_sign)
def deprecated_positional_argument():
"""
This decorator allows the Configuration class to:
(a) accept the old method of specifying the now-deprecated ``filepath`` positional argument,
(b) accept the new method of specifying ``configdir`` and ``filename`` keyword arguments, but
(c) disallow using the old and the new methods in the same call
Adapted from: https://stackoverflow.com/a/49802489
"""
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
# if we received two positional arguments
if len(args) > 2:
# if we also received a keyword argument for filepath
# or configdir, raise an error
if 'filename' in kwargs:
raise ValueError("Cannot specify both the deprecated filepath "
"positional argument and the new-style filename "
"keyword argument.")
if 'configdir' in kwargs:
raise ValueError("Cannot specify both the deprecated filepath "
"positional argument and the new-style configdir "
"keyword argument.")
# raise deprecation warning
warnings.warn("The filepath positional argument is deprecated and "
" will be removed in v8.0. Use the ``configdir`` and "
"``filename`` keyword arguments instead.",
DeprecationWarning)
# split filepath into
# configdir and filename
filepath = args[-1]
kwargs['filename'] = basename(filepath)
kwargs['configdir'] = dirname(abspath(filepath))
# remove filepath from positional arguments
args = args[:-1]
return f(*args, **kwargs)
return wrapper
return decorator
class Configuration:
"""
Configuration class, which encapsulates all of the
configuration parameters and methods to access these
parameters.
"""
@deprecated_positional_argument()
def __init__(self,
config_dict,
*,
configdir=None,
filename=None,
context='rsmtool'):
"""
Create an object of the `Configuration` class.
Note that usually the Configuration
object used for RSMTool experiments is created using
`ConfigurationParser.load_normalize_and_validate_config_from_dict()` or
`ConfigurationParser.read_normalize_validate_and_process_config()`.
You should directly instantiate a Configuration object only if
you already have a normalized configuration dictionary
(e.g., from previous RSMTool experiments).
Parameters
----------
config_dict : dict
A dictionary of configuration parameters.
The dictionary must be a valid configuration dictionary
with default values filled as necessary.
configdir : str, optional, keyword-only
The reference path used to
resolve any relative paths in the configuration
object. When None, will be set during
initialization to the current working directory.
Defaults to None
filename : str, optional, keyword-only
The name of the configuration file.
The file must be stored in configdir.
This argument is not used in RSMTool and only added for
backwards compatibility for the deprecated `filepath` attribute.
Defaults to None.
context : {'rsmtool', 'rsmeval', 'rsmcompare',
'rsmpredict', 'rsmsummarize'}
The context of the tool.
Defaults to 'rsmtool'.
"""
self._config = config_dict
self._context = context
# set configdir to `cwd` if not given and let the user know
if configdir is None:
configdir = getcwd()
logging.info("Configuration directory will be set to {}".format(configdir))
else:
configdir = abspath(configdir)
self._configdir = configdir
self._filename = filename
def __contains__(self, key):
"""
Check if configuration object
contains a given key.
Parameters
----------
key : str
Key to check in the Configuration object.
Returns
-------
key_check : bool
True if key in Configuration object, else False
"""
return key in self._config
def __getitem__(self, key):
"""
Get value, given key.
Parameters
----------
key : str
Key to check in the Configuration object
Returns
-------
value
The value in the Configuration object dictionary.
"""
return self._config[key]
def __setitem__(self, key, value):
"""
Set value, given key.
Parameters
----------
key : str
Key to check in the Configuration object.
value
A value to be set on the key.
"""
self._config[key] = value
def __len__(self):
"""
Return the length of the Configuration dictionary.
Returns
-------
length : int
The length of the config dictionary (i.e. number of elements)
"""
return len(self._config)
def __str__(self):
"""
Return string representation of the object keys
as comma-separated list.
Returns
-------
config_names : str
A comma-separated list of names from the config dictionary.
"""
return ', '.join(self._config)
def __iter__(self):
"""
Iterate through configuration object keys.
Yields
------
key
A key in the config dictionary
"""
for key in self.keys():
yield key
@property
def filepath(self):
"""
Get file path to the configuration file.
.. deprecated:: 8.0
``filepath`` will be removed in RSMTool v8.0. Use ``configdir`` and
``filename`` instead.
Returns
-------
filepath : str
The path for the config file.
"""
warnings.warn("The `filepath` attribute of the Configuration "
"object will be removed in RSMTool v8.0."
"Use the `configdir` and `filename` attributes if you "
"need the full path to the "
"configuration file", DeprecationWarning)
filepath = join(self.configdir, self.filename)
return filepath
@filepath.setter
def filepath(self, new_path):
"""
Set a new file path to configuration file.
.. deprecated:: 8.0
``filepath`` will be removed in RSMTool v8.0. Use ``configdir`` and
``filename`` instead.
Parameters
----------
new_path : str
A new file path for the Configuration object.
"""
warnings.warn("The `filepath` attribute of the Configuration "
"object will be removed in RSMTool 8.0 "
"use `configdir` and `filename` if you "
"need to set a new path to the "
"configuration file", DeprecationWarning)
new_filename = basename(new_path)
new_configdir = dirname(abspath(new_path))
self._filename = new_filename
self._configdir = new_configdir
@property
def configdir(self):
"""
Get the path to the configuration reference directory that
will be used to resolve any relative paths in
the configuration.
Returns
-------
configdir : str
The path to the configuration reference directory
"""
return self._configdir
@configdir.setter
def configdir(self, new_path):
"""
Set a new configuration reference directory
Parameters
----------
new_path : str
Path to the new configuration reference
directory used to resolve any relative paths
in the configuration object.
"""
if new_path is None:
raise ValueError("The `configdir` attribute cannot be set to `None` ")
self._configdir = abspath(new_path)
@property
def filename(self):
"""
Get the name of the configuration file.
Returns
-------
filename : str
The name of the configuration file
"""
return self._filename
@filename.setter
def filename(self, new_path):
"""
Set a new name of the configuration file
Parameters
----------
new_name : str
New name of the configuration file
"""
self._filename = new_path
@property
def context(self):
"""
Get the context.
"""
return self._context
@context.setter
def context(self, new_context):
"""
Set a new context
Parameters
----------
new_context : str
A new context for the
configuration object.
"""
self._context = new_context
def get(self, key, default=None):
"""
Get value or default, given key.
Parameters
----------
key : str
Key to check in the Configuration object.
default, optional
The default value to return, if no key exists.
Defaults to None.
Returns
-------
value
The value in the Configuration object dictionary.
"""
return self._config.get(key, default)
def to_dict(self):
"""
Get a dictionary representation of the Configuration object.
Returns
-------
config : dict
The configuration dictionary.
"""
return self._config
def keys(self):
"""
Return keys as a list.
Returns
-------
keys : list of str
A list of keys in the Configuration object.
"""
return [k for k in self._config.keys()]
def values(self):
"""
Return values as a list.
Returns
-------
values : list
A list of values in the Configuration object.
"""
return [v for v in self._config.values()]
def items(self):
"""
Return items as a list of tuples.
Returns
-------
items : list of tuples
A list of (key, value) tuples in the
configuration object.
"""
return [(k, v) for k, v in self._config.items()]
def pop(self, key, default=None):
"""
Remove and returns an element from
the object having the given key.
Parameters
----------
key : str
Key to pop in the configuration object.
default, optional
The default value to return, if no key exists.
Defaults to None.
Returns
-------
value
The value removed from the object.
"""
return self._config.pop(key, default)
def copy(self, deep=True):
"""
Return a copy of the object.
Parameters
----------
deep : bool, optional
Whether to perform a deep copy.
Defaults to True.
Returns
-------
copy : Configuration
A new configuration object.
"""
if deep:
return deepcopy(self)
return copy(self)
def save(self, output_dir=None):
"""
Save the configuration file to the output directory specified.
Parameters
----------
output_dir : str
The path to the output directory.
"""
# save a copy of the main config into the output directory
if output_dir is None:
output_dir = getcwd()
# Create output directory, if it does not exist
output_dir = join(output_dir, 'output')
makedirs(output_dir, exist_ok=True)
id_field = ID_FIELDS[self._context]
outjson = join(output_dir,
'{}_{}.json'.format(self._config[id_field],
self._context))
expected_fields = (CHECK_FIELDS[self._context]['required'] +
CHECK_FIELDS[self._context]['optional'])
output_config = {k: v for k, v in self._config.items() if k in expected_fields}
with open(outjson, 'w') as outfile:
json.dump(output_config, outfile, indent=4, separators=(',', ': '))
def check_exclude_listwise(self):
"""
Check if we are excluding candidates
based on number of responses, and
add this to the configuration file
Returns
-------
exclude_listwise : bool
Whether to exclude list-wise
"""
exclude_listwise = False
if self._config.get('min_items_per_candidate'):
exclude_listwise = True
return exclude_listwise
def check_flag_column(self,
flag_column='flag_column',
partition='unknown'):
"""
Make sure the `flag_column` field is in the correct format. Get
flag columns and values for filtering if any and convert single
values to lists. Raises an exception if `flag_column` is not
correctly specified.
Parameters
----------
flag_column : str
The flag column to check. Currently used fields are `flag_column` or
`flag_column_test`.
Defaults to 'flag_column'.
partition: {'train', 'test', 'both', 'unknown'}
Partition which is filtered based on the flag column.
This is used to display more helpful warning messages.
Defaults to 'both'
Returns
-------
new_filtering_dict : dict
Properly formatted `flag_column` dictionary.
Raises
------
ValueError
If the `flag_column` is not a dictionary
If `partition` value if not in the expected list
If `partition` value does not match the `flag_column`
"""
config = self._config
new_filter_dict = {}
flag_message = {'train': 'training',
'test': 'evaluating',
'both': 'training and evaluating',
'unknown': 'training and/or evaluating'}
if partition not in flag_message:
raise ValueError("Unknown value for partition: {} "
"This must be one of the following: {}."
"".format(partition, ','.join(flag_message.keys())))
if flag_column == 'flag_column_test':
if partition in ['both', 'train']:
raise ValueError("The conditions specified in `flag_column_test` "
"can only be applied to the evaluation partition.")
if config.get(flag_column):
original_filter_dict = config[flag_column]
# first check that the value is a dictionary
if not isinstance(original_filter_dict, dict):
raise ValueError("`flag_column` must be a dictionary. "
"Please refer to the documentation for "
"further information.")
for column in original_filter_dict:
# if we were given a single value, convert it to list
if not isinstance(original_filter_dict[column], list):
new_filter_dict[column] = [original_filter_dict[column]]
logging.warning("The filtering condition {}"
" for column {} was converted "
"to list. Only responses where "
"{} == {} will be used for "
"{} the "
"model. You can ignore this "
"warning if this is the correct "
"interpretation of your "
"configuration settings"
".".format(original_filter_dict[column],
column,
column,
original_filter_dict[column],
flag_message[partition])
)
else:
new_filter_dict[column] = original_filter_dict[column]
model_eval = ', '.join(map(str,
original_filter_dict[column]))
logging.info("Only responses where "
"{} equals one of the following values "
"will be used for {} the model: "
"{}.".format(column,
flag_message[partition],
model_eval))
return new_filter_dict
def get_trim_min_max(self):
"""
This function is kept for backwards compatibility.
It is now replaced by get_trim_min_max_tolerance
and will be deprecated in future versions.
Returns
-------
spec_trim_min : float
Specified trim min value
spec_trim_max : float
Specified trim max value
"""
logging.warning("get_trim_min_max method has been replaced by "
"get_trim_min_max_tolerance() and will "
"not be supported in future releases.")
(trim_min, trim_max, tolerance) = self.get_trim_min_max_tolerance()
return (trim_min, trim_max)
def get_trim_min_max_tolerance(self):
"""
Get the specified trim min and max,
and trim_tolerance if any,
and make sure they are numeric.
Returns
-------
spec_trim_min : float
Specified trim min value
spec_trim_max : float
Specified trim max value
spec_trim_tolerance: float
specified trim tolerance value
"""
config = self._config
spec_trim_min = config.get('trim_min', None)
spec_trim_max = config.get('trim_max', None)
spec_trim_tolerance = config.get('trim_tolerance', None)
if spec_trim_min:
spec_trim_min = float(spec_trim_min)
if spec_trim_max:
spec_trim_max = float(spec_trim_max)
if spec_trim_tolerance:
spec_trim_tolerance = float(spec_trim_tolerance)
return (spec_trim_min, spec_trim_max, spec_trim_tolerance)
def get_default_converter(self):
"""
Get the default converter dictionary for reader.
Returns
-------
default_converter : dict
The default converter for a train or test file.
"""
string_columns = [self._config['id_column']]
candidate = self._config.get('candidate_column')
if candidate is not None:
string_columns.append(candidate)
subgroups = self._config.get('subgroups')
if subgroups:
string_columns.extend(subgroups)
return dict([(column, str) for column in string_columns if column])
def get_names_and_paths(self, keys, names):
"""
Get a a list of values, given keys.
Remove any values that are None.
Parameters
-------
keys : list
A list of keys whose values to retrieve.
names : list
The default value to use if key cannot be found.
Defaults to None.
Returns
-------
values : list
The list of values.
Raises
------
ValueError
If there are any duplicate keys or names.
"""
assert len(keys) == len(names)
# Make sure keys are not duplicated
if not len(set(keys)) == len(keys):
raise ValueError('The ``keys`` must be unique. However, the '
'following duplicate keys were found: {}.'
''.format(', '.join([key for key, val in Counter(keys).items()
if val > 1])))
# Make sure names are not duplicated
if not len(set(names)) == len(names):
raise ValueError('The``names`` must be unique. However, the '
'following duplicate names were found: {}.'
''.format(', '.join([name for name, val in Counter(names).items()
if val > 1])))
existing_names = []
existing_paths = []
for idx, key in enumerate(keys):
path = self._config.get(key)
# if the `features` field is a list,
# do not include it in the container
if key == 'features':
if isinstance(path, list):
continue
if path is not None:
existing_paths.append(path)
existing_names.append(names[idx])
return existing_names, existing_paths
class ConfigurationParser:
"""
A `ConfigurationParser` class to create a
`Configuration` object.
"""
def __init__(self):
# Set configuration object to None
self._config = None
self._filename = None
self._configdir = None
def _check_config_is_loaded(self):
"""
Check to make sure a configuration file
or dictionary was loaded; otherwise,
raise ``NameError``.
Raises
------
NameError
If no configuration file or dictionary was loaded.
"""
if self._config is None:
raise NameError('No configuration file was loaded '
'Make sure to load a configuration file '
'from a dict using the `load_config_from_dict()` '
'method or use the `read_config_from_file()` method '
'with the appropriate sub-class object to read from '
'a file. You can use the `get_configparser` class '
'method to instantiate the appropriate sub-class '
'object for reading either `.json` or `.cfg` files.')
@classmethod
def get_configparser(cls, config_file_or_obj_or_dict, *args, **kwargs):
"""
Get the correct `ConfigurationParser` object,
based on the input.
Parameters
----------
config_file_or_obj_or_dict: str or pathlib.Path or dict or Configuration
Input object used to construct the configuration parser
Returns
-------
config : ConfigurationParser
The configuration parser object.
Raises
------
ValueError
If config file is not .json or .cfg.
"""
# If we received a path to a file,
# let's convert it to Path
if isinstance(config_file_or_obj_or_dict, Path):
filepath = config_file_or_obj_or_dict
elif isinstance(config_file_or_obj_or_dict, str):
filepath = Path(config_file_or_obj_or_dict)
# if we got anything else, we initialize the base ConfigurationParser
else:
return ConfigurationParser(*args, **kwargs)
# For files we initialize one of the subclasses.
# Get the file extension to determine which.
extension = filepath.suffix
if extension.lower() not in CONFIG_TYPE:
raise ValueError('Configuration file must be '
'in either `.json` or `.cfg`'
'format. You specified: {}.'.format(extension))
return CONFIG_TYPE[extension.lower()](*args, **kwargs)
@staticmethod
def check_id_fields(id_field_values):
"""
Check whether the ID fields in the given dictionary
are properly formatted, i.e., they ::
- do not contain any spaces
- are shorter than 200 characters
Parameters
----------
id_field_values : dict
A dictionary containing the ID fields names
as the keys and the value from the configuration
file as the value.
Raises
------
ValueError
If the values for the ID fields in the given
dictionary are not formatted correctly.
"""
for id_field, id_field_value in id_field_values.items():
if len(id_field_value) > 200:
raise ValueError("{} is too long (must be "
"<=200 characters)".format(id_field))
if re.search(r'\s', id_field_value):
raise ValueError("{} cannot contain any "
"spaces".format(id_field))
def load_config_from_dict(self,
config_dict,
configdir=None):
"""
Load configuration dictionary.
Parameters
----------
config_dict : dict
A dictionary containing the configuration
parameters to parse.
configdir : str, optional
Path to the reference directory used to resolve
any relative path in the dictionary. If not specified,
the current working directory will be used.
filename: str, optional
Raises
------
TypeError
If `config_dict` is not a ``dict``
AttributeError
If config has already been assigned.
"""
if not isinstance(config_dict, dict):
raise TypeError('The `config_dict` must be a dictionary.')
if self._config is None:
self._config = config_dict
else:
raise AttributeError('A configuration dictionary has already'
'been assigned. You cannot assign another'
'dictionary.')
if configdir is None:
configdir = getcwd()
self._configdir = abspath(configdir)
logging.info("Configuration directory will be set to {}".format(self._configdir))
# set filename to none since there was no configuration file.
# If the user for some reason wants
# to set it, they can do so explicitly.
self._filename = None
def load_normalize_and_validate_config_from_dict(self,
config_dict,
configdir=getcwd(),
context='rsmtool'):
"""
Load configuration dictionary.
Parameters
----------
config_dict : dict
A dictionary containing the configuration
parameters to parse.
configdir : str, optional
Path to the reference directory used to resolve
any relative path in the dictionary.
Defaults to the current working directory.
context : str, optional
Context of the tool in which we are validating.
Possible values are ::
{'rsmtool', 'rsmeval',
'rsmpredict', 'rsmcompare', 'rsmsummarize'}
Defaults to 'rsmtool'.
Returns
-------
config_obj : Configuration
A configuration object
"""
self.load_config_from_dict(config_dict, configdir)
return self.normalize_validate_and_process_config(context=context)
def read_config_from_file(self, filepath):
"""
Read the configuration file.
Parameters
----------
filepath : str
The path to the configuration file.
Raises
------
NotImplementedError
This method must be implemented in subclass.
"""
raise NotImplementedError("The method `read_config_from_file()` "
"is only implemented in the subclasses "
"``CFGConfigurationParser`` and "
"``JSONConfigurationParser``. "
"You can use the class method "
"`get_configparser()` to retrieve "
"the correct configuration parser object "
"for parsing JSON or CFG files.")
def normalize_config(self, inplace=True):
"""
Normalize the field names in `self._config` or `config` in order to
maintain backwards compatibility with old configuration files.
Parameters
----------
inplace : bool
Maintain the state of the config object produced by
this method.
Defaults to True.
Returns
-------
new_config : Configuration
A normalized configuration object
Raises
------
ValueError
If no JSON configuration object exists, or if value passed for
`use_scaled_predictions` is in the wrong format.
"""
# Check to make sure a configuration file
# or dictionary has been loaded.
self._check_config_is_loaded()
# Get the parameter dictionary
config = self._config
# Create a new JSON object with the normalized field names
new_config = {}
for field_name in config:
if field_name in FIELD_NAME_MAPPING:
norm_field_name = FIELD_NAME_MAPPING[field_name]
warnings.warn("""The field name "{}" is deprecated """
"""and will be removed in a future """
"""release, please use the """
"""new field name "{}" """
"""instead.""".format(field_name,
norm_field_name),
category=DeprecationWarning)
else:
norm_field_name = field_name
new_config[norm_field_name] = config[field_name]
# Convert old values for prediction scaling:
if 'use_scaled_predictions' in new_config:
if new_config['use_scaled_predictions'] in ['scale', True]: