Esempio n. 1
0
    def pick_interaction_rules(self, wmax):
        '''
        Make 1000 interaction rules, measures the 2d bdm, then picks the top 3 highest and lowest
        :param wmax: max width of CA states
        :return: None, just saves rules to pickle files
        '''

        # make a thousand, then pick from dist
        both_interaction_rules = []
        one_interaction_rules = []

        # Since these are randomly generated, they are almost guaranteed to have LOW bdm values
        # TODO: In the future, get a better way of getting an algorithmic distribution of interaction rules
        for i in range(5000):

            interaction_rules = self.make_interaction_rules(wmax)
            rule_both = interaction_rules['both_states']
            rule_one = interaction_rules['one_state']

            # get bdm
            rule_both_graph = nx.Graph()
            rule_both_graph.add_edges_from(rule_both.items())
            adj_both = nx.adjacency_matrix(rule_both_graph)
            rule_one_graph = nx.Graph()
            rule_one_graph.add_edges_from(rule_one.items())
            adj_one = nx.adjacency_matrix(rule_one_graph)

            bdm_graphs = BDM(ndim=2)
            bdm_interaction_rule_both = bdm_graphs.bdm(adj_both.toarray(),
                                                       normalized=True)
            bdm_interaction_rule_one = bdm_graphs.bdm(adj_one.toarray(),
                                                      normalized=True)

            both_interaction_rules.append(
                (rule_both, bdm_interaction_rule_both))
            one_interaction_rules.append((rule_one, bdm_interaction_rule_one))

        # sort by BDM value
        both_interaction_rules.sort(key=lambda x: x[1])
        one_interaction_rules.sort(key=lambda x: x[1])

        # pick top and bottom three
        both_rules_use = []
        both_rules_use.append(both_interaction_rules[:3])
        both_rules_use.append(both_interaction_rules[-3:])
        both_rules_use = [
            item for sublist in both_rules_use for item in sublist
        ]

        # pick top and bottom three PAIRS
        one_rules_use = []
        one_rules_use.append(one_interaction_rules[:6])
        one_rules_use.append(one_interaction_rules[-6:])
        one_rules_use = [item for sublist in one_rules_use for item in sublist]

        # save rules to file
        pickle.dump(both_rules_use, open('both_rules_use', "wb"))
        pickle.dump(one_rules_use, open('one_rules_use', "wb"))

        return None
Esempio n. 2
0
def k_complexity_bw(image):
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = image.reshape(image.shape[0] * image.shape[1])
    image = image * (252 / 256)
    # bins = list(range(0, 252, 28))
    image = nb_digitize(image, bins=bins_0_252)
    # image = np.digitize(image, bins=bins)-1
    bdm = BDM(ndim=1, nsymbols=9, warn_if_missing_ctm=False)
    return bdm.bdm(image)
Esempio n. 3
0
def k_complexity_lab_b(image):
    image = cv2.cvtColor(image, cv2.COLOR_BGR2Lab)
    image = image.astype(
        'float32'
    ) / 255  # transformation to fix Euclidian distances in Lab space
    image = image[:, :, 2]
    image = image.reshape(image.shape[0] * image.shape[1])
    # bins = list(np.arange(0, 0.9, 0.1))
    image = nb_digitize(image, bins=bins_0_0_9)
    # image = np.digitize(image, bins=bins)-1
    bdm = BDM(ndim=1, nsymbols=9, warn_if_missing_ctm=False)
    return bdm.bdm(image)
Esempio n. 4
0
    def init_bdm(self, type, grouping):
        '''
        Initialize the bdm class for genomes, always going to be ndim=1 and nsymbols=4
        type: str, either genes or proteins
        :return: bdm class
        '''

        # initialize BDM class
        if type == 'proteins' or type == 'random_proteins':
            # only one amino acid grouping uses 8 symbols
            if grouping == '8':
                nsymbols = 8
            else:
                nsymbols = 9
        elif type == 'genes':
            nsymbols = 4
        else:
            print('What kind of sequence is it?')

        bdm = BDM(ndim=1,
                  nsymbols=nsymbols,
                  warn_if_missing_ctm=False,
                  partition=PartitionRecursive)

        return bdm
