In [1]:
from astropy.convolution import *
import sys
import os
sys.path.append(os.path.abspath('..'))
%matplotlib notebook
# utils=os.path.abspath('..')
from utils import *
import time
from KBs import *
(HTML(tog))


Out[1]:

In [48]:
import astropy.convolution
import scipy.signal
import scipy.ndimage
convolve_int=lambda a,fir,method:np.around(convolve(a,fir,method)).astype(np.int);


mat = np.random.randint(0,2,(100,128,128))
fir=np.reshape(2 ** (np.arange(0,9)),[1,3,3])
method = 'wrap'

In [56]:
%%bash
python3 rstr2html.py ../calc_temp_data/result_count0.csv


../calc_temp_data/result_count0.csv
Created new window in existing browser session.
10/29/2017 01:03:14 AM INFO: Reading notebook calc_temp.ipynb
10/29/2017 01:03:15 AM INFO: Running cell:
from astropy.convolution import *
import sys
import os
sys.path.append(os.path.abspath('..'))
%matplotlib notebook
# utils=os.path.abspath('..')
from utils import *
import time
from KBs import *
(HTML(tog))


global log
log = []

10/29/2017 01:03:16 AM INFO: Cell returned
10/29/2017 01:03:16 AM INFO: Running cell:
# tog

10/29/2017 01:03:16 AM INFO: Cell returned
10/29/2017 01:03:16 AM INFO: Running cell:
# convolve_int=lambda a,fir,method:np.around(convolve(a,fir,method)).astype(np.int);

def csv2dat(fname):
    import csv 
    import numpy as np
    global log
    dat=[];
    with open(fname, 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter='\t')
        for row in (spamreader):
            dat+=[row];

    log = log + ['Used \''+fname+'\' as input '];


    return (np.array(dat));

# if not 'input_rulestr' in locals():
#     input_rulestr='000000000060031c61c67f86a0';
# input_rulestr
# CA_sys

10/29/2017 01:03:16 AM INFO: Cell returned
10/29/2017 01:03:16 AM INFO: Running cell:
# #test
# ca1=CA_sys('2dntca',input_rulestr,[600,100,400]);
# ca1.rulestr2alias();
# s=measure_temperature(ca1,hdist);
# output_data=[];
from os import environ
log=[];
if 'query' not in locals():
    query = environ.get('query');
    if not query==None:        
        query = environ['query'];
        if query[-4:]=='.csv':
            query_type = 'csv';
        else:
            query_type = 'rulestr';
#             familyname, input_rulestr = query.split('_');
    else:
    #     familynam
        query='2dntca_000000000060031c61c67f86a0';
        query_type = 'rulestr'
#         familyname, input_rulestr = query.split('_');
        log+=['fail to fetch query, using default rule, B3/S23 \n' +
        'example query:'+query];
        ## Using B3/S23 as example

if query_type == 'csv':
#     sample_dat, log = 
    sample_data=csv2dat('../calc_temp_data/'+query);
    print('data loaded')
if query_type == 'rulestr':
    familyname, input_rulestr = query.split('_');
    sample_data= profile([input_rulestr])
    log+=['data generated for '+query];

10/29/2017 01:03:16 AM INFO: Cell returned
10/29/2017 01:03:16 AM INFO: Running cell:
# import numpy as np

# # TEST sample_data
# sample_data=np.array([['2dntca_b3ianjrecqyks2ac3i2e3a2k3nj2i3re2n3cqyk',
#         '000000000060031c61c67f86a0', '99', '0.148772', '0.087523',
#         '0.089563'],
#        ['2dntca_b3ianjrecqyks2ac3i2e3a2k3nj2i3re2n3cqyk',
#         '000000000060031c61c67f86a0', '99', '0.152794', '0.086693',
#         '0.091644'],
#        ['2dntca_b3ianjrecqyks2ac3i2e3a2k3nj2i3re2n3cqyk',
#         '000000000060031c61c67f86a0', '99', '0.148733', '0.089657',
#         '0.089387'],
#        ['2dntca_b3ianjrecqyks2ac3i2e3a2k3nj2i3re2n3cqyk',
#         '000000000060031c61c67f86a0', '99', '0.150105', '0.092000',
#         '0.090981'],
#        ['2dntca_b3ianjrecqyks2ac3i2e3a2k3nj2i3re2n3cqyk',
#         '000000000060031c61c67f86a0', '99', '0.153150', '0.089772',
#         '0.090938']], 
#       dtype='<U46')

