pg-sui 1.0.2.1__py3-none-any.whl → 1.6.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pg-sui might be problematic. Click here for more details.

Files changed (112) hide show
  1. {pg_sui-1.0.2.1.dist-info → pg_sui-1.6.8.dist-info}/METADATA +51 -70
  2. pg_sui-1.6.8.dist-info/RECORD +78 -0
  3. {pg_sui-1.0.2.1.dist-info → pg_sui-1.6.8.dist-info}/WHEEL +1 -1
  4. pg_sui-1.6.8.dist-info/entry_points.txt +4 -0
  5. pg_sui-1.6.8.dist-info/top_level.txt +1 -0
  6. pgsui/__init__.py +35 -54
  7. pgsui/_version.py +34 -0
  8. pgsui/cli.py +635 -0
  9. pgsui/data_processing/config.py +576 -0
  10. pgsui/data_processing/containers.py +1782 -0
  11. pgsui/data_processing/transformers.py +121 -1103
  12. pgsui/electron/app/__main__.py +5 -0
  13. pgsui/electron/app/icons/icons/1024x1024.png +0 -0
  14. pgsui/electron/app/icons/icons/128x128.png +0 -0
  15. pgsui/electron/app/icons/icons/16x16.png +0 -0
  16. pgsui/electron/app/icons/icons/24x24.png +0 -0
  17. pgsui/electron/app/icons/icons/256x256.png +0 -0
  18. pgsui/electron/app/icons/icons/32x32.png +0 -0
  19. pgsui/electron/app/icons/icons/48x48.png +0 -0
  20. pgsui/electron/app/icons/icons/512x512.png +0 -0
  21. pgsui/electron/app/icons/icons/64x64.png +0 -0
  22. pgsui/electron/app/icons/icons/icon.icns +0 -0
  23. pgsui/electron/app/icons/icons/icon.ico +0 -0
  24. pgsui/electron/app/main.js +189 -0
  25. pgsui/electron/app/package-lock.json +6893 -0
  26. pgsui/electron/app/package.json +50 -0
  27. pgsui/electron/app/preload.js +15 -0
  28. pgsui/electron/app/server.py +146 -0
  29. pgsui/electron/app/ui/logo.png +0 -0
  30. pgsui/electron/app/ui/renderer.js +130 -0
  31. pgsui/electron/app/ui/styles.css +59 -0
  32. pgsui/electron/app/ui/ui_shim.js +72 -0
  33. pgsui/electron/bootstrap.py +43 -0
  34. pgsui/electron/launch.py +59 -0
  35. pgsui/electron/package.json +14 -0
  36. pgsui/example_data/popmaps/{test.popmap → phylogen_nomx.popmap} +185 -99
  37. pgsui/example_data/vcf_files/phylogen_subset14K.vcf.gz +0 -0
  38. pgsui/example_data/vcf_files/phylogen_subset14K.vcf.gz.tbi +0 -0
  39. pgsui/impute/deterministic/imputers/allele_freq.py +691 -0
  40. pgsui/impute/deterministic/imputers/mode.py +679 -0
  41. pgsui/impute/deterministic/imputers/nmf.py +221 -0
  42. pgsui/impute/deterministic/imputers/phylo.py +971 -0
  43. pgsui/impute/deterministic/imputers/ref_allele.py +530 -0
  44. pgsui/impute/supervised/base.py +339 -0
  45. pgsui/impute/supervised/imputers/hist_gradient_boosting.py +293 -0
  46. pgsui/impute/supervised/imputers/random_forest.py +287 -0
  47. pgsui/impute/unsupervised/base.py +924 -0
  48. pgsui/impute/unsupervised/callbacks.py +89 -263
  49. pgsui/impute/unsupervised/imputers/autoencoder.py +972 -0
  50. pgsui/impute/unsupervised/imputers/nlpca.py +1264 -0
  51. pgsui/impute/unsupervised/imputers/ubp.py +1288 -0
  52. pgsui/impute/unsupervised/imputers/vae.py +957 -0
  53. pgsui/impute/unsupervised/loss_functions.py +158 -0
  54. pgsui/impute/unsupervised/models/autoencoder_model.py +208 -558
  55. pgsui/impute/unsupervised/models/nlpca_model.py +149 -468
  56. pgsui/impute/unsupervised/models/ubp_model.py +198 -1317
  57. pgsui/impute/unsupervised/models/vae_model.py +259 -618
  58. pgsui/impute/unsupervised/nn_scorers.py +215 -0
  59. pgsui/utils/classification_viz.py +591 -0
  60. pgsui/utils/misc.py +35 -480
  61. pgsui/utils/plotting.py +514 -824
  62. pgsui/utils/scorers.py +212 -438
  63. pg_sui-1.0.2.1.dist-info/RECORD +0 -75
  64. pg_sui-1.0.2.1.dist-info/top_level.txt +0 -3
  65. pgsui/example_data/phylip_files/test_n10.phy +0 -118
  66. pgsui/example_data/phylip_files/test_n100.phy +0 -118
  67. pgsui/example_data/phylip_files/test_n2.phy +0 -118
  68. pgsui/example_data/phylip_files/test_n500.phy +0 -118
  69. pgsui/example_data/structure_files/test.nopops.1row.10sites.str +0 -117
  70. pgsui/example_data/structure_files/test.nopops.2row.100sites.str +0 -234
  71. pgsui/example_data/structure_files/test.nopops.2row.10sites.str +0 -234
  72. pgsui/example_data/structure_files/test.nopops.2row.30sites.str +0 -234
  73. pgsui/example_data/structure_files/test.nopops.2row.allsites.str +0 -234
  74. pgsui/example_data/structure_files/test.pops.1row.10sites.str +0 -117
  75. pgsui/example_data/structure_files/test.pops.2row.10sites.str +0 -234
  76. pgsui/example_data/trees/test.iqtree +0 -376
  77. pgsui/example_data/trees/test.qmat +0 -5
  78. pgsui/example_data/trees/test.rate +0 -2033
  79. pgsui/example_data/trees/test.tre +0 -1
  80. pgsui/example_data/trees/test_n10.rate +0 -19
  81. pgsui/example_data/trees/test_n100.rate +0 -109
  82. pgsui/example_data/trees/test_n500.rate +0 -509
  83. pgsui/example_data/trees/test_siterates.txt +0 -2024
  84. pgsui/example_data/trees/test_siterates_n10.txt +0 -10
  85. pgsui/example_data/trees/test_siterates_n100.txt +0 -100
  86. pgsui/example_data/trees/test_siterates_n500.txt +0 -500
  87. pgsui/example_data/vcf_files/test.vcf +0 -244
  88. pgsui/example_data/vcf_files/test.vcf.gz +0 -0
  89. pgsui/example_data/vcf_files/test.vcf.gz.tbi +0 -0
  90. pgsui/impute/estimators.py +0 -735
  91. pgsui/impute/impute.py +0 -1486
  92. pgsui/impute/simple_imputers.py +0 -1439
  93. pgsui/impute/supervised/iterative_imputer_fixedparams.py +0 -785
  94. pgsui/impute/supervised/iterative_imputer_gridsearch.py +0 -1027
  95. pgsui/impute/unsupervised/keras_classifiers.py +0 -702
  96. pgsui/impute/unsupervised/models/in_development/cnn_model.py +0 -486
  97. pgsui/impute/unsupervised/neural_network_imputers.py +0 -1424
  98. pgsui/impute/unsupervised/neural_network_methods.py +0 -1549
  99. pgsui/pg_sui.py +0 -261
  100. pgsui/utils/sequence_tools.py +0 -407
  101. simulation/sim_benchmarks.py +0 -333
  102. simulation/sim_treeparams.py +0 -475
  103. test/__init__.py +0 -0
  104. test/pg_sui_simtest.py +0 -215
  105. test/pg_sui_testing.py +0 -523
  106. test/test.py +0 -297
  107. test/test_pgsui.py +0 -374
  108. test/test_tkc.py +0 -214
  109. {pg_sui-1.0.2.1.dist-info → pg_sui-1.6.8.dist-info/licenses}/LICENSE +0 -0
  110. /pgsui/{example_data/trees → electron/app}/__init__.py +0 -0
  111. /pgsui/impute/{unsupervised/models/in_development → supervised/imputers}/__init__.py +0 -0
  112. {simulation → pgsui/impute/unsupervised/imputers}/__init__.py +0 -0
