In [216]:
from IPython import parallel
clients = parallel.Client(profile='parallel')

In [222]:
print clients.ids
print "Total %i cores"%(len(clients.ids))


[0, 1, 2, 3, 4, 5, 6, 15, 16, 17, 18, 19, 20]
Total 13 cores

In [223]:
%%px --local

import sys
sys.path.append("\\\\DAP-NAS\\work\\CNOP")
import cPickle as pickle
import numpy as np
import pandas as pd
from statsmodels.tsa.arima_process import arma_generate_sample
import matplotlib.pyplot as plt
import numpy as np
import CNOP
CNOP = reload(CNOP)
CNOP = CNOP.CNOP
import winsound
def threshold(x,thresholds=[],values=[-1,0,1]):
    for threshold,val in zip(thresholds,values):
        if x < threshold: 
            return val
    return values[-1]
import time
from itertools import repeat
import os
from datetime import datetime
import numpy as np
import numpy.linalg as linalg
from statsmodels.tsa.arima_process import arma_generate_sample
import warnings

In [224]:
%%px --local
x2000 = pd.read_csv("\\\\DAP-NAS\\work\\CNOP\\x2000.csv", delimiter=";")

In [225]:
%%px --local

N=100

def autocorrelated_errors(rho, df, give_distortion=True):
    ###########################################################
    ##### This code is for partial-overlap case of CNOP########
    ###########################################################
    N=500

    #PreSampling:
    df = df[:N]
    #df = x2000[:N]
    
    ### DGP generation
    regime = pd.DataFrame() 
    beta,   alpha   = [0.6, 0.4], [0.9, 1.5]
    gammam, mum =     [0.3, 0.9], [-0.67, 0.36]
    gammap, mup =     [0.2, 0.3], [0.02, 1.28]
    distortion = np.array([arma_generate_sample(ar = [1, -rho], ma=[1], nsample = N) for i in range(3)])
    regime["xbeta"]    = df[["X1", "X2"]].dot(beta)    + distortion[0]
    regime['z-gammam'] = df[["X1", "X3"]].dot(gammam)  + distortion[1]
    regime['z+gammap'] = df[["X2", "X3"]].dot(gammap)  + distortion[2]
    regime['regime'] = regime['xbeta'].apply(lambda x: threshold(x,thresholds=alpha))
    regime['Y-']=regime['z-gammam'].apply(lambda x: threshold(x, thresholds=mum,values=[-2,-1,0]))
    regime['Y+']=regime['z+gammap'].apply(lambda x: threshold(x, thresholds=mup,values=[0,1,2]))
    df['Y'] = 0
    df['Y'] += np.where(regime['regime']==-1,regime['Y-'],0)
    df['Y'] += np.where(regime['regime']==1,regime['Y+'],0)
    ###df is full data matrix

    #Model starts here:
    exog = df[["X1", "X2", "X3"]]
    endog = df[["Y"]]
    l = {0:df}
    pan = pd.Panel(l)
    y      = pan.ix[:,:,['Y']]
    x      = pan.ix[:,:,["X1", "X2"]]
    zminus = pan.ix[:,:,["X1", "X3"]]
    zplus  = pan.ix[:,:,["X2", "X3"]]
    exog = {'x':x,'zplus':zplus,'zminus':zminus}
    CNOP4 = CNOP(y,exog, model='CNOP',interest_step=1)

    #Counting execution time for fit ...
    exec_time = {"fit":0,"se":0}
    start_time = time.time()
    res = CNOP4.fit( maxiter=250, disp=0)
    exec_time["fit"] = time.time() - start_time

    # And for Standard Errors as well
    try:
        start_time = time.time()
        res["se"] = CNOP4.se(res.x)
        exec_time["se"] = time.time() - start_time
        res['status'] = "OK"
    except Exception, e:
        print e
        res['status'] = e

    res["exec_time"]=exec_time

    if give_distortion:
        return res, distortion
    else:
        return res

In [123]:
%matplotlib inline

