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 [2]:
# tog

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
    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

In [4]:
# @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 [5]:
### Profiling loop
def profile(input_list):
    global log
    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);

In [6]:
# #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


fail to fetch query, using default rule, B3/S23 
example query:2dntca_000000000060031c61c67f86a0

In [7]:
log=[];
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];


data generated for 2dntca_000000000060031c61c67f86a0

In [8]:
# 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 dynamics

  • Each point represent a single Cellular Automata. The position of the point indicates the characteristic of its dynamics. The red patch on the right indicates the disordered cluster, whereas the yellow patch on the lower-left indicate the ordered cluster. Anything outside represents some intermediate behaviour.
  • The green patch indicates complex dynamics of particular interest.
  • Hover on the point to display the rule-string of a single point. Click to display the rulestring as a copyable string, and open a simulator in a new pop-up window. (The simulator is provided by lv-plugin.js at http://lazyslug.no-ip.biz/lifeview/plugin/js/)
  • Click on the bottom-left widgets to Zoom-and-pan

In [9]:
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)

In [10]:
%%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>



In [ ]:


In [11]:
### 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)


/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[11]:

In [12]:
# mpld3.display(fig)

In [13]:
import numpy as np

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


Out[13]:
0.0

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


Log of the process:
Starting to profile 1 rules at 2 replicates,
 totaling 2 instances
0 of 2 
1 of 2 
data is succesfully generated at 2 replicates

 Detail of the input:
      familyname      2dntca    
      hmax            100       
      N               400       
      dimsiz          [400, 100, 400]
      rulestr         000000000060031c61c67f86a0
      alias           b3ianjrecqyks2ac3i2e3a2k3nj2i3re2n3cqyk
      siz             (400, 20, 20)

In [15]:
# 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)