Esempio n. 5
0
def test_ctm_distribution_d1(nsymbols):
    """Check normalization of CTM distributions."""
    bdm = BDM(ndim=1, nsymbols=nsymbols)
    total = 0
    for dct in bdm._ctm.values():
        for key, cmx in dct.items():
            n = len(set(key))
            mult = factorial(nsymbols) / factorial(nsymbols - n)
            total += 2**-cmx * mult
    assert total == approx(1, .01)
Esempio n. 6
0
    def init_bdm(self):

        '''
        Initialize the bdm class for 2 dimensions and 2 symbols
        :return: bdm class
        '''

        bdm = BDM(ndim=2)

        return bdm
Esempio n. 7
0
def test_parts_coverage_d1(nsymbols, size):
    """Check the fraction of possible parts that have CTM values."""
    bdm = BDM(ndim=1, nsymbols=nsymbols)
    expected = sum(nsymbols**i for i in range(1, size + 1))
    total = 0
    for dct in bdm._ctm.values():
        for key, _ in dct.items():
            n = len(set(key))
            mult = factorial(nsymbols) / factorial(nsymbols - n)
            total += mult
    assert total / expected >= .25
    def k_complexity(self):
        image = self.cv2_img_bw
        image = image.reshape(image.shape[0] * image.shape[1])
        image = image * (252 / 256)
        image = np.digitize(image, bins=bins_0_252) - 1
        bdm = BDM(ndim=1, nsymbols=9, warn_if_missing_ctm=False)
        feature_value = bdm.bdm(image)
        self.extracted_features.update({'k_complexity_bw': feature_value})

        if self.other_config['extract_lab_channels']:
            for k, v in {'L': 0, 'a': 1, 'b': 2}.items():
                image_ = self.cv2_img_lab * (252 / 256)
                image_ = image_.astype(
                    'float32'
                ) / 255  # transformation to fix Euclidian distances in Lab space
                image_ = image_[:, :, v]
                image_ = image_.reshape(image_.shape[0] * image_.shape[1])
                image_ = np.digitize(image_, bins=bins_0_0_9) - 1
                feature_value = bdm.bdm(image_)
                self.extracted_features.update(
                    {f'k_complexity_{k}_channel': feature_value})
Esempio n. 9
0
def calculate_bdm():

    # init bdm class
    bdm_one = BDM(ndim=2, nsymbols=2, warn_if_missing_ctm=False)


    with open('pickle_jar/all_states') as fp:

        for line in fp:

            print(line)

            bdms_white = []
            bdms_black = []

            # go between black and white each move (white goes first)
            for i, state in enumerate(ast.literal_eval(line)):

                # if even (starting at 0), means it is white turn (just after a move was made
                if (i % 2) == 0:
                    state_white = re.sub('2', '0', line)
                    state_white = ast.literal_eval(state_white)[i]
                    measure_white = bdm_one.bdm(np.array(state_white), normalized=True)
                    bdms_white.append(measure_white)

                # else it means black just made the move
                else:
                    state_black = re.sub('1', '0', line)
                    state_black = re.sub('2', '1', state_black)
                    state_black = ast.literal_eval(state_black)[i]
                    measure_black = bdm_one.bdm(np.array(state_black), normalized=True)
                    bdms_black.append(measure_black)


            # save to file as you chug along. Then this can be used for a plot later
            with open("pickle_jar/bdms_white_all", "a+") as myfile:
                myfile.write(str(bdms_white) + '\n')
            with open("pickle_jar/bdms_black_all", "a+") as myfile:
                myfile.write(str(bdms_black) + '\n')
Esempio n. 10
0
def bdm_d1():
    return BDM(ndim=1)
Esempio n. 11
0
import re, csv, os
import pickle
from run_model import RegularCA
from pybdm import BDM
from pybdm.partitions import PartitionRecursive
import numpy as np

wmax = 3
bdm = BDM(ndim=1, warn_if_missing_ctm=False, partition=PartitionRecursive)
bdm_traj = BDM(ndim=1,
               nsymbols=9,
               warn_if_missing_ctm=False,
               partition=PartitionRecursive)

# map states to integers
ks = ['111', '110', '101', '100', '011', '010', '001', '000']
vs = list(range(8))
states_ints_map = dict(zip(ks, vs))