In [146]:
rho=0.5
res, distortion = autocorrelated_errors(rho=rho, df=x2000)
print "Done for rho=%.3f" % (rho)
print "Res.status:", res.success

beta,   alpha   = [0.6, 0.4], [0.9, 1.5]
gammam, mum =     [0.3, 0.9], [-0.67, 0.36]
gammap, mup =     [0.2, 0.3], [0.02, 1.28]
res_real = beta+alpha+gammam+mum+gammap+mup
plt.bar(np.arange(len(res.x-res_real)),
                  list(res.x-res_real));

winsound.PlaySound(u'C:\Windows\Media\Windows Print complete.wav', winsound.SND_FILENAME)
print "X & SE:"
print np.dstack((res.x,res.se))


Done for rho=0.500
Res.status: True
X & SE:
[[[ 0.58350771  0.15309693]
  [ 0.42537941  0.13749798]
  [ 0.71124071  0.36492697]
  [ 1.15961992  0.27646956]
  [ 0.20410731  0.15151155]
  [ 0.81316952  0.18405241]
  [-0.62803371  0.23619058]
  [ 0.39509324  0.32064347]
  [ 0.18841107  0.12312013]
  [ 0.21638108  0.11003245]
  [ 0.2773254   0.26679995]
  [ 1.25871904  0.190743  ]]]

In [226]:
%%px --local

def runMC(rho, n_repl, fun, append_folder=None, path="\\\\DAP-NAS\\work\\CNOP\\dumps\\", prefix = "CNOPres", ext = ".p", **kwargs):
    print "Starting MC on %i cores, %i replications of \"%s\" with rho = %.2f observations"\
               %(len(clients.ids), n_repl, fun.__name__, rho)
    print "If you again run next(), you will get wait_interactive() form and results would be backed up"
    print "Untill then you are free to use AsyncResult object that was apready yielded, but data will not be backed up!"
    view = clients.load_balanced_view()

    def doJob(i):
        rho,path,fun, kwargs=i
        dumb_str=time.strftime("%Y%m%d%H%M%S")+str(np.random.rand())

        filename = path + dumb_str

        try:
            local_res = fun(rho, **kwargs)
            pickle.dump(local_res, open( filename, "wb" ) )
            return local_res, filename
        except Exception, e:
            pickle.dump(e, open( filename, "wb" ) )
            return Exception, e, filename
    
    if append_folder is None:
        cur_time_str=time.strftime('%Y%m%d_%H%M%S')
        temp_folder_str = path+'temp/'+cur_time_str+"/"
        if not os.path.exists(temp_folder_str):
            os.makedirs(temp_folder_str)
    else:
        temp_folder_str = path+'temp/'+append_folder+"/"

    print temp_folder_str
    if append_folder is not None:
        readme_f = file(temp_folder_str+"!README.txt", "w")
        readme_f.write("Doing MC on %i cores, %i replications of \"%s\" with rho = %.2f observations"\
                       %(len(clients.ids), n_repl, fun.__name__, rho))
        readme_f.close()

    ar = view.map_async(doJob, [[rho, temp_folder_str, fun, kwargs]]*n_repl)
    yield ar

    ar.wait_interactive()
    results = ar.get()
    cur_time_str=time.strftime('%Y%m%d_%H%M%S')
    filename = path + prefix + cur_time_str + ext
    print "DONE! DB in %s"%(temp_folder_str)
    yield results

In [66]:
MCgenr03 = runMC(.3, 10000, autocorrelated_errors, df=x2000)
MCAsyncMapResult03 = next(MCgenr03)


Starting MC on 17 cores, 10000 replications of "autocorrelated_errors" with rho = 0.30 observations
If you again run next(), you will get wait_interactive() form and results would be backed up
Untill then you are free to use AsyncResult object that was apready yielded, but data will not be backed up!
\\DAP-NAS\work\CNOP\dumps\temp/20150412_132614/

In [67]:
results03=next(MCgenr03)


 731/10000 tasks finished after 2416 s
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-67-bb4a0d833a75> in <module>()
----> 1 results03=next(MCgenr03)