@@ -1,1027 +0,0 @@
1
- # Standard library imports
2
- import gc
3
- import math
4
- import os
5
- import shutil
6
- import sys
7
- import warnings
8
-
9
- warnings.simplefilter(action="ignore", category=FutureWarning)
10
-
11
-
12
- # from collections import namedtuple
13
- from contextlib import redirect_stdout
14
- from time import time
15
- from typing import Optional, Union, List, Dict, Tuple, Any, Callable
16
-
17
- # Third-party imports
18
- ## For plotting
19
- import matplotlib.pyplot as plt
20
- import seaborn as sns
21
- from matplotlib.backends.backend_pdf import PdfPages
22
-
23
- ## For stats and numeric operations
24
- import numpy as np
25
- import pandas as pd
26
- from scipy import stats
27
-
28
- # scikit-learn imports
29
- from sklearn.base import clone
30
- from sklearn.experimental import enable_iterative_imputer
31
- from sklearn.impute import IterativeImputer
32
- from sklearn.impute import SimpleImputer
33
- from sklearn.impute._base import _check_inputs_dtype
34
-
35
- ## For warnings
36
- from sklearn.exceptions import ConvergenceWarning
37
- from sklearn.utils._testing import ignore_warnings
38
-
39
- ## Required for IterativeImputer.fit_transform()
40
- from sklearn.utils import check_random_state, _safe_indexing, is_scalar_nan
41
- from sklearn.utils._mask import _get_mask
42
- from sklearn.utils.validation import FLOAT_DTYPES
43
-
44
- # Grid search imports
45
- from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
46
- from sklearn.model_selection import StratifiedKFold
47
-
48
- # Genetic algorithm grid search imports
49
- from sklearn_genetic import GASearchCV
50
- from sklearn_genetic.callbacks import ConsecutiveStopping, DeltaThreshold
51
- from sklearn_genetic.plots import plot_fitness_evolution
52
- from sklearn.preprocessing import (
53
- LabelEncoder,
54
- OneHotEncoder,
55
- OrdinalEncoder,
56
- TargetEncoder,
57
- )
58
- from sklearn.exceptions import NotFittedError
59
- from sklearn.utils.class_weight import compute_sample_weight
60
- from sklearn.pipeline import make_pipeline
61
-
62
- from xgboost import XGBClassifier
63
-
64
- # Custom function imports
65
- try:
66
- from .. import simple_imputers
67
- from ...utils.plotting import Plotting
68
- from ...utils.misc import get_processor_name
69
- from ...utils.misc import HiddenPrints
70
- from ...utils.misc import isnotebook
71
- except (ModuleNotFoundError, ValueError, ImportError):
72
- from impute import simple_imputers
73
- from utils.plotting import Plotting
74
- from utils.misc import get_processor_name
75
- from utils.misc import HiddenPrints
76
- from utils.misc import isnotebook
77
-
78
- # Uses scikit-learn-intellex package if CPU is Intel
79
- if get_processor_name().strip().startswith("Intel"):
80
- try:
81
- from sklearnex import patch_sklearn
82
-
83
- patch_sklearn(verbose=False)
84
- except (ImportError, TypeError):
85
- print(
86
- "Processor not compatible with scikit-learn-intelex; using "
87
- "default configuration"
88
- )
89
-
90
- is_notebook = isnotebook()
91
-
92
- if is_notebook:
93
- from tqdm.notebook import tqdm as progressbar
94
- else:
95
- if sys.platform == "linux" or sys.platform == "linux2":
96
- from tqdm.auto import tqdm as progressbar
97
- else:
98
- from tqdm import tqdm as progressbar
99
-
100
- # NOTE: Removed ImputeTriplets to save memory.
101
- # ImputerTriplet is there so that the missing values
102
- # can be predicted on an already-fit model using just the
103
- # transform method. I didn't need it, so I removed it
104
- # because it was saving thousands of fit estimator models into the object
105
-
106
- # _ImputerTripletGrid = namedtuple(
107
- # '_ImputerTripletGrid', ['feat_idx', 'neighbor_feat_idx', 'estimator'])
108
-
109
-
110
- class IterativeImputerGridSearch(IterativeImputer):
111
- """Overridden IterativeImputer methods.
112
-
113
- Herein, two types of grid searches (RandomizedSearchCV and GASearchCV), progress status updates, and several other improvements have been added. IterativeImputer is a multivariate imputer that estimates each feature from all the others. A strategy for imputing missing values by modeling each feature with missing values as a function of other features in a round-robin fashion.Read more in the scikit-learn User Guide for IterativeImputer. scikit-learn version added: 0.21. NOTE: This estimator is still **experimental** for now: the predictions and the API might change without any deprecation cycle. To use it, you need to explicitly import ``enable_iterative_imputer``\.
114
-
115
- IterativeImputer is based on the R MICE (Multivariate Imputation by Chained Equationspackage) [van Buuren & Groothuis-Oudshoorn, 2011]_. See [Buck, 1960]_ for more information about multiple versus single imputations.
116
-
117
- >>> # explicitly require this experimental feature
118
- >>> from sklearn.experimental import enable_iterative_imputer
119
- >>>
120
- >>> # now you can import normally from sklearn.impute
121
- >>> from sklearn.impute import IterativeImputer
122
-
123
- Args:
124
- logfilepath (str): Path to the progress log file.
125
-
126
- gridparams (sklearn_genetic.space object or Dict[str, Any]): The parameter distributions or values to use for the grid search.
127
-
128
- clf_kwargs (Dict[str, Any]): A dictionary with the classifier keyword arguments.
129
-
130
- ga_kwargs (Dict[str, Any]): A dictionary with the genetic algorithm arguments.
131
-
132
- prefix (str): Prefix for output files.
133
-
134
- estimator (estimator object, optional): The estimator to use at each step of the round-robin imputation. Defaults to BayesianRidge().
135
-
136
- grid_cv (int, optional): The number of cross-validation folds to use with the grid search. CV folds will be stratified, and it will attempt to balance the genotypes in each fold. IMPORTANT: Sites with fewer than ``2 * grid_cv`` of each genotypes will be removed prior to doing the random subsetting because otherwise the imputation would fail. At least two of each gentoype are required to be present in each fold. Defaults to 5.
137
-
138
- grid_n_jobs (int, optional): [The number of processors to use with the grid search. Set ``grid_n_jobs`` to -1 to use all available processors]. Defaults to 1.
139
-
140
- grid_iter (int, optional): The number of iterations (for RandomizedSearchCV) or generations (for the genetic algorithm) to run with the grid search. For the genetic algorithm, an early stopping callback method is implemented that will stop if the accuracy does not improve for more than 5 consecutive generations. Defaults to 10.
141
-
142
- clf_type (str, optional): Whether to run ``"classifier"`` or ``"regression"`` based imputation. Defaults to "classifier".
143
-
144
- ga (bool, optional): Whether or not to use the genetic algorithm. If True, does genetic algorithm, otherwise does RandomizedSearchCV. Defaults to False.
145
-
146
- disable_progressbar (bool, optional): Whether or not to disable the tqdm progress bar. If True, disables the progress bar. If False, tqdm is used for the progress bar. This can be useful if you are running the imputation on an HPC cluster or are saving the standard output to a file. If True, progress updates will be printed to the screen every ``progress_update_percent`` iterations. Defaults to False.
147
-
148
- progress_update_percent (int, optional) : How often to display progress updates (as a percentage) if ``disable_progressbar`` is True. If ``progress_update_percent=10``\, then it displays progress updates every 10%. Defaults to 10.
149
-
150
- pops (List[Union[int, str]]): List of population IDs of shape (n_samples,).
151
-
152
- scoring_metric (str, optional): Scoring metric to use for the grid search. Defaults to "accuracy".
153
-
154
- early_stop_gen (int, optional): Number of consecutive generations lacking improvement for which to implement the early stopping callback. Defaults to 5.
155
-
156
- missing_values (int or np.nan, optional): The placeholder for the missing values. All occurrences of ``missing_values`` will be imputed. For pandas dataframes with nullable integer dtypes with missing values, ``missing_values`` should be set to ``np.nan``\, since ``pd.NA`` will be converted to ``np.nan``\. Defaults to np.nan.
157
-
158
- Sample_posterior (bool, optional): CURRENTLY NOT SUPPORTED. Whether to sample from the (Gaussian) predictive posterior of the fitted estimator for each imputation. Estimator must support ``return_std`` in its ``predict`` method if set to ``True``\. Set to ``True`` if using ``IterativeImputer`` for multiple imputations. Defaults to False.
159
-
160
- max_iter (int, optional): Maximum number of imputation rounds to perform before returning the imputations computed during the final round. A round is a single imputation of each feature with missing values. The stopping criterion is met once ``max(abs(X_t - X_{t-1}))/max(abs(X[known_vals])) < tol``\, where ``X_t`` is ``X`` at iteration `t`. Note that early stopping is only applied if ``sample_posterior=False``\. Defaults to 10.
161
-
162
- tol (float, optional): Tolerance of the stopping condition. Defaults to 1e-3.
163
-
164
- n_nearest_features (int, optional): Number of other features to use to estimate the missing values of each feature column. Nearness between features is measured using the absolute correlation coefficient between each feature pair (after initial imputation). To ensure coverage of features throughout the imputation process, the neighbor features are not necessarily nearest, but are drawn with probability proportional to correlation for each imputed target feature. Can provide significant speed-up when the number of features is huge. If ``None``\, all features will be used. Defaults to None.
165
-
166
- initial_strategy (str, optional): Which strategy to use to initialize the missing values. Same as the ``strategy`` parameter in :class:`~sklearn.impute.SimpleImputer` Valid values: "most_frequent", "populations", "mf", or "phylogeny". Defaults to "populations".
167
-
168
- imputation_order (str, optional): The order in which the features will be imputed. Possible values: "ascending" (From features with fewest missing values to most), "descending" (From features with most missing values to fewest, "roman" (Left to right), "arabic" (Right to left), random" (A random order for each round). Defaults to 'ascending'.
169
-
170
- skip_complete (bool, optional): If True then features with missing values during ``transform`` that did not have any missing values during ``fit`` will be imputed with the initial imputation method only. Set to ``True`` if you have many features with no missing values at both ``fit`` and ``transform`` time to save compute. Defaults to False.
171
-
172
- min_value (float or array-like of shape (n_features,), optional): Minimum possible imputed value. Broadcast to shape (n_features,) if scalar. If array-like, expects shape (n_features,), one min value for each feature. The default is `-np.inf`...versionchanged:: 0.23 (Added support for array-like). Defaults to -np.inf.
173
-
174
- max_value (float or array-like of shape (n_features,), optional): Maximum possible imputed value. Broadcast to shape (n_features,) if scalar. If array-like, expects shape (n_features,), one max value for each feature..versionchanged:: 0.23 (Added support for array-like). Defaults to np.inf.
175
-
176
- verbose (int, optional): Verbosity flag, controls the debug messages that are issued as functions are evaluated. The higher, the more verbose. Can be 0, 1, or 2. Defaults to 0.
177
-
178
- random_state (int or RandomState instance, optional): The seed of the pseudo random number generator to use. Randomizes selection of estimator features if n_nearest_features is not None, the ``imputation_order`` if ``random``\, and the sampling from posterior if ``sample_posterior`` is True. Use an integer for determinism. Defaults to None.
179
-
180
- add_indicator (bool, optional): If True, a :class:`MissingIndicator` transform will stack onto output of the imputer's transform. This allows a predictive estimator to account for missingness despite imputation. If a feature has no missing values at fit/train time, the feature won't appear on the missing indicator even if there are missing values at transform/test time. Defaults to False.
181
-
182
- genotype_data (GenotypeData object, optional): GenotypeData object containing dictionary with keys=sampleIds and values=list of genotypes for the corresponding key. If using ``initial_strategy="phylogeny``\, then this object also needs contain the treefile and qmatrix objects. Defaults to None.
183
-
184
- str_encodings (Dict[str, int], optional): Integer encodings used in STRUCTURE-formatted file. Should be a dictionary with keys=nucleotides and values=integer encodings. The missing data encoding should also be included. Argument is ignored if using a PHYLIP-formatted file. Defaults to {"A": 1, "C": 2, "G": 3, "T": 4, "N": -9}
185
-
186
- Attributes:
187
- initial_imputer_: (:class:`~sklearn.impute.SimpleImputer`): Imputer used to initialize the missing values.
188
-
189
- imputation_sequence_ (List[Tuple[numpy.ndarray]]): Each tuple has ``(feat_idx, neighbor_feat_idx, estimator)``\, where ``feat_idx`` is the current feature to be imputed, ``neighbor_feat_idx`` is the array of other features used to impute the current feature, and ``estimator`` is the trained estimator used for the imputation. Length is ``self.n_features_with_missing_ * self.n_iter_``\.
190
-
191
- n_iter_ (int): Number of iteration rounds that occurred. Will be less than ``self.max_iter`` if early stopping criterion was reached.
192
-
193
- n_features_with_missing_ (int): Number of features with missing values.
194
-
195
- indicator_ (:class:`~sklearn.impute.MissingIndicator`): Indicator used to add binary indicators for missing values ``None`` if add_indicator is False.
196
-
197
- random_state_ (RandomState instance): RandomState instance that is generated either from a seed, the random number generator or by ``np.random``\.
198
-
199
- genotype_data (GenotypeData object): GenotypeData object.
200
-
201
- str_encodings (Dict[str, int]): Dictionary with integer encodings for converting from STRUCTURE-formatted file to IUPAC nucleotides.
202
-
203
- See Also:
204
- SimpleImputer : Univariate imputation of missing values.
205
-
206
- Examples:
207
- >>> import numpy as np
208
- >>> from sklearn.experimental import enable_iterative_imputer
209
- >>> from sklearn.impute import IterativeImputer
210
- >>> imp_mean = IterativeImputer(random_state=0)
211
- >>> imp_mean.fit([[7, 2, 3], [4, np.nan, 6], [10, 5, 9]])
212
- >>> X = [[np.nan, 2, 3], [4, np.nan, 6], [10, np.nan, 9]]
213
- >>> imp_mean.transform(X)
214
- array([[ 6.9584..., 2. , 3. ],
215
- [ 4. , 2.6000..., 6. ],
216
- [10. , 4.9999..., 9. ]])
217
-
218
- Notes:
219
- To support imputation in inductive mode we store each feature's estimator during the ``fit`` phase, and predict without refitting (in order) during the ``transform`` phase. Features which contain all missing values at ``fit`` are discarded upon ``transform``\.
220
-
221
- References:
222
- .. [van Buuren & Groothuis-Oudshoorn, 2011] Stef van Buuren, Karin Groothuis-Oudshoorn (2011). mice: Multivariate Imputation by Chained Equations in R. Journal of Statistical Software 45: 1-67.
223
-
224
- .. [Buck, 1960] S. F. Buck. (1960). A Method of Estimation of Missing Values in Multivariate Data Suitable for use with an Electronic Computer. Journal of the Royal Statistical Society 22(2): 302-306.
225
- """
226
-
227
- def __init__(
228
- self,
229
- logfilepath: str,
230
- clf_kwargs: Dict[str, Any],
231
- ga_kwargs: Dict[str, Any],
232
- *,
233
- estimator: Callable = None,
234
- gridparams: Dict[str, Any] = None,
235
- prefix: str = "output",
236
- grid_cv: int = 5,
237
- grid_n_jobs: int = 1,
238
- grid_iter: int = 10,
239
- clf_type: str = "classifier",
240
- gridsearch_method: str = "gridsearch",
241
- disable_progressbar: bool = False,
242
- progress_update_percent: Optional[int] = None,
243
- pops: Optional[List[Union[str, int]]] = None,
244
- scoring_metric: str = "accuracy",
245
- early_stop_gen: int = 5,
246
- missing_values: Union[int, float] = np.nan,
247
- sample_posterior: bool = False,
248
- max_iter: int = 10,
249
- tol: float = 1e-3,
250
- n_nearest_features: Optional[int] = None,
251
- initial_strategy: str = "populations",
252
- imputation_order: str = "ascending",
253
- skip_complete: bool = False,
254
- min_value: Union[float, int, float] = -np.inf,
255
- max_value: Union[float, int, float] = np.inf,
256
- verbose: int = 0,
257
- random_state: Optional[int] = None,
258
- add_indicator: bool = False,
259
- genotype_data: Optional[Any] = None,
260
- str_encodings: Optional[Dict[str, int]] = None,
261
- ) -> None:
262
- super().__init__(
263
- estimator=estimator,
264
- missing_values=missing_values,
265
- sample_posterior=sample_posterior,
266
- max_iter=max_iter,
267
- tol=tol,
268
- n_nearest_features=n_nearest_features,
269
- initial_strategy=initial_strategy,
270
- imputation_order=imputation_order,
271
- skip_complete=skip_complete,
272
- min_value=min_value,
273
- max_value=max_value,
274
- verbose=verbose,
275
- random_state=random_state,
276
- add_indicator=add_indicator,
277
- )
278
-
279
- self.logfilepath = logfilepath
280
- self.gridparams = gridparams
281
- self.clf_kwargs = clf_kwargs
282
- self.ga_kwargs = ga_kwargs
283
- self.prefix = prefix
284
- self.estimator = estimator
285
- self.sample_posterior = sample_posterior
286
- self.max_iter = max_iter
287
- self.tol = tol
288
- self.n_nearest_features = n_nearest_features
289
- self.initial_strategy = initial_strategy
290
- self.imputation_order = imputation_order
291
- self.skip_complete = skip_complete
292
- self.min_value = min_value
293
- self.max_value = max_value
294
- self.verbose = verbose
295
- self.random_state = random_state
296
- self.genotype_data = genotype_data
297
- self.str_encodings = str_encodings
298
- self.grid_cv = grid_cv
299
- self.grid_n_jobs = grid_n_jobs
300
- self.grid_iter = grid_iter
301
- self.clf_type = clf_type
302
- self.gridsearch_method = gridsearch_method
303
- self.disable_progressbar = disable_progressbar
304
- self.progress_update_percent = progress_update_percent
305
- self.pops = pops
306
- self.scoring_metric = scoring_metric
307
- self.early_stop_gen = early_stop_gen
308
- self.missing_values = missing_values
309
-
310
- def _mode_1d(self, array_1d):
311
- """Get the mode of a 1D array.
312
-
313
- Args:
314
- array_1d (np.ndarray): 1D array to calculate the mode for.
315
-
316
- Returns:
317
- int: Most common value of the 1D array.
318
- """
319
- # Get unique elements and their corresponding counts
320
- vals, counts = np.unique(array_1d, return_counts=True)
321
-
322
- # Get the index of the most frequent element
323
- mode_idx = np.argmax(counts)
324
-
325
- # Return the mode
326
- return vals[mode_idx]
327
-
328
- # Define a function to remove columns with a unique count of 1 or 0
329
- def remove_single_unique_val_cols(self, array_2d, return_idx=False):
330
- # Apply np.unique to each column and get the counts of unique values (excluding np.nan)
331
- unique_counts = np.apply_along_axis(
332
- lambda x: len(np.unique(x[~np.isnan(x)])), axis=0, arr=array_2d
333
- )
334
-
335
- # Get the column indices where the count of unique values is greater than 1
336
- cols_to_keep = np.where(unique_counts > 1)[0]
337
-
338
- # Index into array_2d to keep only these columns
339
- array_2d_filtered = array_2d[:, cols_to_keep]
340
-
341
- if return_idx:
342
- return cols_to_keep
343
- else:
344
- return array_2d_filtered
345
-
346
- def _initial_imputation(
347
- self, X: np.ndarray, cols_to_keep: np.ndarray, in_fit: bool = False
348
- ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
349
- """Perform initial imputation for input X.
350
-
351
- Initially imputes training data using a simple imputation method.
352
-
353
- Args:
354
- X (numpy.ndarray, shape (n_samples, n_features)): Input data, where ``n_samples`` is the number of samples and ``n_features`` is the number of features.
355
-
356
- cols_to_keep (numpy.ndarray, shape (n_features,)): Column indices to keep. Only used if ``initial_strategy="phylogeny"``\.
357
-
358
- in_fit (bool, optional): Whether function is called in fit. Defaults to False.
359
-
360
- Returns:
361
- Xt (numpy.ndarray, shape (n_samples, n_features): Input data, where ``n_samples`` is the number of samples and ``n_features`` is the number of features.
362
-
363
- X_filled (numpy.ndarray, shape (n_samples, n_features)): [Input data with the most recent imputations.
364
-
365
- mask_missing_values (numpy.ndarray, shape (n_samples, n_features)): Input data's missing indicator matrix, where ``n_samples`` is the number of samples and ``n_features`` is the number of features.
366
-
367
- X_missing_mask (numpy.ndarray, shape (n_samples, n_features)): Input data's mask matrix indicating missing datapoints, where
368
- ``n_samples`` is the number of samples and ``n_features`` is the
369
- number of features.
370
- """
371
- if is_scalar_nan(self.missing_values):
372
- force_all_finite = "allow-nan"
373
- else:
374
- force_all_finite = True
375
-
376
- X = self._validate_data(
377
- X,
378
- dtype=FLOAT_DTYPES,
379
- order="F",
380
- reset=in_fit,
381
- force_all_finite=force_all_finite,
382
- )
383
-
384
- X[X < 0] = np.nan
385
-
386
- _check_inputs_dtype(X, self.missing_values)
387
-
388
- X_missing_mask = _get_mask(X, self.missing_values)
389
- mask_missing_values = X_missing_mask.copy()
390
-
391
- if self.initial_strategy == "populations":
392
- self.initial_imputer_ = simple_imputers.ImputeAlleleFreq(
393
- self.genotype_data,
394
- pops=self.pops,
395
- by_populations=True,
396
- missing=-9,
397
- write_output=False,
398
- output_format="array",
399
- verbose=False,
400
- iterative_mode=True,
401
- validation_mode=True,
402
- )
403
-
404
- X_filled = self.initial_imputer_.imputed
405
-
406
- elif self.initial_strategy == "phylogeny":
407
- if (
408
- self.genotype_data.qmatrix is None
409
- and self.genotype_data.qmatrix_iqtree is None
410
- ) or self.genotype_data.guidetree is None:
411
- raise AttributeError(
412
- "GenotypeData object was not initialized with "
413
- "qmatrix/ qmatrix_iqtree or guidetree arguments, "
414
- "but initial_strategy == 'phylogeny'"
415
- )
416
-
417
- else:
418
- self.initial_imputer_ = simple_imputers.ImputePhylo(
419
- genotype_data=self.genotype_data,
420
- str_encodings=self.str_encodings,
421
- write_output=False,
422
- disable_progressbar=True,
423
- column_subset=cols_to_keep,
424
- validation_mode=True,
425
- )
426
-
427
- X_filled = self.initial_imputer_.imputed
428
- valid_sites = self.initial_imputer_.valid_sites
429
-
430
- elif self.initial_strategy == "mf":
431
- self.initial_imputer_ = simple_imputers.ImputeMF(
432
- self.genotype_data,
433
- missing=-9,
434
- write_output=False,
435
- verbose=False,
436
- output_format="array",
437
- validation_mode=True,
438
- )
439
-
440
- X_filled = self.initial_imputer_.imputed
441
-
442
- else:
443
- if self.initial_imputer_ is None:
444
- self.initial_imputer_ = SimpleImputer(
445
- missing_values=self.missing_values,
446
- strategy=self.initial_strategy,
447
- )
448
- X_filled = self.initial_imputer_.fit_transform(X)
449
-
450
- else:
451
- X_filled = self.initial_imputer_.transform(X)
452
-
453
- valid_sites = self.initial_imputer_.statistics_
454
-
455
- Xt = X.copy()
456
-
457
- if self.initial_imputer_ == "phylogeny":
458
- valid_sites = np.apply_along_axis(self._mode_1d, axis=0, arr=Xt)
459
- valid_sites = valid_sites[cols_to_keep]
460
- valid_mask = np.flatnonzero(np.logical_not(np.isnan(valid_sites)))
461
- Xt = X[:, valid_mask]
462
- mask_missing_values = mask_missing_values[:, valid_mask]
463
- X_filled = X_filled[:, valid_mask]
464
-
465
- return Xt, X_filled, mask_missing_values, X_missing_mask
466
-
467
- @ignore_warnings(category=UserWarning)
468
- def _impute_one_feature(
469
- self,
470
- X_filled: np.ndarray,
471
- mask_missing_values: np.ndarray,
472
- feat_idx: int,
473
- neighbor_feat_idx: np.ndarray,
474
- estimator: Optional[Any] = None,
475
- fit_mode: bool = True,
476
- ) -> Tuple[np.ndarray, Optional[Any]]:
477
- """Impute a single feature from the others provided.
478
-
479
- This function predicts the missing values of one of the features using the current estimates of all the other features. The ``estimator`` must support ``return_std=True`` in its ``predict`` method for this function to work.
480
-
481
- Args:
482
- X_filled (numpy.ndarray): Input data with the most recent imputations.
483
-
484
- mask_missing_values (numpy.ndarray): Input data's missing indicator matrix.
485
-
486
- feat_idx (int): Index of the feature currently being imputed.
487
-
488
- neighbor_feat_idx (numpy.ndarray): Indices of the features to be used in imputing ``feat_idx``\.
489
-
490
- estimator (sklearn estimator object, optional): The estimator to use at this step of the round-robin imputation If ``sample_posterior`` is True, the estimator must support ``return_std`` in its ``predict`` method. If None, it will be cloned from self._estimator. Defaults to None.
491
-
492
- fit_mode (bool, optional): Whether to fit and predict with the estimator or just predict. Defaults to True.
493
-
494
- Returns:
495
- X_filled (ndarray): Input data with ``X_filled[missing_row_mask, feat_idx]`` updated.
496
-
497
- estimator (estimator with sklearn API): The fitted estimator used to impute ``X_filled[missing_row_mask, feat_idx]``\.
498
- """
499
- if estimator is None and fit_mode is False:
500
- raise ValueError(
501
- "If fit_mode is False, then an already-fitted "
502
- "estimator should be passed in."
503
- )
504
-
505
- if type(self._estimator).__name__ == "XGBClassifier":
506
- self.gridparams["objective"] = ["multi:softmax"]
507
- self.gridparams["num_class"] = [3]
508
-
509
- if estimator is None:
510
- estimator = clone(self._estimator)
511
-
512
- # Modified code
513
- cross_val = StratifiedKFold(n_splits=self.grid_cv, shuffle=True)
514
-
515
- # Modified code
516
- # If regressor
517
- if self.clf_type == "regressor":
518
- if self.gridsearch_method == "genetic_algorithm":
519
- callback = DeltaThreshold(threshold=1e-3, metric="fitness")
520
-
521
- else:
522
- if self.gridsearch_method == "genetic_algorithm":
523
- callback = ConsecutiveStopping(
524
- generations=self.early_stop_gen, metric="fitness"
525
- )
526
-
527
- # Do randomized grid search
528
- if self.gridsearch_method == "randomized_gridsearch":
529
- search = RandomizedSearchCV(
530
- estimator,
531
- param_distributions=self.gridparams,
532
- n_iter=self.grid_iter,
533
- scoring=self.scoring_metric,
534
- n_jobs=self.grid_n_jobs,
535
- cv=cross_val,
536
- )
537
-
538
- elif self.gridsearch_method == "gridsearch":
539
- search = GridSearchCV(
540
- estimator,
541
- param_grid=self.gridparams,
542
- scoring=self.scoring_metric,
543
- n_jobs=self.grid_n_jobs,
544
- cv=cross_val,
545
- error_score="raise",
546
- )
547
-
548
- # Do genetic algorithm
549
- elif self.gridsearch_method == "genetic_algorithm":
550
- with HiddenPrints():
551
- search = GASearchCV(
552
- estimator=estimator,
553
- cv=cross_val,
554
- scoring=self.scoring_metric,
555
- generations=self.grid_iter,
556
- param_grid=self.gridparams,
557
- n_jobs=self.grid_n_jobs,
558
- verbose=False,
559
- **self.ga_kwargs,
560
- )
561
-
562
- else:
563
- raise ValueError(
564
- f"Invalid gridsearch_method provided: {self.gridsearch_method}. Supported options are 'gridsearch', 'randomized_gridsearch', and 'genetic_algorithm'"
565
- )
566
-
567
- missing_row_mask = mask_missing_values[:, feat_idx]
568
-
569
- if fit_mode:
570
- X_train = _safe_indexing(
571
- X_filled[:, neighbor_feat_idx], ~missing_row_mask
572
- )
573
-
574
- y_train = _safe_indexing(X_filled[:, feat_idx], ~missing_row_mask)
575
- X_train = X_train.astype(int)
576
- y_train = y_train.astype(int)
577
-
578
- if self.gridsearch_method == "genetic_algorithm":
579
- if type(self._estimator).__name__ == "XGBClassifier":
580
- raise NotImplementedError(
581
- "genetic_algorithm is not currently supported with ImputeXGBoost."
582
- )
583
- search.fit(X_train, y_train, callbacks=callback)
584
- else:
585
- if type(self._estimator).__name__ == "XGBClassifier":
586
- oe = OrdinalEncoder(
587
- categories="auto",
588
- dtype=int,
589
- handle_unknown="use_encoded_value",
590
- unknown_value=-1,
591
- )
592
- X_train = oe.fit_transform(X_train)
593
-
594
- # Add one dummy sample for each possible class
595
- for class_label in range(
596
- 3
597
- ): # assuming there are 3 classes 0, 1, 2
598
- class_count = np.count_nonzero(y_train == class_label)
599
- if (
600
- class_label not in y_train
601
- or class_count < self.grid_cv
602
- ):
603
- for _ in range(
604
- self.grid_cv - class_count
605
- ): # add as many dummy samples as there are folds
606
- dummy_sample = np.zeros((1, X_train.shape[1]))
607
- X_train = np.vstack([X_train, dummy_sample])
608
- y_train = np.append(y_train, class_label)
609
-
610
- # Fit the LabelEncoder after adding the dummy samples
611
- le = LabelEncoder()
612
- y_train = le.fit_transform(y_train)
613
- sample_weight = compute_sample_weight("balanced", y_train)
614
-
615
- search.fit(X_train, y_train, sample_weight=sample_weight)
616
- else:
617
- search.fit(X_train, y_train)
618
-
619
- # if no missing values, don't predict
620
- if np.sum(missing_row_mask) == 0:
621
- return X_filled, None
622
-
623
- X_test = _safe_indexing(
624
- X_filled[:, neighbor_feat_idx], missing_row_mask
625
- )
626
-
627
- X_test = X_test.astype(int)
628
-
629
- if type(self._estimator).__name__ == "XGBClassifier":
630
- X_test = oe.transform(X_test)
631
-
632
- # Currently un-tested with grid search
633
- if self.sample_posterior:
634
- raise NotImplementedError(
635
- "sample_posterior is not implemented in PG-SUI"
636
- )
637
-
638
- else:
639
- imputed_values = search.predict(X_test)
640
-
641
- if type(self._estimator).__name__ == "XGBClassifier":
642
- imputed_values = le.inverse_transform(imputed_values)
643
-
644
- imputed_values = np.clip(
645
- imputed_values,
646
- self._min_value[feat_idx],
647
- self._max_value[feat_idx],
648
- )
649
-
650
- # update the feature
651
- X_filled[missing_row_mask, feat_idx] = imputed_values
652
-
653
- del X_train
654
- del y_train
655
- del X_test
656
- del imputed_values
657
- gc.collect()
658
-
659
- return X_filled, search
660
-
661
- @ignore_warnings(category=UserWarning)
662
- def fit_transform(
663
- self,
664
- X: np.ndarray,
665
- valid_cols: Optional[np.ndarray] = None,
666
- y: None = None,
667
- ) -> Tuple[np.ndarray, Optional[List[Any]], Optional[List[Any]]]:
668
- """Fits the imputer on X and return the transformed X.
669
-
670
- The basic functionality is to get the nearest neightbors for each feature (column) and loop through all the features and their correlated neighbors to predict missing values.
671
-
672
- Functionality has been added to perform grid searches using two methods (genetic algorithm and RandomSearchCV). It also makes several useful plots if using the genetic algorithm, and a tqdm progress bar and status updates have been added.
673
-
674
- Args:
675
- X (array-like, shape (n_samples, n_features)): Input data, where "n_samples" is the number of samples and "n_features" is the number of features.
676
-
677
- valid_cols (numpy.ndarray, optional): Array with column indices to keep. Defaults to None.
678
-
679
- y (None, optional): Ignored. Here for compatibility with other sklearn classes. Defaults to None.
680
-
681
- Returns:
682
- array-like, shape (n_samples, n_features)): The imputed input data.
683
- List[Union[str, int, float]]: List of parameter settings found.
684
- List[Union[int, float]]: List of scores.
685
- """
686
- self.random_state_ = getattr(
687
- self, "random_state_", check_random_state(self.random_state)
688
- )
689
-
690
- if self.max_iter < 0:
691
- raise ValueError(
692
- f"'max_iter' should be a positive integer. Got {self.max_iter} instead."
693
- )
694
-
695
- if self.tol < 0:
696
- raise ValueError(
697
- f"'tol' should be a non-negative float. Got {self.tol} instead"
698
- )
699
-
700
- self._estimator = clone(self.estimator)
701
-
702
- self.initial_imputer_ = None
703
-
704
- X, Xt, mask_missing_values, complete_mask = self._initial_imputation(
705
- X.copy(), valid_cols, in_fit=True
706
- )
707
-
708
- super(IterativeImputer, self)._fit_indicator(complete_mask)
709
- X_indicator = super(IterativeImputer, self)._transform_indicator(
710
- complete_mask
711
- )
712
-
713
- if self.max_iter == 0 or np.all(mask_missing_values):
714
- self.n_iter_ = 0
715
- return (
716
- super(IterativeImputer, self)._concatenate_indicator(
717
- Xt, X_indicator
718
- ),
719
- None,
720
- None,
721
- )
722
-
723
- # Edge case: a single feature. We return the initial ...
724
- if Xt.shape[1] == 1:
725
- self.n_iter_ = 0
726
- return (
727
- super(IterativeImputer, self)._concatenate_indicator(
728
- Xt, X_indicator
729
- ),
730
- None,
731
- None,
732
- )
733
-
734
- self._min_value = self._validate_limit(
735
- self.min_value, "min", X.shape[1]
736
- )
737
- self._max_value = self._validate_limit(
738
- self.max_value, "max", X.shape[1]
739
- )
740
-
741
- if not np.all(np.greater(self._max_value, self._min_value)):
742
- raise ValueError(
743
- "One (or more) features have min_value >= max_value."
744
- )
745
-
746
- # order in which to impute
747
- # note this is probably too slow for large feature data (d > 100000)
748
- # and a better way would be good.
749
- # see: https://goo.gl/KyCNwj and subsequent comments
750
- ordered_idx = self._get_ordered_idx(mask_missing_values)
751
- total_features = len(ordered_idx)
752
-
753
- self.n_features_with_missing_ = len(ordered_idx)
754
-
755
- abs_corr_mat = self._get_abs_corr_mat(Xt)
756
-
757
- _, n_features = Xt.shape
758
-
759
- if self.verbose > 0:
760
- print(
761
- f"[IterativeImputer] Completing matrix with shape ({X.shape},)"
762
- )
763
- start_t = time()
764
-
765
- if not self.sample_posterior:
766
- Xt_previous = Xt.copy()
767
- normalized_tol = self.tol * np.max(np.abs(X[~mask_missing_values]))
768
-
769
- params_list = list()
770
- score_list = list()
771
- iter_list = list()
772
-
773
- if self.gridsearch_method == "genetic_algorithm":
774
- sns.set_style("white")
775
-
776
- total_iter = self.max_iter
777
-
778
- #######################################
779
- ### Iterations
780
- #######################################
781
- for self.n_iter_ in progressbar(
782
- range(1, total_iter + 1),
783
- desc="Iteration: ",
784
- disable=self.disable_progressbar,
785
- ):
786
- if self.gridsearch_method == "genetic_algorithm":
787
- iter_list.append(self.n_iter_)
788
-
789
- pp_oneline = PdfPages(
790
- f".score_traces_separate_{self.n_iter_}.pdf"
791
- )
792
-
793
- pp_lines = PdfPages(
794
- f".score_traces_combined_{self.n_iter_}.pdf"
795
- )
796
-
797
- pp_space = PdfPages(f".search_space_{self.n_iter_}.pdf")
798
-
799
- if self.imputation_order == "random":
800
- ordered_idx = self._get_ordered_idx(mask_missing_values)
801
-
802
- # Reset lists for current iteration
803
- params_list.clear()
804
- score_list.clear()
805
- searches = list()
806
-
807
- if self.disable_progressbar:
808
- with open(self.logfilepath, "a") as fout:
809
- # Redirect to progress logfile
810
- with redirect_stdout(fout):
811
- print(
812
- f"Iteration Progress: {self.n_iter_}/{self.max_iter} ({int((self.n_iter_ / total_iter) * 100)}%)"
813
- )
814
-
815
- if self.progress_update_percent is not None:
816
- print_perc_interval = self.progress_update_percent
817
-
818
- ########################################
819
- ### Features
820
- ########################################
821
- for i, feat_idx in enumerate(
822
- progressbar(
823
- ordered_idx,
824
- desc="Feature: ",
825
- leave=False,
826
- position=1,
827
- disable=self.disable_progressbar,
828
- ),
829
- start=1,
830
- ):
831
- neighbor_feat_idx = self._get_neighbor_feat_idx(
832
- n_features, feat_idx, abs_corr_mat
833
- )
834
-
835
- Xt, search = self._impute_one_feature(
836
- Xt,
837
- mask_missing_values,
838
- feat_idx,
839
- neighbor_feat_idx,
840
- estimator=None,
841
- fit_mode=True,
842
- )
843
-
844
- searches.append(search)
845
-
846
- # NOTE: The below source code has been commented out to save
847
- # RAM. estimator_triplet object contains numerous fit estimators
848
- # that demand a lot of resources. It is primarily used for the
849
- # transform function, which is not needed in this application.
850
-
851
- # estimator_triplet = _ImputerTripletGrid(feat_idx,
852
- # neighbor_feat_idx,
853
- # estimator)
854
-
855
- # self.imputation_sequence_.append(estimator_triplet)
856
-
857
- if search is not None:
858
- # There was missing data in the feature
859
- params_list.append(search.best_params_)
860
- score_list.append(search.best_score_)
861
-
862
- if self.gridsearch_method == "genetic_algorithm":
863
- plt.cla()
864
- plt.clf()
865
- plt.close()
866
-
867
- plot_fitness_evolution(search)
868
- pp_oneline.savefig(bbox_inches="tight")
869
- plt.cla()
870
- plt.clf()
871
- plt.close()
872
-
873
- Plotting.plot_search_space(search)
874
- pp_space.savefig(bbox_inches="tight")
875
- plt.cla()
876
- plt.clf()
877
- plt.close()
878
-
879
- else:
880
- # Search is None
881
- # Thus, there was no missing data in the given feature
882
- tmp_dict = dict()
883
- for k in self.gridparams.keys():
884
- tmp_dict[k] = -9
885
- params_list.append(tmp_dict)
886
-
887
- score_list.append(-9)
888
-
889
- # Only print feature updates at each progress_update_percent
890
- # interval
891
- if (
892
- self.progress_update_percent is not None
893
- and self.disable_progressbar
894
- ):
895
- current_perc = math.ceil((i / total_features) * 100)
896
-
897
- if current_perc >= print_perc_interval:
898
- with open(self.logfilepath, "a") as fout:
899
- # Redirect progress to file
900
- with redirect_stdout(fout):
901
- print(
902
- f"Feature Progress (Iteration "
903
- f"{self.n_iter_}/{self.max_iter}): "
904
- f"{i}/{total_features} ({current_perc}"
905
- f"%)"
906
- )
907
-
908
- if i == len(ordered_idx):
909
- with redirect_stdout(fout):
910
- print("")
911
-
912
- while print_perc_interval <= current_perc:
913
- print_perc_interval += self.progress_update_percent
914
-
915
- if self.verbose > 1:
916
- print(
917
- f"[IterativeImputer] Ending imputation round "
918
- f"{self.n_iter_}/{self.max_iter}, "
919
- f"elapsed time {(time() - start_t):0.2f}"
920
- )
921
-
922
- if not self.sample_posterior:
923
- inf_norm = np.linalg.norm(
924
- Xt - Xt_previous, ord=np.inf, axis=None
925
- )
926
- if self.verbose > 0:
927
- print(
928
- f"[IterativeImputer] Change: {inf_norm}, "
929
- f"scaled tolerance: {normalized_tol} "
930
- )
931
-
932
- if inf_norm < normalized_tol:
933
- if self.disable_progressbar:
934
- # Early stopping criteria has been reached
935
- with open(self.logfilepath, "a") as fout:
936
- # Redirect to progress logfile
937
- with redirect_stdout(fout):
938
- print(
939
- "[IterativeImputer] Early stopping "
940
- "criterion reached."
941
- )
942
- else:
943
- print(
944
- "[IterativeImputer] Early stopping criterion "
945
- "reached."
946
- )
947
-
948
- if self.gridsearch_method == "genetic_algorithm":
949
- pp_oneline.close()
950
- pp_space.close()
951
-
952
- plt.cla()
953
- plt.clf()
954
- plt.close()
955
- for iter_search in searches:
956
- if iter_search is not None:
957
- plot_fitness_evolution(iter_search)
958
-
959
- pp_lines.savefig(bbox_inches="tight")
960
-
961
- plt.cla()
962
- plt.clf()
963
- plt.close()
964
- pp_lines.close()
965
-
966
- break
967
- Xt_previous = Xt.copy()
968
-
969
- if self.gridsearch_method == "genetic_algorithm":
970
- pp_oneline.close()
971
- pp_space.close()
972
-
973
- plt.cla()
974
- plt.clf()
975
- plt.close()
976
- for iter_search in searches:
977
- if iter_search is not None:
978
- plot_fitness_evolution(iter_search)
979
-
980
- pp_lines.savefig(bbox_inches="tight")
981
-
982
- plt.cla()
983
- plt.clf()
984
- plt.close()
985
- pp_lines.close()
986
-
987
- else:
988
- if not self.sample_posterior:
989
- warnings.warn(
990
- "[IterativeImputer] Early stopping criterion not"
991
- " reached.",
992
- ConvergenceWarning,
993
- )
994
-
995
- Xt[~mask_missing_values] = X[~mask_missing_values]
996
- Xt = Xt.astype(int)
997
-
998
- if self.gridsearch_method == "genetic_algorithm":
999
- # Remove all files except last iteration
1000
- final_iter = iter_list.pop()
1001
-
1002
- [os.remove(f".score_traces_separate_{x}.pdf") for x in iter_list]
1003
- [os.remove(f".score_traces_combined_{x}.pdf") for x in iter_list]
1004
- [os.remove(f".search_space_{x}.pdf") for x in iter_list]
1005
-
1006
- shutil.move(
1007
- f".score_traces_separate_{final_iter}.pdf",
1008
- f"{self.prefix}_score_traces_separate.pdf",
1009
- )
1010
-
1011
- shutil.move(
1012
- f".score_traces_combined_{final_iter}.pdf",
1013
- f"{self.prefix}_score_traces_combined.pdf",
1014
- )
1015
-
1016
- shutil.move(
1017
- f".search_space_{final_iter}.pdf",
1018
- f"{self.prefix}_search_space.pdf",
1019
- )
1020
-
1021
- return (
1022
- super(IterativeImputer, self)._concatenate_indicator(
1023
- Xt, X_indicator
1024
- ),
1025
- params_list,
1026
- score_list,
1027
- )