# only use the 88 unique ca rules for this analysis, since it's taking a while to come up with results
# (will reduce redundancy anyways)
use_these_rules = [
    0, 1, 4, 5, 18, 19, 22, 23, 32, 33, 36, 37, 50, 51, 54, 55, 72, 73, 76, 77,
    90, 91, 94, 95, 104, 105, 108, 109, 122, 123, 126, 127, 128, 129, 132, 133,
    146, 147, 150, 151, 160, 161, 164, 165, 178, 179, 182, 183, 200, 201, 204,
    205, 218, 219, 222, 223, 232, 233, 236, 237, 250, 251, 254, 255
]

# ============ ECA trajectories ==============

# instantiate eca class instance
Esempio n. 12
0
        for j in range(k*6):    # every cycle contains 6 random cbits
            if QuantumCoinFlip(1)[0]!=0:
            # if QuantumCoinFlip(1).get("0")!=None:
                single_string.append(1)
            else:
                single_string.append(0)
        if len(gen_strings)==0:
            gen_strings = single_string
        else: 
            gen_strings = np.vstack((gen_strings, single_string))
        single_string = np.array(single_string)
        single_string = []
    return gen_strings

# Initialization of Block Decomposition Method option - characterizes randomness of a binary-entry matrix
bdm = BDM(ndim=2, nsymbols=2)

# Integer to gate dict - 4-7 belong to axes of rotation 45° from the main X-Y axes
NumberToGateDict = {
    0 : "ScramblingCircuit.rx(pi/2, i)",
    1 : "ScramblingCircuit.rx((-1)*pi/2, i)",
    2 : "ScramblingCircuit.ry(pi/2, i)",
    3 : "ScramblingCircuit.ry((-1)*pi/2, i)",
    4 : "ScramblingCircuit.r(pi/2, pi/4, i)",
    5 : "ScramblingCircuit.r((-1)*pi/2, pi/4, i)",
    6 : "ScramblingCircuit.r(pi/2, 3*(pi/4), i)",
    7 : "ScramblingCircuit.r((-1)*pi/2, 3*(pi/4), i)"
} 

# Main function, scrambling unitary
def ScramblingU(n, k, nearest=True, filters=True, printArray=False):
Esempio n. 13
0
def bdm_d1_collapse3():
    return BDM(ndim=1, partition=PartitionCorrelated, shift=3)
Esempio n. 14
0
#Module sys has to be imported:
import sys
import numpy as np
from pybdm import BDM
from pybdm import options

options.set(raise_if_zero=False)

file = sys.argv[1]
with open(file, 'r') as file:
    data = file.read().replace('\n', '')

tape = np.fromstring(data, dtype=int, sep='-')
bdm = BDM(ndim=1, nsymbols=2)
value = bdm.nbdm(tape)
value2 = bdm.nent(tape)
if value2 == data:
    value2 = 0
if (value == 0 and (np.isnan(value2) is False)
        and value2 > 0.0) or (value2 < value and value2 > 0.0):
    value = value2

print(value)
Esempio n. 15
0
#!/usr/bin/env python
#Python script:
import sys
import numpy as np
from pybdm import BDM
from pybdm import options

options.set(raise_if_zero=False)

file = sys.argv[1]

with open(file, 'r') as file:
    data = file.read()

imagelist = data.splitlines()
number_of_lines = len(imagelist[0])
s = ""
image_array = np.empty((0, number_of_lines), dtype=int)

for line in imagelist:
    for char in line:
        s += char + "-"
    image_array = np.vstack(
        [image_array, np.fromstring(s, dtype=int, sep="-")])
    s = ""

bdm = BDM(ndim=2, nsymbols=2)
value = bdm.bdm(image_array)
value = (value / image_array.size)
print(value)
Esempio n. 16
0
#!python
#!/usr/bin/env python
#Python script:
import sys
import numpy as np
from pybdm import BDM
from pybdm import options

options.set(raise_if_zero=False)

file = sys.argv[1]

with open(file, 'r') as file:
   data = file.read()

imagelist = data.splitlines()
number_of_lines=len(imagelist[0])
s = ""
image_array = np.empty((0,number_of_lines),dtype=int)

for line in imagelist:
        for char in line:
            s += char + "-"
        image_array=np.vstack([image_array, np.fromstring(s, dtype=int, sep="-")])
        s = ""