<ipython-input-38-792c319cc8cd> in runMC(rho, n_repl, fun, path, prefix, ext, **kwargs)
     33     yield ar
     34 
---> 35     ar.wait_interactive()
     36     results = ar.get()
     37     cur_time_str=time.strftime('%Y%m%d_%H%M%S')

C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\client\asyncresult.pyc in wait_interactive(self, interval, timeout)
    392         tic = time.time()
    393         while not self.ready() and (timeout < 0 or time.time() - tic <= timeout):
--> 394             self.wait(interval)
    395             clear_output(wait=True)
    396             print("%4i/%i tasks finished after %4i s" % (self.progress, N, self.elapsed), end="")

C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\client\asyncresult.pyc in wait(self, timeout)
    141             self._wait_for_outputs(timeout)
    142             return
--> 143         self._ready = self._client.wait(self.msg_ids, timeout)
    144         if self._ready:
    145             try:

C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\client\client.pyc in wait(self, jobs, timeout)
   1089             if timeout >= 0 and ( time.time()-tic ) > timeout:
   1090                 break
-> 1091             time.sleep(1e-3)
   1092             self.spin()
   1093         return len(theids.intersection(self.outstanding)) == 0

KeyboardInterrupt: 

In [68]:
MCAsyncMapResult03.abort()

In [74]:
i=MCAsyncMapResult03.get()


[Engine Exception]
Traceback (most recent call last):
  File "C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\controller\scheduler.py", line 357, in handle_stranded_tasks
    raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
EngineError: Engine 'af443219-7e22-43e9-a91b-660407e04051' died while running task u'a79dd743-dce0-46f9-85c8-3f87bd8b7f92'

[Engine Exception]
Traceback (most recent call last):
  File "C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\controller\scheduler.py", line 357, in handle_stranded_tasks
    raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
EngineError: Engine '1d7f788d-5e4b-4ced-966f-fbf60b59a180' died while running task u'5f97f761-2e0a-45a6-8de7-da3f95cf1771'

[Engine Exception]
Traceback (most recent call last):
  File "C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\controller\scheduler.py", line 357, in handle_stranded_tasks
    raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
EngineError: Engine '6cb9fc44-c91a-4511-99b1-6f3ba7e3d610' died while running task u'2169de1d-369f-4215-996f-46525b595b62'

[Engine Exception]
Traceback (most recent call last):
  File "C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\controller\scheduler.py", line 357, in handle_stranded_tasks
    raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
EngineError: Engine 'ad96f5df-501e-4c24-bf46-270427eb07fc' died while running task u'8adc86e1-e200-4767-871e-4102a3f34c37'

In [80]:
someresults = MCAsyncMapResult03

In [ ]:


In [86]:
MCgenr03 = runMC(.3, 9300, autocorrelated_errors, df=x2000)
MCAsyncMapResult03 = next(MCgenr03)


Starting MC on 17 cores, 9300 replications of "autocorrelated_errors" with rho = 0.30 observations
If you again run next(), you will get wait_interactive() form and results would be backed up
Untill then you are free to use AsyncResult object that was apready yielded, but data will not be backed up!
\\DAP-NAS\work\CNOP\dumps\temp/20150412_141301/

In [87]:
results03=next(MCgenr03)


 283/9300 tasks finished after  954 s
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-87-bb4a0d833a75> in <module>()
----> 1 results03=next(MCgenr03)

<ipython-input-85-792c319cc8cd> in runMC(rho, n_repl, fun, path, prefix, ext, **kwargs)
     33     yield ar
     34 
---> 35     ar.wait_interactive()
     36     results = ar.get()
     37     cur_time_str=time.strftime('%Y%m%d_%H%M%S')

C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\client\asyncresult.pyc in wait_interactive(self, interval, timeout)
    392         tic = time.time()
    393         while not self.ready() and (timeout < 0 or time.time() - tic <= timeout):
