Repository navigation
Description
Describe the bug
When calling varProcess.simulate_var(num_time_steps), an error is thrown which essentially reads:
Traceback (most recent call last):
File "foo.py", line 191, in <module>
data1[0,:,:] = my_varProcess.simulate_var(num_time_steps)
File "/user1/.local/lib/python3.7/site-packages/statsmodels/tsa/vector_ar/var_model.py", line 959, in simulate_var
offset = self.endog_lagged[:, : self.k_exog].dot(
AttributeError: 'VARProcess' object has no attribute 'endog_lagged'
This error seems to suggest that VARProcess.simulate_var() is calling a function for which the VARProcess object has not been properly initialized. It appears that this error would need to be fixed before simulate_var could complete its functional objectives.
For reference, this issue seems loosely related to the following issue from 2018: <BUG/REF: fixing a few VAR problems #4538>
Code Sample, a copy-pastable example if possible
pip install statsmodels
pip install slycot
pip install control
pip install -U numpy
pip install scipy --upgradeimport pickle as pkl
import numpy as np
import copy
import control.matlab as ctrl
from statsmodels.tsa.vector_ar.var_model import VARProcess as varp
from scipy.signal import zpk2tf
from scipy.signal.filter_design import bilinear_zpk
data_save_path = "/folder/for/saving/sims"
logs_save_path = "/folder/for/saving/sims/logs"
num_data_samples = 21
sample_temp_window_size = 1000
max_num_samps_per_preprocessed_file = 5
num_channels = 5
decay1 = 0.98
mu1 = 5
decay2 = 0.9
mu2 = 30
seed = 1337
fs = 1000
LOOP1DELAY = 10
LOOP2DELAY = 3
LOOP1STR = 0.003
LOOP2STR = 0.02
NOISE_COV1 = 1
NOISE_COV2 = 1
NOISE_COV3 = 1
if __name__=="__main__":
# create VAR models to simulate data
# generate intra-region AR coefficient from desired poles
pole1a = decay1*np.exp(1j*mu1/fs*(2*np.pi))
pole1b = decay1*np.exp(-1j*mu1/fs*(2*np.pi))
pole2a = decay2*np.exp(1j*mu2/fs*(2*np.pi))
pole2b = decay2*np.exp(-1j*mu2/fs*(2*np.pi))
# For logic behind following code, see zpk2tf docs at https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.zpk2tf.html#scipy.signal.zpk2tf
# as well as _ at https://python.hotexamples.com/examples/scipy.signal/-/zpk2tf/python-zpk2tf-function-examples.html and https://www.mathworks.com/help/signal/ref/bilinear.html
sys1zz, sys1pz, sys1kz = bilinear_zpk([], [pole1a, pole1b], LOOP1STR, 1/fs) # create continuous analogue of discrete system
_, sys1Denom = zpk2tf(sys1zz, sys1pz, sys1kz)
nCoefs1 = np.prod(list(sys1Denom.shape))-1
nLags1 = max(LOOP1DELAY, nCoefs1)
coef1intra = np.zeros((nLags1,1))
coef1intra[:nCoefs1,0] = -sys1Denom[1:]
# make inter region AR coefficients simple impulse
coef1inter = np.zeros((nLags1,1))
coef1inter[LOOP1DELAY-1,0] = LOOP1STR
# populate VAR1 parameters
preCov = np.random.randn(num_channels)/num_channels
net1Covariance = NOISE_COV1*((preCov + preCov.conjugate())/2 + np.eye(num_channels))
net1Constant = np.zeros((num_channels,1))
net1AR = []
for k in range(nLags1):
thisLag = np.zeros((1,num_channels, num_channels))
# the network simulated by this var is 1>2>3>4 with recurrent connections within 1,2,3,&4
for r in range(4):
thisLag[0,r,r] = coef1intra[k]
thisLag[0,1,0] = coef1inter[k]
thisLag[0,2,1] = coef1inter[k]
thisLag[0,3,2] = coef1inter[k]
net1AR.append(thisLag)
net1AR = np.concatenate(net1AR, axis=0)
net1 = varp(net1AR, net1Constant, net1Covariance) # currently assumes exogenous variables () are zeros
print("__MAIN__: drawing and saving samples")
samples = []
subset_counter = 0
for i in range(num_data_samples):
print("__MAIN__: \t processing sample i==", i, " of n==", num_data_samples)
# Simulate data from VAR model
# initialize network data arrays
data1 = np.zeros((1, sample_temp_window_size, num_channels))
# generate scores for each network
scores = np.random.random(1)
# simulate each window w/ scaled innovation term
net1.Covariance = copy.deepcopy(net1Covariance) * scores[0]
data1[0,:,:] = net1.simulate_var(sample_temp_window_size) # NOTE: THIS IS WHERE THE ERROR GETS THROWN
# sum network contributions
curr_samp = data1
samples.append([curr_samp, scores])
# periodically save sample sets to external files so that full dataset need not be loaded all at once
if len(samples)+1 == max_num_samps_per_preprocessed_file:
print("__MAIN__: \t now saving subset_counter==", subset_counter)
curr_subset_name = "processed_data_subset_"+str(subset_counter)+".pkl"
with open(os.path.join(data_save_path, curr_subset_name), 'wb') as outfile:
pkl.dump(samples, outfile)
samples = []
subset_counter += 1
pass
print("__MAIN__: FINISHED !!!!!!")
passExpected Output
Rather than an error message being thrown, the above code should save five .pkl files to the given (pre-existing) data_save_path variable, each of which should contain a python list of 1-5 np.array objects with shape (1 x num_channels x sample_temp_window_size ). (Note: the true saved shape of the np.array objects may have axes 1 and 2 transposed, which would also be an acceptable output)
Output of import statsmodels.api as sm; sm.show_versions()
INSTALLED VERSIONS
Python: 3.7.6.final.0
OS: Linux 4.18.0-408.el8.x86_64 #1 SMP Mon Jul 18 17:42:52 UTC 2022 x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
statsmodels
Installed: 0.13.5 (/user1/.local/lib/python3.7/site-packages/statsmodels)
Required Dependencies
cython: 3.0a1 (/opt/apps/user2/python-3.7.6/lib/python3.7/site-packages/Cython)
numpy: 1.21.6 (/user1/.local/lib/python3.7/site-packages/numpy)
scipy: 1.7.3 (/user1/.local/lib/python3.7/site-packages/scipy)
pandas: 1.0.3 (/opt/apps/user2/python-3.7.6/lib/python3.7/site-packages/pandas)
dateutil: 2.8.1 (/opt/apps/user2/python-3.7.6/lib/python3.7/site-packages/dateutil)
patsy: 0.5.3 (/user1/.local/lib/python3.7/site-packages/patsy)
Optional Dependencies
matplotlib: 3.5.3 (/user1/.local/lib/python3.7/site-packages/matplotlib)
backend: agg
cvxopt: Not installed
joblib: 0.16.0 (/opt/apps/user2/python-3.7.6/lib/python3.7/site-packages/joblib)
Developer Tools
IPython: 7.18.1 (/opt/apps/user2/python-3.7.6/lib/python3.7/site-packages/IPython)
jinja2: 2.11.2 (/opt/apps/user2/python-3.7.6/lib/python3.7/site-packages/jinja2)
sphinx: Not installed
pygments: 2.7.1 (/opt/apps/user2/python-3.7.6/lib/python3.7/site-packages/pygments)
pytest: Not installed
virtualenv: Not installed
Activity
zacharycbrown commentedon Jun 22, 2023
Looking at the version of statsmodels in the main branch, it appears that the error reported above (based on statsmodels version 0.13.5) would be thrown by the code in the main branch on line 967 of statsmodels/statsmodels/tsa/vector_ar/var_model.py, where it reads
While I have not been able to test if the code provided above still throws the same error when run using the package contained in the main branch, it appears that - similarly to version 0.13.5, apparently - the main branch also contains a class definition of VARProcess which does not have an initialization of self.endog_lagged (however, there is an initialization statement for self.endog_lagged in the VARResults class, which inherets from VARProcess) ...
Fontanapink commentedon Jan 30, 2024
I have the same problem! I want to use VARProcess to simulate data but having the same error:
BUG: Count coefs_exog columns in VARProcess