10/29/2017 01:03:16 AM INFO: Cell returned
10/29/2017 01:03:16 AM INFO: Running cell:
viewer='''<script src="lv-plugin.js"></script>\n
<meta name="LifeViewer" content="viewer textarea 60 hide">\n
<div class="viewer" id="viewer"><textarea id="textarea">bob!</textarea><br><canvas id="cv1" width="480" height="480"></canvas></div>\n''';
# HTML(viewer)

10/29/2017 01:03:17 AM INFO: Cell returned
10/29/2017 01:03:17 AM INFO: Running cell:
%%html
<script>
String.prototype.formatUnicorn = String.prototype.formatUnicorn ||
function () {
    "use strict";
    var str = this.toString();
    if (arguments.length) {
        var t = typeof arguments[0];
        var key;
        var args = ("string" === t || "number" === t) ?
            Array.prototype.slice.call(arguments)
            : arguments[0];

        for (key in args) {
            str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
        }
    }

    return str;
};

var s= new String("");
var soup=new String("3bo4b11o2b2ob2o2bobo$obobo2bo3bobo3bo2bob3ob2o$2b3obobob6o3b5o2bo2bo$bob2o3b2ob2ob3o4bo5bob2o$2o3b3o3bob4ob2o4bobob2o$5bo4bo4b2obo3b3o2bo$o2bob3obob4o4b3obob2obobo$3bo4bob5o5b3ob2o2b2o$2b3obob2ob4o2bo3bobo3bo$bo4bob2ob6obo3bo4bob2o$5b4obo3bo4bo5bo2bo$ob2obobo2bob2o2bobo2bo2b2o4bo$obo2b2ob2o2b2o3bo2b2obobob4o$6ob2ob2o3b2ob4obo3bob2o$3ob3obo2b3ob4ob4o5bo$obobo7bo3b2o6b3o3bo$bob3o6bob2ob2o3b4obob2o$o2b2o2bo2bo2bobob7ob2o3bo$2obo2bo2b5ob2obo3b2o4b2o$b2o2bob5obo2b5o2bob4o$2o2b4ob2ob4obo3bob3obo2bo$b2o3bo2bo3b6o2bo3bo2bo$bobo3b2ob2o3b3obo3bo5bo$o4b8obobobobob2ob2ob2o$3obo3b4obo3bob3obobo$o3b2obobob2o2b2o5bob2o$6bo5bob2o3b2obo2b2obo$7bo2b2obo2bobobo3bobo2b2o$2o4b7o4bo2b2ob2o3bo$o2bo3bobo3b4o2bo3b2obobo!");
var rule="b3s23578";
var template="x = 300, y = 300, rule = {0} \n {1}";
var div_template="<textarea>{0}</textarea><br><canvas width=\"480\" height=\"480\" tabindex=\"1\"></canvas>";

//s=template.formatUnicorn("B3/S23","bbboooobbbboo!");
//var s="<textarea>x = 300, y = 300, rule = B3/S238 \nbobbbbbbooooooo!</textarea><br><canvas width=\"480\" height=\"480\"></canvas>";
//alert(s)
var s = template.formatUnicorn(rule,soup)
//document.getElementById("viewer").innerHTML = s;
</script>





10/29/2017 01:03:17 AM INFO: Cell returned
10/29/2017 01:03:17 AM INFO: Running cell:


10/29/2017 01:03:17 AM INFO: Cell returned
10/29/2017 01:03:17 AM INFO: Running cell:
### Plotting sample_data

%matplotlib inline

# mpld3.enable_notebook()
from graphics import *
fig, ax = plt.subplots(subplot_kw=dict(axisbg='#DDDDDD'
#                                        ,projection='3d'
                                      ))
fig.set_size_inches([6,6])

ax.grid(color='white', linestyle='solid')
ax.set_ylim(-.1,0.38)
ax.set_xlim(0,1)

fig2,ax2=plt.subplots(subplot_kw=dict(axisbg='#DDDDDD'
                                       ,projection='3d'
                                      ))
fig2.set_size_inches([10,10])
# fig2.subplots_adjust(left=0.2, right=0.8, top=0.9, bottom=0.3)