--> 394             self.wait(interval)
    395             clear_output(wait=True)
    396             print("%4i/%i tasks finished after %4i s" % (self.progress, N, self.elapsed), end="")

C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\client\asyncresult.pyc in wait(self, timeout)
    141             self._wait_for_outputs(timeout)
    142             return
--> 143         self._ready = self._client.wait(self.msg_ids, timeout)
    144         if self._ready:
    145             try:

C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\client\client.pyc in wait(self, jobs, timeout)
   1076             theids = set()
   1077             for job in jobs:
-> 1078                 if isinstance(job, int):
   1079                     # index access
   1080                     job = self.history[job]

KeyboardInterrupt: 

In [89]:
MCAsyncMapResult03.abort()

In [90]:
i=MCAsyncMapResult03.get()


[Engine Exception]
Traceback (most recent call last):
  File "C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\controller\scheduler.py", line 357, in handle_stranded_tasks
    raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
EngineError: Engine '9938e28b-2a8b-4bcd-adbe-5b12f00d7772' died while running task u'4b5c97f1-d9c3-4add-b09e-0abed9eb926f'

[Engine Exception]
Traceback (most recent call last):
  File "C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\controller\scheduler.py", line 357, in handle_stranded_tasks
    raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
EngineError: Engine '6508f065-9fc5-4cbc-935e-4f9a0681cbf9' died while running task u'5332552d-6f5e-4f41-953b-1e92be501619'

[Engine Exception]
Traceback (most recent call last):
  File "C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\controller\scheduler.py", line 357, in handle_stranded_tasks
    raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
EngineError: Engine '72b31e02-eb76-4103-a7ce-82ded2a0b003' died while running task u'f302d169-11ad-4eb1-bce5-7fe36e2523c5'

[Engine Exception]
Traceback (most recent call last):
  File "C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\controller\scheduler.py", line 357, in handle_stranded_tasks
    raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
EngineError: Engine '9ddcf274-0d98-416d-9f4a-5e23c2d9d7aa' died while running task u'74164121-09f4-415f-bdbf-5cb93885d288'

In [92]:
someresults = MCAsyncMapResult03

In [ ]:


In [100]:
MCgenr03 = runMC(.3, 9000, autocorrelated_errors, df=x2000)
MCAsyncMapResult03 = next(MCgenr03)


Starting MC on 17 cores, 9000 replications of "autocorrelated_errors" with rho = 0.30 observations
If you again run next(), you will get wait_interactive() form and results would be backed up
Untill then you are free to use AsyncResult object that was apready yielded, but data will not be backed up!
\\DAP-NAS\work\CNOP\dumps\temp/20150412_143656/

In [101]:
results03=next(MCgenr03)


9000/9000 tasks finished after 27837 s
done
[Engine Exception]
Traceback (most recent call last):
  File "C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\controller\scheduler.py", line 357, in handle_stranded_tasks
    raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
EngineError: Engine '3eee9dda-99c1-4cf1-ac75-581c55a07963' died while running task u'7d0300e3-3bf1-4bcc-b133-a67538514249'

[Engine Exception]
Traceback (most recent call last):
  File "C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\controller\scheduler.py", line 357, in handle_stranded_tasks
    raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
EngineError: Engine 'cae851df-ac8e-4337-994e-98fff819727c' died while running task u'3585989d-0dee-4d04-b268-b7170e0d7ef5'

[Engine Exception]
Traceback (most recent call last):
  File "C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\controller\scheduler.py", line 357, in handle_stranded_tasks
    raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
EngineError: Engine '7bb7bf6c-3ac9-43bf-8fea-9a9c9c5934c1' died while running task u'72bbe114-e895-4446-abb1-efc817df12fa'

[Engine Exception]
Traceback (most recent call last):
  File "C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\controller\scheduler.py", line 357, in handle_stranded_tasks
    raise error.EngineError("Engine %r died while running task %r"%(engine, msg_id))
EngineError: Engine '4bf9c72f-68a0-4a62-9581-2cca598c7d48' died while running task u'6e445b62-3c01-4bd8-a9a5-339aa9fb0d9f'

