/ concept-collection / benchcompress
Sign in
concept-collection / benchcompress
64 lines · 2.1 KBBlameHistoryRaw
1import numpy as np
2from zia_benchmark._analysis import linear_fit
5def markov_predict(x: np.ndarray, M: int) -> tuple:
6 """Predict signal using Markov model and return coefficients, initial values and residuals.
8 Args:
9 x: Input signal
10 M: Number of previous samples to use for prediction (default: 20)
12 Returns:
13 tuple: (coefficients, initial_values, residuals)
14 """
15 # Keep initial values for reconstruction
16 initial = x[: M - 1]
18 # Create sequences of M consecutive samples
19 sequences = np.array([x[i : i + M] for i in range(len(x) - M + 1)])
20 predictors = sequences[:, : M - 1] # Use M-1 previous samples to predict
21 target = sequences[:, M - 1] # The value to predict
23 # Get coefficients and prediction function using linear regression
24 coeffs, predict = linear_fit(predictors, target)
26 # Make predictions using the linear model
27 predictions = predict(predictors)
28 predictions = np.round(predictions)
30 # Calculate residuals (difference between actual and predicted values)
31 residuals = target - predictions
32 residuals = residuals.astype(x.dtype)
34 return coeffs, initial, residuals
37def markov_reconstruct(
38 coeffs: np.ndarray, initial: np.ndarray, resid: np.ndarray
39) -> np.ndarray:
40 """Reconstruct signal from Markov model parameters and residuals.
42 Args:
43 coeffs: Model coefficients from linear regression
44 initial: Initial values needed for prediction
45 resid: Prediction residuals
47 Returns:
48 np.ndarray: Reconstructed signal
49 """
50 M = len(initial) + 1 # Number of samples used in prediction
51 output = np.zeros(len(resid) + len(initial), dtype=resid.dtype)
52 output[: len(initial)] = initial # Set initial values
54 # Reconstruct signal iteratively
55 for i in range(len(resid)):
56 # Get previous M-1 values to make prediction
57 prev_values = output[i : i + M - 1]
58 # Make prediction using coefficients
59 prediction = np.sum(coeffs[:-1] * prev_values) + coeffs[-1]
60 prediction = np.round(prediction)
61 # Add residual to get actual value
62 output[i + M - 1] = prediction + resid[i]
64 return output
moveopenescclose