ax2.grid(color='white', linestyle='solid')
ax2.set_ylim(-.1,0.38)
ax2.set_xlim(0,1)

fig,ax,fig2,ax2 = make_figure((fig,ax,fig2,ax2),sample_data)
fig.set_size_inches([7,7])
ax.set_ylim(-.1,0.38)
ax.set_xlim(0,1)

# display(HTML(viewer))



mpld3.display(fig)
# mpld3.display(fig2)





10/29/2017 01:03:20 AM INFO: Cell returned
10/29/2017 01:03:20 AM INFO: Running cell:
print {'b':{'1':['1e','1k']},'s':{'1':['1e','1k']}}



10/29/2017 01:03:20 AM INFO: Cell returned
10/29/2017 01:03:20 AM INFO: Running cell:
# len(KBs.henseldict)
# len(KBs.rca2ntca)
# KBs.henseldict[:51]
from KBs import *
import itertools
import collections
if 1:
        OUT = ''
        rulestr =  '000000000060031c61c67f86a0'
        r=hex2bin(rulestr,102);
        r=r[::-1];
        rule=[i for i,x in enumerate(r) if x=='1'];
#         print r
        lst = [henseldict[i] for i in rule]
        lst.sort()
        
        #### group by B/S
        d = collections.OrderedDict((('b',{}),('s',{}))) ### set default
#         d = {'b':{},'s':{}}   ### set default
        d.update(
            {k:list(gp) for k,gp in itertools.groupby(lst, lambda x:x[0])}        
        )
        for k,lst in d.iteritems():
            d[k] = {k:list(gp) for k,gp in itertools.groupby(lst, lambda x:x[1])}
            
        for bs, dd in d.iteritems():
            OUT += bs
            for k,lst in dd.iteritems():
                OUT += k + ''.join( conf[-1] for conf in lst)
        OUT = OUT.replace('_','')
        alias = OUT
#         return OUT
print OUT
# t

10/29/2017 01:03:20 AM INFO: Cell returned
10/29/2017 01:03:20 AM INFO: Running cell:
print lst.sort()
# lst

10/29/2017 01:03:20 AM INFO: Cell returned
10/29/2017 01:03:20 AM INFO: Running cell:


10/29/2017 01:03:20 AM INFO: Cell returned
10/29/2017 01:03:20 AM INFO: Running cell:
        from KBs import *
        OUT = ''
        rulestr =  '131c3c3c001fff03e03e000ea0'
        r=hex2bin(rulestr,102);
        r=r[::-1];
        rule=[i for i,x in enumerate(r) if x=='1'];
#         print r
        lst = [henseldict[i] for i in rule]
        lst.sort()
        print lst
        raise(Exception('stop'))
        #### group by B/S
        d = collections.OrderedDict((('b',{}),('s',{}))) ### set default
#         d = {'b':{},'s':{}}   ### set default
        d.update(
            {k:list(gp) for k,gp in itertools.groupby(lst, lambda x:x[0])}        
        )
        for k,lst in d.iteritems():
            d[k] = {k:list(gp) for k,gp in itertools.groupby(lst, lambda x:x[1])}
            
        for bs, dd in d.iteritems():
            OUT += bs
            for k,lst in dd.iteritems():
                OUT += k + ''.join( conf[-1] for conf in lst)
        OUT = OUT.replace('_','')
        alias = OUT

10/29/2017 01:03:20 AM INFO: Cell raised uncaught exception: 

ExceptionTraceback (most recent call last)
<ipython-input-12-7c3d8aaed7f8> in <module>()
      9 lst.sort()
     10 print lst
---> 11 raise(Exception('stop'))
     12 #### group by B/S
     13 d = collections.OrderedDict((('b',{}),('s',{}))) ### set default

Exception: stop
10/29/2017 01:03:20 AM INFO: Saving to temp.ipynb
10/29/2017 01:03:21 AM INFO: Shutdown kernel
10/29/2017 01:03:21 AM WARNING: Exiting with nonzero exit status
/home/shouldsee/.local/lib/python3.5/site-packages/IPython/nbformat.py:13: ShimWarning: The `IPython.nbformat` package has been deprecated since IPython 4.0. You should import from nbformat instead.
  "You should import from nbformat instead.", ShimWarning)