In [ ]:


In [112]:
MCgenr06 = runMC(.6, 10000, autocorrelated_errors, df=x2000)
MCAsyncMapResult06 = next(MCgenr06)


Starting MC on 13 cores, 10000 replications of "autocorrelated_errors" with rho = 0.60 observations
If you again run next(), you will get wait_interactive() form and results would be backed up
Untill then you are free to use AsyncResult object that was apready yielded, but data will not be backed up!
\\DAP-NAS\work\CNOP\dumps\temp/20150413_005610/

In [113]:
results06=next(MCgenr06)


10000/10000 tasks finished after 33496 s
done
[35:apply]: 
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)<string> in <module>()
<ipython-input-108-792c319cc8cd> in doJob(i)
IOError: [Errno 22] invalid mode ('wb') or filename: '\\\\DAP-NAS\\work\\CNOP\\dumps\\temp/20150413_005610/201504130210250.0404848754521'

[34:apply]: 
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)<string> in <module>()
<ipython-input-108-792c319cc8cd> in doJob(i)
IOError: [Errno 22] invalid mode ('wb') or filename: '\\\\DAP-NAS\\work\\CNOP\\dumps\\temp/20150413_005610/201504130210250.143615438273'

In [ ]:


In [114]:
MCgenr09 = runMC(.9, 10000, autocorrelated_errors, df=x2000)
MCAsyncMapResult09 = next(MCgenr09)


Starting MC on 13 cores, 10000 replications of "autocorrelated_errors" with rho = 0.90 observations
If you again run next(), you will get wait_interactive() form and results would be backed up
Untill then you are free to use AsyncResult object that was apready yielded, but data will not be backed up!
\\DAP-NAS\work\CNOP\dumps\temp/20150413_112135/

In [115]:
results09=next(MCgenr09)


4837/10000 tasks finished after 19112 s
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-115-810c6d578694> in <module>()
----> 1 results09=next(MCgenr09)

<ipython-input-108-792c319cc8cd> in runMC(rho, n_repl, fun, path, prefix, ext, **kwargs)
     33     yield ar
     34 
---> 35     ar.wait_interactive()
     36     results = ar.get()
     37     cur_time_str=time.strftime('%Y%m%d_%H%M%S')

C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\client\asyncresult.pyc in wait_interactive(self, interval, timeout)
    392         tic = time.time()
    393         while not self.ready() and (timeout < 0 or time.time() - tic <= timeout):
--> 394             self.wait(interval)
    395             clear_output(wait=True)
    396             print("%4i/%i tasks finished after %4i s" % (self.progress, N, self.elapsed), end="")

C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\client\asyncresult.pyc in wait(self, timeout)
    141             self._wait_for_outputs(timeout)
    142             return
--> 143         self._ready = self._client.wait(self.msg_ids, timeout)
    144         if self._ready:
    145             try:

C:\Users\Andrew\Anaconda\lib\site-packages\IPython\parallel\client\client.pyc in wait(self, jobs, timeout)
   1089             if timeout >= 0 and ( time.time()-tic ) > timeout:
   1090                 break
-> 1091             time.sleep(1e-3)
   1092             self.spin()
   1093         return len(theids.intersection(self.outstanding)) == 0

KeyboardInterrupt: 

In [116]:
MCAsyncMapResult09.abort()

In [ ]:


In [129]:
MCgenr09_1 = runMC(.9, 5163, append_folder="20150413_112135", fun=autocorrelated_errors, df=x2000)
MCAsyncMapResult09_1 = next(MCgenr09_1)


Starting MC on 13 cores, 5163 replications of "autocorrelated_errors" with rho = 0.90 observations
If you again run next(), you will get wait_interactive() form and results would be backed up
Untill then you are free to use AsyncResult object that was apready yielded, but data will not be backed up!
\\DAP-NAS\work\CNOP\dumps\temp/20150413_112135/

In [130]:
results09_1=next(MCgenr09_1)


