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,785 +0,0 @@
1
- # Standard library imports
2
- import gc
3
- import math
4
- import os
5
- import sys
6
- import warnings
7
-
8
- warnings.simplefilter(action="ignore", category=FutureWarning)
9
-
10
-
11
- # from collections import namedtuple
12
- from contextlib import redirect_stdout
13
- from time import time
14
- from typing import Optional, Union, List, Dict, Tuple, Any, Callable
15
-
16
- # Third-party imports
17
- ## For stats and numeric operations
18
- import numpy as np
19
- import pandas as pd
20
- from scipy import stats
21
-
22
- # scikit-learn imports
23
- from sklearn.base import clone
24
- from sklearn.experimental import enable_iterative_imputer
25
- from sklearn.impute import IterativeImputer
26
- from sklearn.impute import SimpleImputer
27
- from sklearn.impute._base import _check_inputs_dtype
28
-
29
- ## For warnings
30
- from sklearn.exceptions import ConvergenceWarning
31
- from sklearn.utils._testing import ignore_warnings
32
-
33
- ## Required for IterativeImputer.fit_transform()
34
- from sklearn.utils import check_random_state, _safe_indexing, is_scalar_nan
35
- from sklearn.utils._mask import _get_mask
36
- from sklearn.utils.validation import FLOAT_DTYPES
37
- from sklearn.preprocessing import LabelEncoder
38
-
39
- # Custom function imports
40
- try:
41
- from .. import simple_imputers
42
- from ...utils.misc import get_processor_name
43
- from ...utils.misc import HiddenPrints
44
- from ...utils.misc import isnotebook
45
- except (ModuleNotFoundError, ValueError, ImportError):
46
- from pgsui.impute import simple_imputers
47
- from pgsui.utils.misc import get_processor_name
48
- from pgsui.utils.misc import HiddenPrints
49
- from pgsui.utils.misc import isnotebook
50
-
51
- # Uses scikit-learn-intellex package if CPU is Intel
52
- if get_processor_name().strip().startswith("Intel"):
53
- try:
54
- from sklearnex import patch_sklearn
55
-
56
- patch_sklearn(verbose=False)
57
- except (ImportError, TypeError):
58
- print(
59
- "Processor not compatible with scikit-learn-intelex; using "
60
- "default configuration"
61
- )
62
-
63
- is_notebook = isnotebook()
64
-
65
- if is_notebook:
66
- from tqdm.notebook import tqdm as progressbar
67
- else:
68
- if sys.platform == "linux" or sys.platform == "linux2":
69
- from tqdm.auto import tqdm as progressbar
70
- else:
71
- from tqdm import tqdm as progressbar
72
-
73
- # NOTE: Removed ImputeTriplets to save memory.
74
- # ImputerTriplet is there so that the missing values
75
- # can be predicted on an already-fit model using just the
76
- # transform method. I didn't need it, so I removed it
77
- # because it was saving thousands of fit estimator models into the object
78
-
79
- # _ImputerTripletAll = namedtuple(
80
- # '_ImputerTripletAll', ['feat_idx', 'neighbor_feat_idx', 'estimator'])
81
-
82
-
83
- class IterativeImputerFixedParams(IterativeImputer):
84
- """Overridden IterativeImputer methods.
85
-
86
- Herein, progress status updates, optimizations to save RAM, 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 versionadded: 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``\.
87
-
88
- IterativeImputer is based on the R MICE (Multivariate Imputation by Chained Equationspackage) [3]_. See [4]_ for more information about multiple versus single imputations.
89
-
90
- >>> # explicitly require this experimental feature
91
- >>> from sklearn.experimental import enable_iterative_imputer
92
- >>>
93
- >>> # now you can import normally from sklearn.impute
94
- >>> from sklearn.impute import IterativeImputer
95
-
96
- Args:
97
- logfilepath (str): Path to the progress log file.
98
-
99
- clf_kwargs (Dict[str, Any]): A dictionary with the classifier keyword arguments.
100
-
101
- prefix (str): Prefix for output files.
102
-
103
- estimator (callable estimator object, optional): The estimator to use at each step of the round-robin imputation. If ``sample_posterior`` is True, the estimator must support ``return_std`` in its ``predict`` method. Defaults to BayesianRidge().
104
-
105
- clf_type (str, optional): Whether to run ```'classifier'``` or ``'regression'`` based imputation. Defaults to 'classifier'
106
-
107
- 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.
108
-
109
- progress_update_percent (int, optional): How often to display progress updates (as a percentage) if ``disable_progressbar`` is True. If ``progress_update_frequency=10``\, then it displays progress updates every 10%. Defaults to 10.
110
-
111
- pops (List[Union[str, int]] or None): List of population IDs to be used with ImputeAlleleFreq if ``initial_strategy="populations"``\.
112
-
113
- 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.
114
-
115
- Sample_posterior (bool, optional): 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.
116
-
117
- 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.
118
-
119
- tol (float, optional): Tolerance of the stopping condition. Defaults to 1e-3.
120
-
121
- 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.
122
-
123
- 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: "mean", "median", "most_frequent", "populations", "phylogeny", "mf", or "constant". Defaults to "mean".
124
-
125
- 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".
126
-
127
- 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.
128
-
129
- 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`...sklearn versionchanged:: 0.23 (Added support for array-like). Defaults to -np.inf.
130
-
131
- 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..sklearn versionchanged:: 0.23 (Added support for array-like). Defaults to np.inf.
132
-
133
- 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.
134
-
135
- 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.
136
-
137
- 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.
138
-
139
- 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.
140
-
141
- 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}
142
-
143
- kwargs (Dict[str, Any]): For compatibility with grid search IterativeImputer.
144
-
145
- Attributes:
146
- initial_imputer_ (sklearn.impute.SimpleImputer): Imputer used to initialize the missing values.
147
-
148
- n_iter_ (int): Number of iteration rounds that occurred. Will be less than ``self.max_iter`` if early stopping criterion was reached.
149
-
150
- n_features_with_missing_ (int): Number of features with missing values.
151
-
152
- indicator_ (sklearn.impute.MissingIndicator): Indicator used to add binary indicators for missing values ``None`` if add_indicator is False.
153
-
154
- random_state_ (RandomState instance): RandomState instance that is generated either from a seed, the random number generator or by ``np.random``\.
155
-
156
- logfilepath (str): Path to status logfile.
157
-
158
- clf_kwargs (Dict[str, Any]): Keyword arguments for estimator.
159
-
160
- prefix (str): Prefix for output files.
161
-
162
- clf_type (str): Type of estimator, either "classifier" or "regressor".
163
-
164
- disable_progressbar (bool): Whether to disable the tqdm progress bar. If True, writes status updates to file instead of tqdm progress bar.
165
-
166
- progress_update_percent (float or None): Print feature progress update every ``progress_update_percent`` percent.
167
-
168
- pops (List[Union[str, int]]): List of population IDs of shape (n_samples,).
169
-
170
- estimator (estimator object): Estimator to impute data with.
171
-
172
- sample_posterior (bool): Whether to use the sample_posterior option. This overridden class does not currently support sample_posterior.
173
-
174
- max_iter (int): The maximum number of iterations to run.
175
-
176
- tol (float): Convergence criteria.
177
-
178
- n_nearest_features (int): Number of nearest features to impute target with.
179
-
180
- initial_strategy (str): Strategy to use with SimpleImputer for training data.
181
-
182
- imputation_order (str): Order to impute.
183
-
184
- skip_complete (bool): Whether to skip features with no missing data.
185
-
186
- min_value (int or float): Minimum value of imputed data.
187
-
188
- max_value (int or float): Maximum value of imputed data.
189
-
190
- verbose (int): Verbosity level.
191
-
192
- genotype_data (GenotypeData object): GenotypeData object.
193
-
194
- str_encodings (Dict[str, int]): Dictionary with integer encodings for converting from STRUCTURE-formatted file to IUPAC nucleotides.
195
-
196
- See Also:
197
- SimpleImputer : Univariate imputation of missing values.
198
-
199
- Examples:
200
- >>> import numpy as np
201
- >>> from sklearn.experimental import enable_iterative_imputer
202
- >>> from sklearn.impute import IterativeImputer
203
- >>> imp_mean = IterativeImputer(random_state=0)
204
- >>> imp_mean.fit([[7, 2, 3], [4, np.nan, 6], [10, 5, 9]])
205
- >>> X = [[np.nan, 2, 3], [4, np.nan, 6], [10, np.nan, 9]]
206
- >>> imp_mean.transform(X)
207
- array([[ 6.9584..., 2. , 3. ],
208
- [ 4. , 2.6000..., 6. ],
209
- [10. , 4.9999..., 9. ]])
210
-
211
- Notes:
212
- 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``\.
213
-
214
- NOTE: Inductive mode support was removed herein.
215
-
216
- References:
217
- .. [3] Stef van Buuren, Karin Groothuis-Oudshoorn (2011). mice: Multivariate Imputation by Chained Equations in R. Journal of Statistical Software 45: 1-67.
218
-
219
- .. [4] 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.
220
- """
221
-
222
- def __init__(
223
- self,
224
- logfilepath: str,
225
- clf_kwargs: Dict[str, Any],
226
- *,
227
- estimator: Callable = None,
228
- clf_type: str = "classifier",
229
- disable_progressbar: bool = False,
230
- progress_update_percent: Optional[int] = None,
231
- pops: Optional[List[Union[str, int]]] = None,
232
- missing_values: Union[float, int] = np.nan,
233
- sample_posterior: bool = False,
234
- max_iter: int = 10,
235
- tol: float = 1e-3,
236
- n_nearest_features: Optional[int] = None,
237
- initial_strategy: str = "mean",
238
- imputation_order: str = "ascending",
239
- skip_complete: bool = False,
240
- min_value: Union[int, float] = -np.inf,
241
- max_value: Union[int, float] = np.inf,
242
- verbose: int = 0,
243
- random_state: Optional[int] = None,
244
- add_indicator: bool = False,
245
- genotype_data: Optional[Any] = None,
246
- str_encodings: Optional[Dict[str, int]] = None,
247
- prefix="imputer",
248
- **kwargs,
249
- ) -> None:
250
- super().__init__(
251
- estimator=estimator,
252
- missing_values=missing_values,
253
- sample_posterior=sample_posterior,
254
- max_iter=max_iter,
255
- tol=tol,
256
- n_nearest_features=n_nearest_features,
257
- initial_strategy=initial_strategy,
258
- imputation_order=imputation_order,
259
- skip_complete=skip_complete,
260
- min_value=min_value,
261
- max_value=max_value,
262
- verbose=verbose,
263
- random_state=random_state,
264
- add_indicator=add_indicator,
265
- )
266
-
267
- self.logfilepath = logfilepath
268
- self.clf_kwargs = clf_kwargs
269
- self.prefix = prefix
270
- self.clf_type = clf_type
271
- self.disable_progressbar = disable_progressbar
272
- self.progress_update_percent = progress_update_percent
273
- self.pops = pops
274
- self.estimator = estimator
275
- self.sample_posterior = sample_posterior
276
- self.max_iter = max_iter
277
- self.tol = tol
278
- self.n_nearest_features = n_nearest_features
279
- self.initial_strategy = initial_strategy
280
- self.imputation_order = imputation_order
281
- self.skip_complete = skip_complete
282
- self.min_value = min_value
283
- self.max_value = max_value
284
- self.verbose = verbose
285
- self.random_state = random_state
286
- self.genotype_data = genotype_data
287
- self.str_encodings = str_encodings
288
- self.missing_values = missing_values
289
-
290
- def _initial_imputation(
291
- self, X: np.ndarray, cols_to_keep: np.ndarray, in_fit: bool = False
292
- ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
293
- """Perform initial imputation for input X.
294
-
295
- Performs initial imputation on training data (neighbors).
296
-
297
- Args:
298
- X (ndarray): Input data of shape (n_samples, n_features), where n_samples is the number of samples and n_features is the number of features.
299
-
300
- cols_to_keep (numpy.ndarray): Column indices of shape (n_features,) to keep. Only used if ``initial_strategy=="phylogeny"``\.
301
-
302
- in_fit (bool, optional): True if function is called in fit, otherwise False. Defaults to False.
303
-
304
- Returns:
305
- Xt (numpy.ndarray): Input data of shape (n_samples, n_features), where n_samples is the number of samples and "n_features" is the number of features.
306
-
307
- X_filled (numpy.ndarray): Input data of shape (n_samples, features) with the most recent imputations.
308
-
309
- mask_missing_values (numpy.ndarray): Input data missing indicator matrix of of shape (n_samples, n_features), where n_samples is the number of samples and "n_features" is the number of features.
310
-
311
- X_missing_mask (numpy.ndarray): Input data mask matrix of shape (n_samples, n_features) indicating missing datapoints, where
312
- n_samples is the number of samples and n_features is the
313
- number of features.
314
-
315
- Raises:
316
- AttributeError: GenotypeData object must be initialized with guidetree and qmatrix if using ``initial_strategy=phylogeny``\.
317
- """
318
- if is_scalar_nan(self.missing_values):
319
- force_all_finite = "allow-nan"
320
- else:
321
- force_all_finite = True
322
-
323
- X = self._validate_data(
324
- X,
325
- dtype=FLOAT_DTYPES,
326
- order="F",
327
- reset=in_fit,
328
- force_all_finite=force_all_finite,
329
- )
330
-
331
- X[X < 0] = np.nan
332
-
333
- _check_inputs_dtype(X, self.missing_values)
334
-
335
- X_missing_mask = _get_mask(X, self.missing_values)
336
- mask_missing_values = X_missing_mask.copy()
337
-
338
- if self.initial_strategy == "populations":
339
- self.initial_imputer_ = simple_imputers.ImputeAlleleFreq(
340
- self.genotype_data,
341
- gt=np.nan_to_num(X, nan=-9).tolist(),
342
- pops=self.pops,
343
- by_populations=True,
344
- missing=-9,
345
- verbose=False,
346
- iterative_mode=True,
347
- validation_mode=True,
348
- )
349
-
350
- X_filled = np.array(self.initial_imputer_.imputed)
351
- Xt = X.copy()
352
-
353
- elif self.initial_strategy == "phylogeny":
354
- if (
355
- self.genotype_data.qmatrix is None
356
- and self.genotype_data.qmatrix_iqtree is None
357
- ) or self.genotype_data.guidetree is None:
358
- raise AttributeError(
359
- "GenotypeData object was not initialized with "
360
- "qmatrix/ qmatrix_iqtree or guidetree arguments, "
361
- "but initial_strategy == 'phylogeny'"
362
- )
363
-
364
- else:
365
- self.initial_imputer_ = simple_imputers.ImputePhylo(
366
- genotype_data=self.genotype_data,
367
- str_encodings=self.str_encodings,
368
- write_output=False,
369
- disable_progressbar=True,
370
- column_subset=cols_to_keep,
371
- validation_mode=True,
372
- )
373
-
374
- X_filled = self.initial_imputer_.imputed.to_numpy()
375
- valid_sites = self.initial_imputer_.valid_sites
376
-
377
- valid_mask = np.flatnonzero(
378
- np.logical_not(np.isnan(valid_sites))
379
- )
380
-
381
- Xt = X[:, valid_mask]
382
- mask_missing_values = mask_missing_values[:, valid_mask]
383
-
384
- elif self.initial_strategy == "mf":
385
- self.initial_imputer_ = simple_imputers.ImputeMF(
386
- self.genotype_data,
387
- gt=np.nan_to_num(X, nan=-9),
388
- missing=-9,
389
- verbose=False,
390
- validation_mode=True,
391
- )
392
-
393
- X_filled = np.array(self.initial_imputer_.imputed)
394
- Xt = X.copy()
395
-
396
- elif self.initial_strategy == "phylogeny":
397
- if (
398
- self.genotype_data.qmatrix is None
399
- and self.genotype_data.qmatrix_iqtree is None
400
- ) or self.genotype_data.guidetree is None:
401
- raise AttributeError(
402
- "GenotypeData object was not initialized with "
403
- "qmatrix/ qmatrix_iqtree or guidetree arguments, "
404
- "but initial_strategy == 'phylogeny'"
405
- )
406
-
407
- else:
408
- self.initial_imputer_ = simple_imputers.ImputePhylo(
409
- genotype_data=self.genotype_data,
410
- str_encodings=self.str_encodings,
411
- write_output=False,
412
- disable_progressbar=True,
413
- column_subset=cols_to_keep,
414
- validation_mode=True,
415
- )
416
-
417
- X_filled = self.initial_imputer_.imputed.to_numpy()
418
- Xt = X.copy()
419
-
420
- else:
421
- if self.initial_imputer_ is None:
422
- self.initial_imputer_ = SimpleImputer(
423
- missing_values=self.missing_values,
424
- strategy=self.initial_strategy,
425
- )
426
- X_filled = self.initial_imputer_.fit_transform(X)
427
-
428
- else:
429
- X_filled = self.initial_imputer_.transform(X)
430
-
431
- valid_mask = np.flatnonzero(
432
- np.logical_not(np.isnan(self.initial_imputer_.statistics_))
433
- )
434
-
435
- Xt = X[:, valid_mask]
436
- mask_missing_values = mask_missing_values[:, valid_mask]
437
-
438
- return Xt, X_filled, mask_missing_values, X_missing_mask
439
-
440
- @ignore_warnings(category=UserWarning)
441
- def _impute_one_feature(
442
- self,
443
- X_filled: np.ndarray,
444
- mask_missing_values: np.ndarray,
445
- feat_idx: int,
446
- neighbor_feat_idx: np.ndarray,
447
- estimator: Optional[Any] = None,
448
- fit_mode: bool = True,
449
- ) -> np.ndarray:
450
- """Impute a single feature from the others provided.
451
-
452
- 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.
453
-
454
- Args:
455
- X_filled (numpy.ndarray): Input data with the most recent imputations.
456
-
457
- mask_missing_values (numpy.ndarray): Input data's missing indicator matrix.
458
-
459
- feat_idx (int): Index of the feature currently being imputed.
460
-
461
- neighbor_feat_idx (numpy.ndarray): Indices of the features to be used in imputing ``feat_idx``\.
462
-
463
- estimator (object): 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.
464
-
465
- fit_mode (bool, optional): Whether to fit and predict with the estimator or just predict. Defaults to True.
466
-
467
- Returns:
468
- X_filled (numpy.ndarray)]: Input data with ``X_filled[missing_row_mask, feat_idx]`` updated.
469
- """
470
- if estimator is None and fit_mode is False:
471
- raise ValueError(
472
- "If fit_mode is False, then an already-fitted "
473
- "estimator should be passed in."
474
- )
475
-
476
- if estimator is None:
477
- estimator = clone(self._estimator)
478
-
479
- missing_row_mask = mask_missing_values[:, feat_idx]
480
-
481
- if fit_mode:
482
- X_train = _safe_indexing(
483
- X_filled[:, neighbor_feat_idx], ~missing_row_mask
484
- )
485
-
486
- y_train = _safe_indexing(X_filled[:, feat_idx], ~missing_row_mask)
487
-
488
- try:
489
- estimator.fit(X_train, y_train)
490
- le = None
491
- except ValueError as e:
492
- # Happens in newer versions of XGBClassifier.
493
- if str(e).startswith(
494
- "Invalid classes inferred from unique values of `y`"
495
- ):
496
- le = LabelEncoder()
497
- y_train = le.fit_transform(y_train)
498
- estimator.fit(X_train, y_train)
499
-
500
- # if no missing values, don't predict
501
- if np.sum(missing_row_mask) == 0:
502
- return X_filled
503
-
504
- X_test = _safe_indexing(
505
- X_filled[:, neighbor_feat_idx], missing_row_mask
506
- )
507
-
508
- if self.sample_posterior:
509
- raise NotImplementedError(
510
- "sample_posterior is not currently supported. "
511
- "Please set sample_posterior to False"
512
- )
513
-
514
- else:
515
- imputed_values = estimator.predict(X_test)
516
-
517
- if le is not None:
518
- imputed_values = le.inverse_transform(imputed_values)
519
-
520
- imputed_values = np.clip(
521
- imputed_values,
522
- self._min_value[feat_idx],
523
- self._max_value[feat_idx],
524
- )
525
-
526
- # update the feature
527
- X_filled[missing_row_mask, feat_idx] = imputed_values
528
-
529
- del estimator
530
- del X_train
531
- del y_train
532
- del X_test
533
- del imputed_values
534
- gc.collect()
535
-
536
- return X_filled
537
-
538
- @ignore_warnings(category=UserWarning)
539
- def fit_transform(
540
- self,
541
- X: np.ndarray,
542
- valid_cols: Optional[np.ndarray] = None,
543
- y: None = None,
544
- ) -> np.ndarray:
545
- """Fits the imputer on X and return the transformed X.
546
-
547
- Args:
548
- 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.
549
-
550
- valid_cols (numpy.ndarray, optional): Array with column indices to keep. Defaults to None.
551
-
552
- y (None): Ignored. Here for compatibility with other sklearn classes.
553
-
554
- Returns:
555
- Xt (array-like, shape (n_samples, n_features)): The imputed input data.
556
-
557
- Raises:
558
- ValueError: "max_iter" must be a positive integer.
559
- ValueError: "tol" should be non-negative float.
560
- ValueError: One or more features has min_value >= max_value.
561
- ConvergenceWarning: Early stopping criterion not reached.
562
- """
563
- self.random_state_ = getattr(
564
- self, "random_state_", check_random_state(self.random_state)
565
- )
566
-
567
- if self.max_iter < 0:
568
- raise ValueError(
569
- f"'max_iter' should be a positive integer. Got {self.max_iter} instead."
570
- )
571
-
572
- if self.tol < 0:
573
- raise ValueError(
574
- f"'tol' should be a non-negative float. Got {self.tol} instead"
575
- )
576
-
577
- self._estimator = clone(self.estimator)
578
-
579
- self.initial_imputer_ = None
580
-
581
- # X is the input data subset to only valid features (not nan)
582
- # Xt is the data imputed with SimpleImputer
583
- # mask_missing_values is the missing indicator matrix
584
- # complete_mask is the input data's mask matrix
585
- X, Xt, mask_missing_values, complete_mask = self._initial_imputation(
586
- X, valid_cols, in_fit=True
587
- )
588
-
589
- super(IterativeImputer, self)._fit_indicator(complete_mask)
590
- X_indicator = super(IterativeImputer, self)._transform_indicator(
591
- complete_mask
592
- )
593
-
594
- if self.max_iter == 0 or np.all(mask_missing_values):
595
- self.n_iter_ = 0
596
- return super(IterativeImputer, self)._concatenate_indicator(
597
- Xt, X_indicator
598
- )
599
-
600
- # Edge case: a single feature. We return the initial ...
601
- if Xt.shape[1] == 1:
602
- self.n_iter_ = 0
603
- return super(IterativeImputer, self)._concatenate_indicator(
604
- Xt, X_indicator
605
- )
606
-
607
- self._min_value = self._validate_limit(
608
- self.min_value, "min", X.shape[1]
609
- )
610
- self._max_value = self._validate_limit(
611
- self.max_value, "max", X.shape[1]
612
- )
613
-
614
- if not np.all(np.greater(self._max_value, self._min_value)):
615
- raise ValueError(
616
- "One (or more) features have min_value >= max_value."
617
- )
618
-
619
- # order in which to impute
620
- # note this is probably too slow for large feature data (d > 100000)
621
- # and a better way would be good.
622
- # see: https://goo.gl/KyCNwj and subsequent comments
623
- ordered_idx = self._get_ordered_idx(mask_missing_values)
624
- total_features = len(ordered_idx)
625
-
626
- self.n_features_with_missing_ = len(ordered_idx)
627
-
628
- abs_corr_mat = self._get_abs_corr_mat(Xt)
629
-
630
- n_samples, n_features = Xt.shape
631
-
632
- if self.verbose > 0:
633
- print(
634
- f"[IterativeImputer] Completing matrix with shape ({X.shape},)"
635
- )
636
- start_t = time()
637
-
638
- if not self.sample_posterior:
639
- Xt_previous = Xt.copy()
640
- normalized_tol = self.tol * np.max(np.abs(X[~mask_missing_values]))
641
-
642
- total_iter = self.max_iter
643
-
644
- ###########################################
645
- ### Iteration Start
646
- ###########################################
647
- for self.n_iter_ in progressbar(
648
- range(1, total_iter + 1),
649
- desc="Iteration: ",
650
- disable=self.disable_progressbar,
651
- ):
652
- if self.imputation_order == "random":
653
- ordered_idx = self._get_ordered_idx(mask_missing_values)
654
-
655
- if self.disable_progressbar:
656
- with open(self.logfilepath, "a") as fout:
657
- # Redirect to progress logfile
658
- with redirect_stdout(fout):
659
- print(
660
- f"Iteration Progress: "
661
- f"{self.n_iter_}/{self.max_iter} "
662
- f"({int((self.n_iter_ / total_iter) * 100)}%)"
663
- )
664
-
665
- if self.progress_update_percent is not None:
666
- print_perc_interval = self.progress_update_percent
667
-
668
- ##########################
669
- ### Feature Start
670
- ##########################
671
- for i, feat_idx in enumerate(
672
- progressbar(
673
- ordered_idx,
674
- desc="Feature: ",
675
- leave=False,
676
- position=1,
677
- disable=self.disable_progressbar,
678
- ),
679
- start=1,
680
- ):
681
- neighbor_feat_idx = self._get_neighbor_feat_idx(
682
- n_features, feat_idx, abs_corr_mat
683
- )
684
-
685
- Xt = self._impute_one_feature(
686
- Xt,
687
- mask_missing_values,
688
- feat_idx,
689
- neighbor_feat_idx,
690
- estimator=None,
691
- fit_mode=True,
692
- )
693
-
694
- # NOTE: The below source code has been commented out to save
695
- # RAM. estimator_triplet object contains numerous fit estimators
696
- # that demand a lot of resources. It is primarily used for the
697
- # transform function, which is not needed in this application.
698
-
699
- # estimator_triplet = _ImputerTripletAll(
700
- # feat_idx,
701
- # neighbor_feat_idx,
702
- # estimator)
703
-
704
- # self.imputation_sequence_.append(estimator_triplet)
705
-
706
- # Only print feature updates at each progress_update_percent
707
- # interval
708
- if (
709
- self.progress_update_percent is not None
710
- and self.disable_progressbar
711
- ):
712
- current_perc = math.ceil((i / total_features) * 100)
713
-
714
- if current_perc >= print_perc_interval:
715
- with open(self.logfilepath, "a") as fout:
716
- # Redirect progress to file
717
- with redirect_stdout(fout):
718
- print(
719
- f"Feature Progress (Iteration "
720
- f"{self.n_iter_}/{self.max_iter}): "
721
- f"{i}/{total_features} ({current_perc}"
722
- f"%)"
723
- )
724
-
725
- if i == len(ordered_idx):
726
- print("\n", end="")
727
-
728
- while print_perc_interval <= current_perc:
729
- print_perc_interval += self.progress_update_percent
730
-
731
- if self.verbose > 1:
732
- print(
733
- f"[IterativeImputer] Ending imputation round "
734
- f"{self.n_iter_}/{self.max_iter}, "
735
- f"elapsed time {(time() - start_t):0.2f}"
736
- )
737
-
738
- if not self.sample_posterior:
739
- inf_norm = np.linalg.norm(
740
- Xt - Xt_previous, ord=np.inf, axis=None
741
- )
742
-
743
- if self.verbose > 0:
744
- print(
745
- f"[IterativeImputer] Change: {inf_norm}, "
746
- f"scaled tolerance: {normalized_tol} "
747
- )
748
-
749
- if inf_norm < normalized_tol:
750
- if self.disable_progressbar:
751
- # Early stopping criteria has been reached
752
- with open(self.logfilepath, "a") as fout:
753
- # Redirect to progress logfile
754
- with redirect_stdout(fout):
755
- print(
756
- "[IterativeImputer] Early stopping "
757
- "criterion reached."
758
- )
759
- else:
760
- print(
761
- "[IterativeImputer] Early stopping criterion "
762
- "reached."
763
- )
764
-
765
- break
766
- Xt_previous = Xt.copy()
767
-
768
- else:
769
- if not self.sample_posterior:
770
- warnings.warn(
771
- "[IterativeImputer] Early stopping criterion not"
772
- " reached.",
773
- ConvergenceWarning,
774
- )
775
-
776
- Xt[~mask_missing_values] = X[~mask_missing_values]
777
- Xt = Xt.astype(int)
778
-
779
- return (
780
- super(IterativeImputer, self)._concatenate_indicator(
781
- Xt, X_indicator
782
- ),
783
- None,
784
- None,
785
- )