bdm = BDM(ndim=2,nsymbols=2)
nbdm = bdm.nbdm(image_array)
print(nbdm)
Esempio n. 17
0
def bdm_d2():
    return BDM(ndim=2)
Esempio n. 18
0
                        chem = out_node[len(amount):]
                        amount = float(amount)
                    else:
                        amount = 1.0
                        chem = out_node

                    G.add_node(chem, bipartite=0)
                    G.add_edge(reaction_id, chem, amount=amount)

            plume_networks[plume + '_' + temp] = G

    # apply BDM measure to each graph
    # perturb each reaction node to see the change in complexity
    # save that value as a node attribute

    bdm = BDM(ndim=2)

    for plume_network in plume_networks.keys():

        # get bdm for graph
        G = plume_networks[plume_network]
        bottom_nodes, top_nodes = bipartite.sets(G)

        adj = nx.adj_matrix(G)
        adj = scipy.sparse.csr_matrix.toarray(adj)
        bdm_before = bdm.bdm(adj)

        for reaction_node in bottom_nodes:

            # get bdm for graph with removed node
            removed_graph = copy.deepcopy(G)
Esempio n. 19
0
def bdm_d1_b9():
    return BDM(ndim=1, nsymbols=9, partition=PartitionRecursive, min_length=1)
Esempio n. 20
0
#!python
#!/usr/bin/env python
#Python script:
import sys
import numpy as np
from pybdm import BDM
from pybdm import options
import warnings
warnings.filterwarnings("ignore")

options.set(raise_if_zero=False)
options.set(warn_if_missing_ctm=False)

file = sys.argv[1]

with open(file, 'r') as file:
    data = file.read()

Translator = {"A": 0, "C": 1, "G": 2, "T": 3}
datafile = list(map(lambda x: Translator[x], data))

datafile = np.asarray(datafile)
bdm = BDM(ndim=1, nsymbols=4)
nbdm = bdm.nbdm(datafile)
print(nbdm)
Esempio n. 21
0
import warnings
from pybdm import BDM
from pybdm.partitions import PartitionRecursive
from algorithms import PerturbationExperiment, NodePerturbationExperiment
from getpass import getuser
# Settings and loading of adj matrix
input_file = str(sys.argv[1])
start = time.time()
pid = os.getpid()
ps = psutil.Process(pid)
warnings.filterwarnings("ignore")
with open(input_file, 'rb') as f:
    dti_adj = pickle.load(f)['dti_adj']
print('\nInput data loaded\n')
jobs = 4
bdm = BDM(ndim=2, partition=PartitionRecursive)
part = 'PartitionRecursive'
# ============================================================================================= #
# CALCULATION
# Node perturbation
dti_nodeper = NodePerturbationExperiment(bdm,
                                         metric='bdm',
                                         bipartite_network=True,
                                         parallel=True,
                                         jobs=jobs)
dti_nodeper.set_data(np.array(dti_adj.todense()))
print("Initial BDM calculated for nodes\n")
nodebdm_genes_dti, nodebdm_drugs_dti = dti_nodeper.run()
print('BDM for DTI calculated\n')
# Edge perturbation
dti_edgeper = PerturbationExperiment(bdm, bipartite_network=True)
Esempio n. 22
0
    image_buffed_array = np.vstack([image_buffed_array, a])

    s = ""

print(image_array.shape)
np.savetxt('image.txt', image_array, fmt='%d', delimiter='')
print(image_buffed_array.shape)
np.savetxt('amplified_image.txt', image_buffed_array, fmt='%d', delimiter='')

for x in range(0, 8):
    for y in range(0, 8):
        print(image_array[x][y], end="  ")
    print()

for x in range(0, 16):
    for y in range(0, 16):
        print(image_buffed_array[x][y], end="  ")
    print()

bdm = BDM(ndim=2, nsymbols=2)
print(bdm.partition.shape)
val = bdm.bdm(image_array)
value = (val / image_array.size)
print("Original BDM value:", '{:.5f}'.format(val))

bdm_new_value = BDM(ndim=2, nsymbols=2)
val = bdm_new_value.bdm(image_buffed_array)
value = (val / image_buffed_array.size)

print("new BDM value:", '{:.5f}'.format(val))