5163/5163 tasks finished after 20177 s
done
[3:apply]: 
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)<string> in <module>()
<ipython-input-124-3e6ecde4e1e0> in doJob(i)
IOError: [Errno 22] invalid mode ('wb') or filename: '\\\\DAP-NAS\\work\\CNOP\\dumps\\temp/20150413_112135/201504131923430.659241939717'


In [227]:
%%px --local


def autocorrelated_errors_x(rho, df, give_distortion=True):
    ###########################################################
    ##### This code is for partial-overlap case of CNOP########
    ###########################################################
    N=500

    #PreSampling:
    df = df[:N]
    #df = x2000[:N]
    
    ### DGP generation
    regime = pd.DataFrame() 
    beta,   alpha   = [0.6, 0.4], [0.9, 1.5]
    gammam, mum =     [0.3, 0.9], [-0.67, 0.36]
    gammap, mup =     [0.2, 0.3], [0.02, 1.28]
    distortion = arma_generate_sample(ar = [1, -rho], ma=[1], nsample = N)
    distortion = np.vstack((distortion, np.random.randn(2,N)))
    regime["xbeta"]    = df[["X1", "X2"]].dot(beta)    + distortion[0]
    regime['z-gammam'] = df[["X1", "X3"]].dot(gammam)  + distortion[1]
    regime['z+gammap'] = df[["X2", "X3"]].dot(gammap)  + distortion[2]
    regime['regime'] = regime['xbeta'].apply(lambda x: threshold(x,thresholds=alpha))
    regime['Y-']=regime['z-gammam'].apply(lambda x: threshold(x, thresholds=mum,values=[-2,-1,0]))
    regime['Y+']=regime['z+gammap'].apply(lambda x: threshold(x, thresholds=mup,values=[0,1,2]))
    df['Y'] = 0
    df['Y'] += np.where(regime['regime']==-1,regime['Y-'],0)
    df['Y'] += np.where(regime['regime']==1,regime['Y+'],0)
    ###df is full data matrix

    #Model starts here:
    exog = df[["X1", "X2", "X3"]]
    endog = df[["Y"]]
    l = {0:df}
    pan = pd.Panel(l)
    y      = pan.ix[:,:,['Y']]
    x      = pan.ix[:,:,["X1", "X2"]]
    zminus = pan.ix[:,:,["X1", "X3"]]
    zplus  = pan.ix[:,:,["X2", "X3"]]
    exog = {'x':x,'zplus':zplus,'zminus':zminus}
    CNOP4 = CNOP(y,exog, model='CNOP',interest_step=1)

    #Counting execution time for fit ...
    exec_time = {"fit":0,"se":0}
    start_time = time.time()
    res = CNOP4.fit( maxiter=250, disp=0)
    exec_time["fit"] = time.time() - start_time

    # And for Standard Errors as well
    try:
        start_time = time.time()
        res["se"] = CNOP4.se(res.x)
        exec_time["se"] = time.time() - start_time
        res['status'] = "OK"
    except Exception, e:
        print e
        res['status'] = e

    res["exec_time"]=exec_time

    if give_distortion:
        return res, distortion
    else:
        return res

In [147]:
rho=0.5
res, distortion = autocorrelated_errors_x(rho=rho, df=x2000)
print "Done for rho=%.3f" % (rho)
print "Res.status:", res.success

beta,   alpha   = [0.6, 0.4], [0.9, 1.5]
gammam, mum =     [0.3, 0.9], [-0.67, 0.36]
gammap, mup =     [0.2, 0.3], [0.02, 1.28]
res_real = beta+alpha+gammam+mum+gammap+mup
plt.bar(np.arange(len(res.x-res_real)),
                  list(res.x-res_real));

winsound.PlaySound(u'C:\Windows\Media\Windows Print complete.wav', winsound.SND_FILENAME)
print "X & SE:"
print np.dstack((res.x,np.array(res.se)))


