File size: 26,791 Bytes
bd3c428
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ============================================
# CLASS 3: MISSING VALUE ANALYSER
# ============================================
from typing import Dict, Tuple
from venv import logger

from config.config import Config
from scipy.interpolate import interp1d
from statsmodels.tsa.seasonal import seasonal_decompose, STL
try:
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    print("✅ All imports working!")
except ImportError as e:
    print(f"❌ Import error: {e}")

class MissingValueAnalyser:
    """Class for analysing and handling missing values"""
    
    def __init__(self, config: Config):
        """
        Initialise missing value analyser
        
        Parameters:
        -----------
        config : Config
            Experiment configuration
        """
        self.config = config
        self.missing_info = {}
        self.handling_methods = {}
        self.imputers = {}
        self.missing_patterns = {}
    
    def analyse(
        self, 
        data: pd.DataFrame, 
        detailed: bool = True
    ) -> Dict:
        """
        Analyse missing values in data
        
        Parameters:
        -----------
        data : pd.DataFrame
            Input data
        detailed : bool
            Whether to perform detailed analysis
        
        Returns:
        --------
        Dict
            Information about missing values
        """
        logger.info("\n" + "="*80)
        logger.info("MISSING VALUE ANALYSIS")
        logger.info("="*80)
        
        # Calculate missing values
        missing_total = data.isnull().sum()
        missing_percent = (missing_total / len(data)) * 100
        
        missing_df = pd.DataFrame({
            'missing_count': missing_total,
            'missing_percent': missing_percent,
            'dtype': data.dtypes.astype(str)
        })
        
        # Detailed analysis
        if detailed:
            self._detailed_missing_analysis(data, missing_df)
        
        # Save information
        self.missing_info = {
            'summary': {
                col: {
                    'missing_count': int(missing_df.loc[col, 'missing_count']),
                    'missing_percent': float(missing_df.loc[col, 'missing_percent']),
                    'dtype': missing_df.loc[col, 'dtype']
                }
                for col in missing_df.index
            },
            'overall': {
                'total_missing': int(missing_total.sum()),
                'total_rows': int(len(data)),
                'total_cells': int(data.size),
                'overall_missing_percentage': float(missing_total.sum() / data.size * 100),
                'rows_with_any_missing': int(data.isnull().any(axis=1).sum()),
                'rows_all_missing': int(data.isnull().all(axis=1).sum()),
                'columns_with_missing': missing_df[missing_df['missing_count'] > 0].index.tolist(),
                'columns_all_missing': missing_df[missing_df['missing_count'] == len(data)].index.tolist()
            }
        }
        
        # Visualisation
        if self.config.save_plots:
            self._plot_missing_values(data, missing_df)
        
        # Output results
        self._log_missing_summary(missing_df)
        
        return self.missing_info
    
    def _detailed_missing_analysis(
        self, 
        data: pd.DataFrame, 
        missing_df: pd.DataFrame
    ) -> None:
        """Detailed missing value analysis"""
        # Analyse missing patterns
        missing_matrix = data.isnull()
        
        # Row missing patterns
        row_patterns = missing_matrix.apply(lambda x: ''.join(x.astype(int).astype(str)), axis=1)
        row_pattern_counts = row_patterns.value_counts().head(10)
        
        # Column missing patterns
        col_patterns = missing_matrix.apply(lambda x: ''.join(x.astype(int).astype(str)), axis=0)
        col_pattern_counts = col_patterns.value_counts().head(10)
        
        # Time-based missing patterns analysis
        time_patterns = {}
        if isinstance(data.index, pd.DatetimeIndex):
            # Missing values by time
            time_missing = data.isnull().resample('M').sum()
            time_patterns['monthly_missing'] = time_missing.sum(axis=1).to_dict()
            
            # Missing values by day of week
            data_with_dow = data.copy()
            data_with_dow['dayofweek'] = data.index.dayofweek
            dow_missing = data_with_dow.groupby('dayofweek').apply(lambda x: x.isnull().sum().sum())
            time_patterns['dayofweek_missing'] = dow_missing.to_dict()
        
        self.missing_patterns = {
            'row_patterns': row_pattern_counts.to_dict(),
            'col_patterns': col_pattern_counts.to_dict(),
            'time_patterns': time_patterns,
            'missing_correlation': missing_matrix.corr().to_dict()  # Missing value correlation
        }
        
        logger.debug(f"Found {len(row_pattern_counts)} unique row missing patterns")
        logger.debug(f"Found {len(col_pattern_counts)} unique column missing patterns")
    
    def _plot_missing_values(
        self, 
        data: pd.DataFrame, 
        missing_df: pd.DataFrame
    ) -> None:
        """Visualise missing values"""
        fig, axes = plt.subplots(3, 2, figsize=(16, 12))
        
        # 1. Missing percentage histogram
        axes[0, 0].barh(
            missing_df.index, 
            missing_df['missing_percent']
        )
        axes[0, 0].axvline(self.config.missing_threshold, color='red', linestyle='--')
        axes[0, 0].set_title('Missing Percentage by Column')
        axes[0, 0].set_xlabel('Missing Percentage (%)')
        axes[0, 0].set_ylabel('Columns')
        axes[0, 0].grid(True, alpha=0.3)
        
        # 2. Missing values heatmap
        missing_matrix = data.isnull()
        axes[0, 1].imshow(
            missing_matrix.T if len(data) > 1000 else missing_matrix.T[:1000],
            aspect='auto', 
            cmap='binary', 
            interpolation='none'
        )
        axes[0, 1].set_title('Missing Values Matrix')
        axes[0, 1].set_xlabel('Observation Index')
        axes[0, 1].set_ylabel('Variables')
        axes[0, 1].set_yticks(range(len(data.columns)))
        axes[0, 1].set_yticklabels(data.columns, fontsize=8)
        
        # 3. Missing values over time (if time series)
        if isinstance(data.index, pd.DatetimeIndex):
            time_missing = data.isnull().resample('M').sum()
            
            axes[1, 0].plot(time_missing.sum(axis=1))
            axes[1, 0].set_title('Missing Values by Month')
            axes[1, 0].set_xlabel('Date')
            axes[1, 0].set_ylabel('Number of Missing Values')
            axes[1, 0].grid(True, alpha=0.3)
            
            # 4. Missing values by day of week
            data_with_dow = data.copy()
            data_with_dow['dayofweek'] = data.index.dayofweek
            dow_missing = data_with_dow.groupby('dayofweek').apply(lambda x: x.isnull().sum().sum())
            dow_names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            
            axes[1, 1].bar(range(7), dow_missing)
            axes[1, 1].set_title('Missing Values by Day of Week')
            axes[1, 1].set_xlabel('Day of Week')
            axes[1, 1].set_ylabel('Number of Missing Values')
            axes[1, 1].set_xticks(range(7))
            axes[1, 1].set_xticklabels(dow_names)
            axes[1, 1].grid(True, alpha=0.3)
        
        # 5. Missing value correlation
        missing_corr = data.isnull().corr()
        im = axes[2, 0].imshow(
            missing_corr, 
            cmap='coolwarm', 
            vmin=-1, 
            vmax=1,
            aspect='auto'
        )
        axes[2, 0].set_title('Missing Value Correlation Between Variables')
        axes[2, 0].set_xlabel('Variables')
        axes[2, 0].set_ylabel('Variables')
        plt.colorbar(im, ax=axes[2, 0])
        
        # 6. Cumulative missing sum
        cumulative_missing = data.isnull().cumsum()
        for col in data.columns[:5]:  # First 5 columns
            if data[col].isnull().any():
                axes[2, 1].plot(
                    cumulative_missing.index, 
                    cumulative_missing[col],
                    label=col[:20]
                )
        axes[2, 1].set_title('Cumulative Missing Values')
        axes[2, 1].set_xlabel('Time/Index')
        axes[2, 1].set_ylabel('Cumulative Missing')
        axes[2, 1].legend(fontsize=8)
        axes[2, 1].grid(True, alpha=0.3)
        
        plt.tight_layout()
        plt.savefig(
            f'{self.config.results_dir}/plots/missing_values_analysis.png',
            dpi=300, 
            bbox_inches='tight'
        )
        plt.show()
    
    def _log_missing_summary(self, missing_df: pd.DataFrame) -> None:
        """Log missing value summary"""
        missing_columns = missing_df[missing_df['missing_count'] > 0]
        
        if len(missing_columns) > 0:
            logger.info("MISSING VALUES FOUND:")
            logger.info("-" * 50)
            logger.info(f"Total missing values: {self.missing_info['overall']['total_missing']}")
            logger.info(f"Overall missing percentage: {self.missing_info['overall']['overall_missing_percentage']:.2f}%")
            logger.info(f"Rows with missing values: {self.missing_info['overall']['rows_with_any_missing']}")
            logger.info(f"Columns with missing values: {len(self.missing_info['overall']['columns_with_missing'])}")
            
            logger.info("\nTop-10 columns by missing values:")
            top_missing = missing_df.nlargest(10, 'missing_percent')
            for idx, (col, row) in enumerate(top_missing.iterrows(), 1):
                logger.info(f"  {idx:2d}. {col}: {int(row['missing_count'])} missing ({row['missing_percent']:.2f}%)")
        else:
            logger.info("✓ No missing values found")
    
    def handle(
        self, 
        data: pd.DataFrame, 
        method: str = 'interpolate',
        strategy: str = 'columnwise',
        **kwargs
    ) -> pd.DataFrame:
        """
        Handle missing values
        
        Parameters:
        -----------
        data : pd.DataFrame
            Input data
        method : str
            Handling method: 'interpolate', 'ffill', 'bfill', 'mean', 'median', 'mode', 'knn', 'regression'
        strategy : str
            Strategy: 'columnwise', 'rowwise', 'global'
        **kwargs : dict
            Additional parameters for method
        
        Returns:
        --------
        pd.DataFrame
            Data with handled missing values
        """
        logger.info("\n" + "="*80)
        logger.info("HANDLING MISSING VALUES")
        logger.info("="*80)
        
        data_processed = data.copy()
        methods_applied = {}
        
        # Determine columns to process
        if strategy == 'columnwise':
            columns_to_process = data_processed.columns
        elif strategy == 'rowwise':
            # Row-wise handling (for time series)
            data_processed = self._handle_rowwise(data_processed, method, **kwargs)
            return data_processed
        else:
            columns_to_process = data_processed.select_dtypes(include=[np.number]).columns
        
        # Process each column
        for col in columns_to_process:
            missing_before = data_processed[col].isnull().sum()
            
            if missing_before > 0:
                # Check if missing percentage exceeds threshold
                missing_percent = (missing_before / len(data_processed)) * 100
                
                if missing_percent > self.config.missing_threshold:
                    logger.warning(f"  {col}: {missing_before} missing ({missing_percent:.1f}%) > threshold {self.config.missing_threshold}%")
                    
                    if kwargs.get('drop_high_missing', False):
                        data_processed = data_processed.drop(columns=[col])
                        method_used = f"dropped (>{self.config.missing_threshold}% missing)"
                        missing_after = 0
                    else:
                        # Use selected method
                        data_processed[col], method_used = self._apply_imputation_method(
                            data_processed[col], method, **kwargs
                        )
                        missing_after = data_processed[col].isnull().sum()
                else:
                    # Use selected method
                    data_processed[col], method_used = self._apply_imputation_method(
                        data_processed[col], method, **kwargs
                    )
                    missing_after = data_processed[col].isnull().sum()
                
                methods_applied[col] = {
                    'method': method_used,
                    'missing_before': int(missing_before),
                    'missing_after': int(missing_after),
                    'missing_percent_before': float(missing_percent)
                }
                
                if missing_before > 0:
                    logger.info(f"  {col}: {missing_before}{missing_after} missing ({method_used})")
        
        self.handling_methods = methods_applied
        
        # Check that all missing values are handled
        remaining_missing = data_processed.isnull().sum().sum()
        if remaining_missing == 0:
            logger.info("✓ All missing values successfully handled")
        else:
            logger.warning(f"⚠ {remaining_missing} missing values remain")
            # Additional handling of remaining missing values
            data_processed = data_processed.fillna(method='ffill').fillna(method='bfill')
            remaining_after = data_processed.isnull().sum().sum()
            if remaining_after == 0:
                logger.info("✓ Remaining missing values handled with ffill/bfill combination")
        
        return data_processed
    
    def _apply_imputation_method(
        self, 
        series: pd.Series, 
        method: str,
        **kwargs
    ) -> Tuple[pd.Series, str]:
        """
        Apply imputation method to individual series
        
        Parameters:
        -----------
        series : pd.Series
            Input series
        method : str
            Imputation method
        **kwargs : dict
            Additional parameters
        
        Returns:
        --------
        Tuple[pd.Series, str]
            Processed series and method description
        """
        if method == 'interpolate':
            # Interpolation for time series
            if isinstance(series.index, pd.DatetimeIndex):
                method_name = f"{kwargs.get('interpolation_method', 'linear')} interpolation"
                series_filled = series.interpolate(
                    method=kwargs.get('interpolation_method', 'linear'),
                    limit_direction=kwargs.get('limit_direction', 'both'),
                    limit=kwargs.get('limit', None)
                )
            else:
                method_name = 'linear interpolation'
                series_filled = series.interpolate(method='linear')
        
        elif method == 'time_weighted':
            # Time-weighted interpolation
            method_name = 'time-weighted interpolation'
            series_filled = self._time_weighted_interpolation(series)
        
        elif method == 'seasonal':
            # Seasonal interpolation
            method_name = 'seasonal interpolation'
            series_filled = self._seasonal_interpolation(series, **kwargs)
        
        elif method == 'ffill':
            # Forward fill
            method_name = 'forward fill'
            series_filled = series.ffill(limit=kwargs.get('limit', None))
        
        elif method == 'bfill':
            # Backward fill
            method_name = 'backward fill'
            series_filled = series.bfill(limit=kwargs.get('limit', None))
        
        elif method == 'mean':
            # Mean imputation
            method_name = 'mean imputation'
            series_filled = series.fillna(series.mean())
        
        elif method == 'median':
            # Median imputation
            method_name = 'median imputation'
            series_filled = series.fillna(series.median())
        
        elif method == 'mode':
            # Mode imputation
            method_name = 'mode imputation'
            mode_value = series.mode()
            if not mode_value.empty:
                series_filled = series.fillna(mode_value.iloc[0])
            else:
                series_filled = series.fillna(series.median())
        
        elif method == 'knn':
            # KNN imputation
            method_name = f"KNN imputation (k={kwargs.get('k', 5)})"
            # Simplified version using nearest neighbour mean
            series_filled = self._knn_imputation(series, k=kwargs.get('k', 5))
        
        elif method == 'regression':
            # Regression imputation
            method_name = 'regression imputation'
            series_filled = self._regression_imputation(series, **kwargs)
        
        elif method == 'spline':
            # Spline interpolation
            method_name = 'spline interpolation'
            series_filled = series.interpolate(method='spline', order=kwargs.get('order', 3))
        
        elif method == 'stl':
            # STL decomposition + interpolation
            method_name = 'STL-based imputation'
            series_filled = self._stl_imputation(series, **kwargs)
        
        else:
            raise ValueError(f"Unknown method: {method}")
        
        # If missing values remain, fill with ffill/bfill
        if series_filled.isnull().any():
            series_filled = series_filled.ffill().bfill()
            method_name += " + ffill/bfill"
        
        return series_filled, method_name
    
    def _time_weighted_interpolation(self, series: pd.Series) -> pd.Series:
        """Time-weighted interpolation"""
        if not isinstance(series.index, pd.DatetimeIndex):
            return series.interpolate()
        
        # Create timestamps
        time_numeric = pd.Series(range(len(series)), index=series.index)
        
        # Interpolate timestamps for missing values
        time_interpolated = time_numeric.interpolate()
        
        # Interpolate values based on timestamps
        valid_mask = series.notna()
        if valid_mask.sum() < 2:
            return series.ffill().bfill()
        
        # Use linear interpolation
        valid_times = time_numeric[valid_mask]
        valid_values = series[valid_mask]
        
        # Interpolation
        interp_func = interp1d(
            valid_times, 
            valid_values, 
            kind='linear',
            bounds_error=False,
            fill_value='extrapolate'
        )
        
        series_filled = series.copy()
        missing_mask = series.isna()
        series_filled[missing_mask] = interp_func(time_interpolated[missing_mask])
        
        return series_filled
    
    def _seasonal_interpolation(
        self, 
        series: pd.Series, 
        **kwargs
    ) -> pd.Series:
        """Seasonal interpolation"""
        if not isinstance(series.index, pd.DatetimeIndex):
            return series.interpolate()
        
        period = kwargs.get('period', self.config.seasonal_period)
        
        # Create series copy
        series_filled = series.copy()
        
        # Interpolation considering seasonality
        for i in range(len(series)):
            if pd.isna(series.iloc[i]):
                # Find values at same seasonal position
                seasonal_indices = []
                for offset in range(1, 10):  # Look in previous/next cycles
                    idx_back = i - offset * period
                    idx_forward = i + offset * period
                    
                    if idx_back >= 0 and not pd.isna(series.iloc[idx_back]):
                        seasonal_indices.append(idx_back)
                    
                    if idx_forward < len(series) and not pd.isna(series.iloc[idx_forward]):
                        seasonal_indices.append(idx_forward)
                
                if seasonal_indices:
                    # Take mean value from seasonal positions
                    seasonal_values = series.iloc[seasonal_indices]
                    series_filled.iloc[i] = seasonal_values.mean()
        
        # Fill remaining missing values with regular interpolation
        series_filled = series_filled.interpolate()
        
        return series_filled
    
    def _knn_imputation(
        self, 
        series: pd.Series, 
        k: int = 5
    ) -> pd.Series:
        """KNN imputation for time series"""
        # Simplified KNN for time series
        series_filled = series.copy()
        
        for i in range(len(series)):
            if pd.isna(series.iloc[i]):
                # Find nearest k non-missing values
                distances = []
                values = []
                
                for j in range(max(0, i - k * 10), min(len(series), i + k * 10)):
                    if j != i and not pd.isna(series.iloc[j]):
                        distance = abs(i - j)
                        distances.append(distance)
                        values.append(series.iloc[j])
                        
                        if len(values) >= k:
                            break
                
                if values:
                    # Distance-weighted average
                    weights = [1 / (d + 1) for d in distances]
                    weighted_avg = np.average(values, weights=weights)
                    series_filled.iloc[i] = weighted_avg
        
        return series_filled
    
    def _regression_imputation(
        self, 
        series: pd.Series, 
        **kwargs
    ) -> pd.Series:
        """Regression imputation based on neighbouring values"""
        # Simplified regression for time series
        series_filled = series.copy()
        
        if series.notna().sum() < 3:
            return series.ffill().bfill()
        
        # Use polynomial regression
        x = np.arange(len(series))
        y = series.values
        
        # Valid values mask
        valid_mask = ~np.isnan(y)
        
        if valid_mask.sum() < 2:
            return series.ffill().bfill()
        
        # Polynomial regression degree 2
        coeffs = np.polyfit(x[valid_mask], y[valid_mask], 2)
        poly_func = np.poly1d(coeffs)
        
        # Fill missing values
        missing_mask = np.isnan(y)
        series_filled.iloc[missing_mask] = poly_func(x[missing_mask])
        
        return series_filled
    
    def _stl_imputation(
        self, 
        series: pd.Series, 
        **kwargs
    ) -> pd.Series:
        """STL decomposition-based imputation"""
        try:
            if not isinstance(series.index, pd.DatetimeIndex):
                return series.interpolate()
            
            # STL decomposition
            stl = STL(
                series.ffill().bfill(),  # Fill missing for STL
                period=kwargs.get('period', self.config.seasonal_period),
                robust=True
            )
            result = stl.fit()
            
            # Reconstruct series without noise
            reconstructed = result.trend + result.seasonal
            
            # Replace missing values with reconstructed values
            series_filled = series.copy()
            missing_mask = series.isna()
            series_filled[missing_mask] = reconstructed[missing_mask]
            
            return series_filled
            
        except Exception as e:
            logger.warning(f"STL imputation failed: {e}, using interpolation")
            return series.interpolate()
    
    def _handle_rowwise(
        self, 
        data: pd.DataFrame, 
        method: str,
        **kwargs
    ) -> pd.DataFrame:
        """Row-wise missing value handling"""
        data_processed = data.copy()
        
        # Remove rows with high missing counts
        if kwargs.get('drop_rows_threshold', 0) > 0:
            threshold = kwargs['drop_rows_threshold']
            rows_before = len(data_processed)
            missing_per_row = data_processed.isnull().sum(axis=1) / data_processed.shape[1] * 100
            rows_to_drop = missing_per_row[missing_per_row > threshold].index
            data_processed = data_processed.drop(rows_to_drop)
            rows_after = len(data_processed)
            logger.info(f"Rows removed: {rows_before - rows_after} (missing > {threshold}%)")
        
        # Row-wise imputation
        if method == 'row_mean':
            data_processed = data_processed.T.fillna(data_processed.mean(axis=1)).T
        elif method == 'row_median':
            data_processed = data_processed.T.fillna(data_processed.median(axis=1)).T
        elif method == 'row_ffill':
            data_processed = data_processed.ffill(axis=1).bfill(axis=1)
        
        return data_processed
    
    def create_validation_rules(self) -> Dict:
        """Create validation rules based on missing value analysis"""
        rules = {}
        
        for col, info in self.missing_info['summary'].items():
            missing_percent = info['missing_percent']
            
            if missing_percent > 50:
                rules[col] = {
                    'action': 'drop_column',
                    'reason': f'Missing > 50%: {missing_percent:.1f}%'
                }
            elif missing_percent > 20:
                rules[col] = {
                    'action': 'advanced_imputation',
                    'reason': f'High missing: {missing_percent:.1f}%',
                    'recommended_method': 'knn'
                }
            elif missing_percent > 5:
                rules[col] = {
                    'action': 'standard_imputation',
                    'reason': f'Moderate missing: {missing_percent:.1f}%',
                    'recommended_method': 'interpolate'
                }
            elif missing_percent > 0:
                rules[col] = {
                    'action': 'simple_imputation',
                    'reason': f'Low missing: {missing_percent:.1f}%',
                    'recommended_method': 'ffill'
                }
        
        return rules
    
    def get_report(self) -> Dict:
        """Get missing values report"""
        return {
            'missing_info': self.missing_info,
            'handling_methods': self.handling_methods,
            'missing_patterns': self.missing_patterns,
            'validation_rules': self.create_validation_rules()
        }