/usr/local/lib/python3.5/dist-packages/nbformat/current.py:19: UserWarning: nbformat.current is deprecated.

- use nbformat for read/write/validate public API
- use nbformat.vX directly to composing notebooks of a particular version

  """)

In [54]:
%timeit astropy.convolution.convolve( mat,fir,method)
%timeit scipy.ndimage.filters.convolve(mat, fir, mode = method)


1 loop, best of 3: 229 ms per loop
10 loops, best of 3: 39.6 ms per loop

In [45]:
%timeit mat = scipy.ndimage.filters.convolve(mat, fir, mode = method)
%timeit mat = np.around(astropy.convolution.convolve( mat,fir,method)).astype(np.int);


Out[45]:
array([[[ 86, 164, 264, ...,  10,  21,  43],
        [180, 289,  66, ...,  86, 173, 346],
        [420, 265,  19, ..., 183, 367, 214],
        ..., 
        [143, 350, 180, ..., 393, 275, 103],
        [121, 242, 420, ...,  72, 152, 312],
        [458, 404, 289, ...,  65, 194, 453]],

       [[ 59, 127, 191, ...,   8,  24,  57],
        [475, 510, 508, ...,  68, 192, 457],
        [219, 502, 485, ...,  34,   4,  73],
        ..., 
        [147, 303,  23, ..., 480, 384, 329],
        [152, 377, 186, ..., 256,   0,  72],
        [199, 463, 471, ...,   1,   3,  71]],

       [[484, 456, 472, ..., 304, 105, 210],
        [292,  65, 194, ..., 386, 333, 146],
        [292,   8,  16, ...,  20, 105, 146],
        ..., 
        [ 36,  64, 201, ..., 228, 393, 274],
        [295,   7,  79, ..., 292,  73, 147],
        [316,  57, 123, ..., 294,  77, 154]],

       ..., 
       [[178, 292,  72, ..., 169, 282, 125],
        [400, 288,  65, ..., 335, 214, 492],
        [135, 263,  14, ..., 125, 179, 359],
        ..., 
        [493, 466, 421, ..., 194, 461, 466],
        [362, 148, 297, ...,  18, 108, 145],
        [342, 164, 329, ..., 149, 355, 143]],

       [[131, 326, 140, ..., 511, 438, 357],
        [ 29,  50, 101, ..., 510, 437, 298],
        [238, 404, 297, ..., 497, 427, 343],
        ..., 
        [280, 121, 251, ..., 299,  86, 172],
        [194, 461, 474, ..., 351, 182, 357],
        [ 16, 104, 209, ..., 255, 438, 300]],

       [[366, 213, 419, ..., 402, 365, 147],
        [372, 169, 283, ..., 151, 367, 158],
        [416, 329, 219, ..., 187, 382, 244],
        ..., 
        [ 69, 202, 468, ...,  22,  37,   2],
        [ 45,  83, 166, ..., 182, 301,  18],
        [365, 154, 308, ..., 434, 365, 146]]])

In [31]:
mat = np.random.randint(0,2,(128,128))
method = 'wrap'
%timeit mat = np.around(astropy.convolution.convolve( mat,fir,method)).astype(np.int);


Out[31]:
array([[0, 1, 1, ..., 1, 1, 1],
       [0, 1, 0, ..., 0, 1, 1],
       [0, 0, 1, ..., 1, 1, 0],
       ..., 
       [0, 0, 1, ..., 1, 0, 0],
       [1, 1, 0, ..., 1, 0, 1],
       [1, 0, 1, ..., 0, 1, 0]])

In [3]:
convolve_int=lambda a,fir,method:np.around(convolve(a,fir,method)).astype(np.int);

def csv2dat(fname):
    import csv 
    import numpy as np
    dat=[];
    with open(fname, 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter='\t')
        for row in (spamreader):
            dat+=[row];

    log = 'Used \''+fname+'\' as input ';


    return (np.array(dat),log);

# if not 'input_rulestr' in locals():
#     input_rulestr='000000000060031c61c67f86a0';
# input_rulestr
# CA_sys

In [3]:
# @function
def measure_temperature(sys0=None,hdist=None,*args,**kwargs):
#     varargin = measure_temperature.varargin
#     nargin = measure_temperature.nargin
    sysX=copy.copy(sys0)
    jmax=sysX.N;
    avi=sysX.rdf()
    siz=avi.shape
    siz=(sysX.hmax,)+siz;
    tmp=np.zeros(siz)
    smtmp=np.zeros(siz)

    avc=avi
    i=0
    fir=np.reshape(2 ** (np.arange(0,9)),[1,3,3])
    trans=6
    mtp=0
    stp=0
    while i+1 < sysX.hmax:

        i=i + 1
        avcnew=(sysX.adv(avc,i))
        cavc=convolve_int(avc,fir,'wrap').astype(np.int);
        cavcnew=convolve_int(avcnew,fir,'wrap').astype(np.int);
        idx=np.ravel_multi_index((cavc,cavcnew),[2**9,2**9]);
        tmp[i,:,:,:]=np.expand_dims(hdist.flat[idx],0)
        if i >= trans:
            smtmpnow=np.mean(tmp[i - trans:i,:,:,:],axis=0)
            smtmp[i - trans,:,:,:]=smtmpnow
            if i >= trans + 10:
                mtp=np.mean(smtmpnow.flat)
                stpmat=((smtmp[i - trans,:,:,:] - smtmp[i - trans - trans,:,:,:]))
                a=np.mean(np.abs(stpmat.flat))
                b=abs(np.mean(stpmat.flat))
                stp=a - b
                stp1=np.mean(avcnew.flat)
                stp1=min(stp1,1 - stp1)
        avc=avcnew;
        #     im1=[avc(1,:,:)];
        if mtp < 0.02 and i > 20:
            break
    
    fam_alias=sys0.familyname+'_'+sys0.alias;
# /home/shouldsee/Documents/repos/CA_tfmat/custom_function/measure_temperature.m:55
    # s=sprintf('%s\\t%s\\t%d\\t%f\\t%f\\t%f\\n',fam_alias,num2str(sys0.od),i,mtp,stp,stp1)
    s='{}\t{}\t{:d}\t{:f}\t{:f}\t{:f}\n'.format(fam_alias,sysX.rulestr,i,mtp,stp,stp1)
# /home/shouldsee/Documents/repos/CA_tfmat/custom_function/measure_temperature.m:56
    return s
    
# if __name__ == '__main__':
#     pass

In [4]:
### Profiling loop
def profile(input_list):
    output_data=[];    
    repeat=2;
    # input_list=[input_rulestr];
    ipt_list=input_list*repeat;
    # for i in range(5):
    l_ipt=len(input_list)
    log = ['Log of the process:'];
    logs='Starting to profile {:d} rules at {:d} replicates,\n totaling {:d} instances'.format(l_ipt,repeat,l_ipt*repeat);
    log += [logs];
    # print('Starting to profile {:d} rules at {:d} replicates,\n totaling {:d} instances'.format(l_ipt,repeat,l_ipt*repeat))

    for num,rulestr in enumerate(ipt_list):
        ca1=CA_sys(familyname,rulestr,[400,100,400]);
        ca1.rulestr2alias();
        s=measure_temperature(ca1,hdist);
        output_data+=[s];
    #     print('{:d} of {:d}'.format(num,len(ipt_list)))
        logs =('{:d} of {:d} '.format(num,len(ipt_list)));
        log += [logs];
    temp_data=[];
    # sample_data=[]
    for line in output_data:
        temp_data+=[line.rstrip('\n').split('\t')];
    sample_data=np.array(temp_data)
    # print('data is succesfully generated at {:d} replicates'.format(repeat))
    logs=('data is succesfully generated at {:d} replicates'.format(repeat))

    log  += [logs];

    # print('\n Detail of the input:')
    logs='\n Detail of the input:';
    log+=[logs];
    for k,v in ca1.__dict__.items():
        if not callable(v):
    #         print(k+str(v).ljust(-10))
    #         print("{:5} {:<15} {:<10}".format('',k, str(v)))

            logs=("{:5} {:<15} {:<10}".format('',k, str(v)));
            log+=[logs];
    return (sample_data,log);

In [5]:
# #test
# ca1=CA_sys('2dntca',input_rulestr,[600,100,400]);
# ca1.rulestr2alias();
# s=measure_temperature(ca1,hdist);
# output_data=[];
from os import environ
# environ['query']='result_count0.csv'
try:
    query = environ['query'];
    if query[-4:]=='.csv':
        query_type = 'csv';
    else:
        query_type = 'rulestr';
        familyname, input_rulestr = query.split('_');
except:
#     familynam
    query='2dntca_000000000060031c61c67f86a0';
    query_type = 'rulestr'
    familyname, input_rulestr = query.split('_');
    print('fail to fetch query, using default rule, B3/S23 \n' +
    'example query'+query);
    ## Using B3/S23 as example

In [6]:
if query_type == 'csv':
#     sample_dat, log = 
    sample_data, log=csv2dat(query);
    print('data loaded')
if query_type == 'rulestr':
    sample_data, log= profile([input_rulestr])
    print('data generated')


data loaded

In [7]:
# import numpy as np

# # TEST sample_data
# sample_data=np.array([['2dntca_b3ianjrecqyks2ac3i2e3a2k3nj2i3re2n3cqyk',
#         '000000000060031c61c67f86a0', '99', '0.148772', '0.087523',
#         '0.089563'],
#        ['2dntca_b3ianjrecqyks2ac3i2e3a2k3nj2i3re2n3cqyk',
#         '000000000060031c61c67f86a0', '99', '0.152794', '0.086693',
#         '0.091644'],
#        ['2dntca_b3ianjrecqyks2ac3i2e3a2k3nj2i3re2n3cqyk',
#         '000000000060031c61c67f86a0', '99', '0.148733', '0.089657',
#         '0.089387'],
#        ['2dntca_b3ianjrecqyks2ac3i2e3a2k3nj2i3re2n3cqyk',
#         '000000000060031c61c67f86a0', '99', '0.150105', '0.092000',
#         '0.090981'],
#        ['2dntca_b3ianjrecqyks2ac3i2e3a2k3nj2i3re2n3cqyk',
#         '000000000060031c61c67f86a0', '99', '0.153150', '0.089772',
#         '0.090938']], 
#       dtype='<U46')

Landscape of the observed dynamics

  • Hover on the point to get the NTCA(non-totalistic cellular automata) rule-string. Click to display the rulestring as a copyable string.
  • Click on the bottom-left widgets to Zoom-and-pan

In [8]:
### Plotting sample_data

%matplotlib inline
# mpld3.enable_notebook()
from graphics import *
fig, ax = plt.subplots(subplot_kw=dict(axisbg='#DDDDDD'
#                                        ,projection='3d'
                                      ))
fig.set_size_inches([6,6])

ax.grid(color='white', linestyle='solid')
ax.set_ylim(-.1,0.38)
ax.set_xlim(0,1)

fig2,ax2=plt.subplots(subplot_kw=dict(axisbg='#DDDDDD'
                                       ,projection='3d'
                                      ))
fig2.set_size_inches([10,10])
# fig2.subplots_adjust(left=0.2, right=0.8, top=0.9, bottom=0.3)

ax2.grid(color='white', linestyle='solid')
ax2.set_ylim(-.1,0.38)
ax2.set_xlim(0,1)

fig,ax,fig2,ax2 = make_figure((fig,ax,fig2,ax2),sample_data)
fig.set_size_inches([7,7])
ax.set_ylim(-.1,0.38)
ax.set_xlim(0,1)

mpld3.display(fig)


/home/shouldsee/.local/lib/python3.5/site-packages/matplotlib/cbook.py:136: MatplotlibDeprecationWarning: The axisbg attribute was deprecated in version 2.0. Use facecolor instead.
  warnings.warn(message, mplDeprecation, stacklevel=1)
Out[8]:

In [9]:
import numpy as np

sum(float(x)>0.3 for x in list(sample_data[:,3]))/sample_data.shape[0]


Out[9]:
0.9618063896228681

In [10]:
# len(ntca_list)
# .shape
# print(tst_data)
print('\n'.join(log));


U
s
e
d
 
'
c
a
l
c
_
t
e
m
p
_
d
a
t
a
/
r
e
s
u
l
t
_
c
o
u
n
t
0
.
c
s
v
'
 
a
s
 
i
n
p
u
t
 

In [11]:
# from nbconvert import HTMLExporter
# import codecs
# import nbformat
# exporter = HTMLExporter()
# # execfile()
# output_notebook = nbformat.read('calc_temp.ipynb', as_version=4)
# output, resources = exporter.from_notebook_node(output_notebook)
# codecs.open('test.html', 'w', encoding='utf-8').write(output)