Done for rho=0.500
Res.status: True
X & SE:
[[[ 0.84972254  0.18173823]
  [ 0.7489793   0.17787902]
  [ 1.55194172  0.42990198]
  [ 2.00233154  0.32720411]
  [ 0.45951546  0.11553206]
  [ 1.0535065   0.15988364]
  [-0.62816143  0.17627021]
  [ 0.57960918  0.2336302 ]
  [ 0.12485229  0.13313939]
  [ 0.15623085  0.13031907]
  [ 0.29471577  0.2415521 ]
  [ 1.21508746  0.18874771]]]

In [212]:
MCgenr03 = runMC(.3, 8503, fun=autocorrelated_errors_x, df=x2000)
MCAsyncMapResult03 = next(MCgenr03)


Starting MC on 13 cores, 8503 replications of "autocorrelated_errors_x" with rho = 0.30 observations
If you again run next(), you will get wait_interactive() form and results would be backed up
Untill then you are free to use AsyncResult object that was apready yielded, but data will not be backed up!
\\DAP-NAS\work\CNOP\dumps\temp/20150413_234307/

In [213]:
results03=next(MCgenr03)


8503/8503 tasks finished after 24731 s
done
DONE! DB in \\DAP-NAS\work\CNOP\dumps\temp/20150413_234307/

In [ ]:


In [220]:
MCgenr06 = runMC(.6, 10000, fun=autocorrelated_errors_x, df=x2000)
MCAsyncMapResult06 = next(MCgenr06)


Starting MC on 9 cores, 10000 replications of "autocorrelated_errors_x" with rho = 0.60 observations
If you again run next(), you will get wait_interactive() form and results would be backed up
Untill then you are free to use AsyncResult object that was apready yielded, but data will not be backed up!
\\DAP-NAS\work\CNOP\dumps\temp/20150414_085358/

In [221]:
results06=next(MCgenr06)


10000/10000 tasks finished after 44152 s
done
[2:apply]: 
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)<string> in <module>()
<ipython-input-209-3e6ecde4e1e0> in doJob(i)
IOError: [Errno 22] invalid mode ('wb') or filename: '\\\\DAP-NAS\\work\\CNOP\\dumps\\temp/20150414_085358/201504141252390.490266502233'

In [ ]:

MCgenr09 = runMC(.9, 10000, fun=autocorrelated_errors_x, df=x2000) MCAsyncMapResult09 = next(MCgenr09)

In [231]:
results09=next(MCgenr09)


10000/10000 tasks finished after 32218 s
done
DONE! DB in \\DAP-NAS\work\CNOP\dumps\temp/20150415_000032/

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [65]:
(np.matrix([[1,2,3],[4,5,6],[7,8,9],[10,12,12]])-[1,2,3]).mean(axis=1)


Out[65]:
matrix([[ 0.        ],
        [ 3.        ],
        [ 6.        ],
        [ 9.33333333]])

In [17]:
rho=0.5
N=1000

In [18]:
ACrng = np.array([arma_generate_sample(ar = [1, -rho], ma=[1], nsample = N) for i in range(3)])

In [33]:
ACrng[0].mean()


Out[33]:
-0.069112463199309387

In [36]:
import statsmodels.tsa.stattools

In [39]:
statsmodels.tsa.stattools.acf(ACrng[0])


Out[39]:
array([ 1.        ,  0.50132144,  0.22020868,  0.09132236,  0.02982614,
       -0.01942175, -0.01105547,  0.01568259,  0.03015956,  0.06453532,
        0.05803312,  0.04706826,  0.03739803,  0.04235316,  0.03462817,
        0.03484475,  0.02692754,  0.04061451,  0.03164208,  0.00298074,
       -0.00764724, -0.00509256,  0.00583346, -0.00267002, -0.0435213 ,
       -0.06878025, -0.0392789 , -0.01162159,  0.03902757,  0.041136  ,
        0.02605928,  0.0185213 ,  0.00839297, -0.03121933, -0.05212769,
       -0.0130405 , -0.0031086 ,  0.05032496,  0.05278086,  0.0166053 ,
       -0.06411126])