Пример #1
0
 def test_generate_ca_sequence(self):
     """
     Test Case #1
     Check return type
     """
     result = type(CA.generate_ca_sequence(30, 1, 1, 8, 10))
     self.assertTrue(result is list)
     """
     Test Case #2
     Check for correct values
     """
     result = CA.generate_ca_sequence(30, 1, 1, 8, 10)
     expected = [1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1]
     self.assertEqual(result, expected)
     """
     Test Case #3
     Check for length
     """
     result = len(CA.generate_ca_sequence(30, 1, 1, 8, 1))
     expected = 2  # number generations + 1 (zero indexing)
     self.assertEqual(result, expected)
     """
     Test Case #4
     Check for edge case
     """
     result = len(CA.generate_ca_sequence(30, 1, 1, 8, 0, 1))
     expected = 1  # number of generations + 1 (zero indexing)
     self.assertEqual(result, expected)
Пример #2
0
def Encrypt(bytes:list, seed, steps:int):
    global seedlen, debug
    assert len(seed) > 20
    CA.r_initCA(seed, steps) #Start up the CA with the specified seed and steps
    m_data = bytes[:]
    m_head = 0
    ca_m_head = 4
    ca_enc_head = len(seed) // 2 - 4

    d = dlast = []

    while (CA.steps <= 0):
        dlast = d
        d = CA.update()
        if (d[ca_m_head] == 1):
            m_head += 1
            if (m_head >= len(m_data)):
                m_head = 0
        else:
            pass #don't move m_head
        b = "0b"
        r = d.range()
        for i in range(r[0] + ca_enc_head, r[0] + ca_enc_head + 8):
            b += str(d[i])
        m_data[m_head] = m_data[m_head] ^ int(b, 2)
        DumpCurrentRow(CA.steps, m_head, m_data, ca_m_head, d, b)
    #debug.write("\n\n\n")
    return m_data
Пример #3
0
 def test_make_config(self):
     """
     Test Case #1
     Check for correct return type
     """
     result = type(CA.make_config(30, 1))
     self.assertTrue(result is list)
     """
     Test Case #2
     Check for correct values
     """
     result = CA.make_config(30, 8)
     expected = [0, 1, 1, 1, 1, 0, 0, 0]
     self.assertEqual(result, expected)
     """
     Test Case #3
     Check for correct length
     """
     result = len(CA.make_config(30, 8))
     expected = 8
     self.assertEqual(result, expected)
     """
     Test Case #4
     Test edge case
     """
     result = CA.make_config(0, 8)
     expected = [0, 0, 0, 0, 0, 0, 0, 0]
     expected = expected[::-1]
     self.assertEqual(result, expected)
Пример #4
0
 def test_dec_to_bin(self):
     """
     Test Case #1
     Check return type
     """
     result = type(CA.dec_to_bin(8, 4))
     self.assertTrue(result is list)
     """
     Test Case #2
     Check for expected value
     Values are ordinal so they need to be reversed
     """
     result = CA.dec_to_bin(8, 4)
     expected = [1, 0, 0, 0]
     expected = expected[::-1]  # reversed
     self.assertEqual(result, expected)
     """
     Test Case #3
     Check for edge case
     """
     result = CA.dec_to_bin(0, 4)
     expected = [0, 0, 0, 0]
     expected = expected[::-1]  # reversed
     self.assertEqual(result, expected)
     """
     Test Case #3
     Check for edge case
     """
     result = CA.dec_to_bin(15, 4)
     expected = [1, 1, 1, 1]
     expected = expected[::-1]  # reversed
     self.assertEqual(result, expected)
Пример #5
0
 def test_make_rule_table(self):
     """
     Test Case #1
     Check return type
     """
     result = type(CA.make_rule_table(30, 1))
     self.assertTrue(result is list)
     """
     Test Case #2
     Check rule 30 for correct value
     """
     result = CA.make_rule_table(30, 1)
     expected = [0, 1, 1, 1, 1, 0, 0, 0]
     self.assertEqual(result, expected)
     """
     Test Case #3
     Check for correct length
     """
     result = CA.make_rule_table(30, 1)
     expected = 8
     result_len = len(result)
     self.assertEqual(result_len, expected)
     """
     Test Case #4
     Check for edge case
     """
     result = CA.make_rule_table(0, 1)
     expected = 8  # default bits are equal to 8
     result_len = len(result)
     self.assertEqual(result_len, expected)
Пример #6
0
def train():

    features = []
    train = []
    keys = {}

    with open('train.csv', 'r') as dataset:

        for x, i in enumerate(next(dataset).split(',')):
            keys[i] = x  # Initialize list of feature names

        features = ([
            next(dataset).strip('\n').replace(' ', '').split(',')
            for x in range(35000)
        ])
        #Way too messy

    dataset.close()

    for i in range(len(features)):
        train.append(features[i].pop())

    #Remove unwanted data

    keep_list = []  #Only keep data points where room was booked
    for i in range(len(features)):

        if features[i][keys['is_booking']] == '1':
            keep_list.append(i)

    features = [features[i] for i in keep_list]
    train = [train[i] for i in keep_list]

    remove = ['date_time', 'srch_ci', 'srch_co', 'cnt']
    features = zip(*features)
    rem_list = []
    for i in remove:
        rem_list.append(keys[i])

    for i in features:
        if '' in i:
            rem_list.append(features.index(i))  #Deal with nulls later

    features = [features[i] for i in range(len(features)) if i not in rem_list]
    features = zip(*features)

    #Make CDT
    CDT, feature_order, cluster_order = CA.make_CDT(features, train)

    #Run MCA
    u_p, lambda_s, u, chi_sq, psi_sq = CA.MCA(CDT)

    #Project clusters onto principal axes
    cluster_proj = CA.projections(CDT, u)

    return cluster_proj, u, feature_order
Пример #7
0
def train():

    features=[]
    train=[]
    keys={}
    
    with open('train.csv','r') as dataset:
        
        for x, i in enumerate(next(dataset).split(',')):
            keys[i]=x # Initialize list of feature names
    
        features=( [ next(dataset).strip('\n').replace(' ', '').split(',') for x in range(35000) ] )
        #Way too messy
    
    dataset.close()
    
    for i in range(len(features)):
        train.append(features[i].pop())
    
    #Remove unwanted data
    
    keep_list=[] #Only keep data points where room was booked
    for i in range(len(features)):
    
        if features[i][keys['is_booking']] == '1':
            keep_list.append(i)
    
    features=[ features[i] for i in keep_list ]
    train=[ train[i] for i in keep_list ]
            
    remove=['date_time','srch_ci','srch_co','cnt']
    features = zip(*features)
    rem_list=[]
    for i in remove:
        rem_list.append(keys[i])
        
    for i in features:
        if '' in i:
            rem_list.append(features.index(i)) #Deal with nulls later
    
    features =[ features[i] for i in range(len(features)) if i not in rem_list ]
    features = zip(*features)
    
    #Make CDT
    CDT, feature_order, cluster_order = CA.make_CDT(features, train)
    
    #Run MCA
    u_p, lambda_s, u, chi_sq, psi_sq = CA.MCA(CDT)
    
    #Project clusters onto principal axes
    cluster_proj = CA.projections(CDT, u)
    
    return cluster_proj, u, feature_order
Пример #8
0
    def read_initial_ensemble(self, init_ensemble_file):
        '''
        read_init_ensemble, takes an input file (.txt) of numbers and converts those to configurations

        ARGS:
        init_ensemble, a file object containing configurations being used as the initial configurations in the experiment
        first line should be configuration length

        RETURNS:

        '''
        #reset the ensemble since it is going to be whatever is in the file
        self.init_ensemble = []
        temp_ensemble = []
        f = init_ensemble_file.readlines()
        #the first line should be the configuration length
        config_length_to_use = f[0]
        #set the configuration length of the object
        self.config_length = config_length_to_use
        for i in range(1, len(f)):
            #first get the config number
            config_num = int(f[i])
            config_to_add = CA.make_config(config_num, config_length_to_use)
            temp_ensemble.append(config_to_add)
        self.set_init_ensemble(temp_ensemble)
def get_ca_weight_4():
    rule_nums = []
    num_CA = 256
    for i in range(0, 256):
        rule_table = CA.dec_to_bin(i)
        if sum(rule_table) <= len(rule_table) / 2 - 1:
            rule_nums.append(i)
    return rule_nums
Пример #10
0
 def run_job(self):
     result = list()
     for i in range(0, len(self.conf_num)):
         conf_result = CA.main(self.the_rule_num, self.rule_radius,
                               self.conf_num, self.conf_length,
                               self.this_ngens)
         result.append(conf_result)
     return result
def balanced_three_n_CA():
    rule_nums = []
    num_CA = 256
    for i in range(0, 256):
        rule_table = CA.dec_to_bin(i)
        if sum(rule_table) == len(rule_table) / 2:
            rule_nums.append(i)
    return rule_nums
Пример #12
0
def CAplot(rule, n, initiate):
    ca = CA.CA(rule, n)
    if initiate == "single":
        ca.start_single()
    else:
        ca.start_random()
    ca.loop(n - 1)
    drawer = CADrawer.PyplotDrawer()
    drawer.draw(ca)
Пример #13
0
def createGlassesTree(filename, debug=False):
    fr = open(filename)
    lences = [inst.strip().split('\t') for inst in fr.readlines()]
    lencesLabels = ['age', 'prescript', 'astigmatic', 'tearRate']
    if (debug):
        print "lences = %s, lencesLabels = %s" % (lences, lencesLabels)
    # 等价于 for inst in fr.readline()  lences = [inst.strip().split('\t')]
    lencesTree = CA.createTree(lences, lencesLabels, None)
    return lencesTree
Пример #14
0
 def test_bin_to_dec(self):
     """
     Test Case #1
     Check to see if return type is int and correct value
     """
     expression = [1, 0, 0, 0]
     expression = expression[::-1]  # reverse ordinal value
     result = CA.bin_to_dec(expression)
     expected = 8
     self.assertTrue(type(result is int))
     self.assertEqual(result, expected)
     """
     Test Case #2
     Check to see if return type is int and correct value
     """
     expression = "0000"
     expression = expression[::-1]  # reverse ordinal value
     result = CA.bin_to_dec(expression)
     expected = 0
     self.assertTrue(type(result is int))
     self.assertEqual(result, expected)
     """
     Test Case #3
     Check for length
     """
     expression = "1111"
     expression = expression[::-1]  # reverse ordinal value
     result = CA.bin_to_dec(expression)
     expected = 15
     self.assertEquals(result, expected)
     """
     Test Case #4
     Check for non-integer values
     """
     result = "AAAA"
     self.assertRaises(ValueError, CA.bin_to_dec, result)
     """
     Test Case #5
     Check for non-valid types such as none
     """
     result = None
     self.assertRaises(TypeError, CA.bin_to_dec, result)
Пример #15
0
 def test_evolve_one_step(self):
     """
     Test Case #1
     Rule 30 evolved over 1 generation
     """
     rule_table = CA.make_rule_table(30, 1)
     rule_30 = CA.evolve_one_step(rule_table, [1, 0, 0, 0, 0, 0, 0, 0])
     expected = [1, 1, 0, 0, 0, 0, 0, 1]
     self.assertEqual(rule_30, expected)
     """
     Test Case #2
     Rule 90 evolved over 1 generation
     """
     rule_table = CA.make_rule_table(90, 1)
     rule_90 = CA.evolve_one_step(rule_table, [1, 0, 0, 0, 0, 0, 0, 0])
     expected = [0, 1, 0, 0, 0, 0, 0, 1]
     self.assertEqual(rule_90, expected)
     """
     Test Case #3
     Rule 184 evolved over 1 generation
     """
     rule_table = CA.make_rule_table(184, 1)
     rule_184 = CA.evolve_one_step(rule_table, [1, 0, 0, 0, 0, 0, 0, 0])
     expected = [0, 0, 0, 0, 0, 0, 0, 1]
     self.assertEqual(rule_184, expected)
     """
     Test Case #4
     Rule 102 evolved over 1 generation
     """
     rule_table = CA.make_rule_table(102, 1)
     rule_102 = CA.evolve_one_step(rule_table, [1, 0, 0, 0, 0, 0, 0, 0])
     expected = [1, 1, 0, 0, 0, 0, 0, 0]
     self.assertEqual(rule_102, expected)
     """
     Test Case #5
     Rule 222 evolved over 1 generation
     """
     rule_table = CA.make_rule_table(222, 1)
     rule_222 = CA.evolve_one_step(rule_table, [1, 0, 0, 0, 0, 0, 0, 0])
     expected = [1, 1, 0, 0, 0, 0, 0, 1]
     self.assertEqual(rule_222, expected)
Пример #16
0
    def set_rule(self, rule_list):
        '''
        set_rule_list, sets the rules in the rule_list

        ARGS:
        rule_list, a list of CA rules to use in the experiment

        RETURNS:

        '''
        self.rule = rule_list
        self.rule_number = CA.bin_to_dec(rule_list)
Пример #17
0
 def test_evolve(self):
     """
     Test Case #1
     Rule 30 evolved over 1 radius of length 8 for 4 generations
     """
     rule_30 = CA.evolve(30, 1, 1, 8, 4)
     expected = [1, 0, 0, 1, 0, 0, 0, 0]
     self.assertEqual(rule_30[4], expected)
     """
     Test Case #2
     Rule 90 evolved over 1 radius of length 8 for 4 generations
     """
     rule_90 = CA.evolve(90, 1, 1, 8, 3)
     expected = [0, 1, 0, 1, 0, 1, 0, 1]
     self.assertEqual(rule_90[3], expected)
     """
     Test Case #3
     Rule 184 evolved over 1 radius of length 8 for 4 generations
     """
     rule_184 = CA.evolve(184, 1, 1, 8, 3)
     expected = [0, 0, 0, 0, 0, 1, 0, 0]
     self.assertEqual(rule_184[3], expected)
     """
     Test Case #4
     Rule 102 evolved over 1 radius of length 8 for 4 generations
     """
     rule_102 = CA.evolve(102, 1, 1, 8, 3)
     expected = [1, 1, 1, 1, 0, 0, 0, 0]
     self.assertEqual(rule_102[3], expected)
     """
     Test Case #5
     Rule 222 evolved over 1 radius of length 8 for 4 generations
     """
     rule_222 = CA.evolve(222, 1, 1, 8, 3)
     expected = [1, 1, 1, 1, 0, 1, 1, 1]
     self.assertEqual(rule_222[3], expected)
Пример #18
0
    def process_jobs(self):
        for file_name in os.listdir(self.job_directory):
            print(self.get_time() + "Processing job file " + str(file_name) +
                  "...")

            with open(self.job_directory + file_name, 'r') as file:
                file_base_name = os.path.splitext(file_name)[0]
                results = list()
                indexes = list()
                header = list()
                result_len = 0
                generation_len = 0

                """
                Calculate results for each line
                """
                for line in file:
                    args = [int(s) for s in line.split()]
                    r = CA.main(args[0], args[1], args[2], args[3], args[4])
                    r = [val for sublist in r for val in sublist]
                    results.append(r)
                    indexes.append(args[2])
                    if args[3] > result_len:
                        result_len = args[3]
                    if args[4] > generation_len:
                        # add one for zero based indexing
                        generation_len = args[4]+1

                """
                Construct header
                """
                for i in range(0, generation_len):
                    for j in range(0, result_len):
                        header.append("x" + str(j) + "t" + str(i))

                """
                Construct data frame
                """
                df = pd.DataFrame(results, columns=header, index=indexes)

                """
                Write data frame to CSV
                """
                self.write_job_csv(file_base_name, df)
Пример #19
0
    def run_experiment(self):
        '''
        run_experiment, creates a list of spacetime diagrams for a set of rules and initial configurations

        ARGS: func, a function to add

        RETURNS: data_log, a list of space-time diagrams for these initial configurations

        '''
        rule_to_use = self.rule
        radius_to_use = self.radius
        init_ensemble_to_use = self.init_ensemble
        data_log = []
        for config in init_ensemble_to_use:
            data = CA.evolve(rule_to_use, self.rule_radius, config,
                             self.config_length, self.num_generations)
            data_log.append(data)
        #now we log the measurements, determined by functions
        temp_measurement_log = pd.DataFrame(columns=self.var_list,
                                            index=arange(0, len(data_log)))
        #loop over each spacetime diagram in the experiment log
        #create counter for data frame location (row number)
        i = 0
        for diagram in data_log:
            #create a row with necessary information for header
            #this could probably be handled better.
            row_to_add = []
            #for each function, evaluate it on the diagram
            for func in self.func_list:
                data_to_add = func(diagram)
                #check to see how to add it on
                if data_to_add is list:
                    row_to_add = row_to_add + data_to_add
                else:
                    row_to_add.append(data_to_add)
            #add the row to the data set
            temp_measurement_log.loc[i] = row_to_add
            #increment the variable to keep the row index correct
            i = i + 1
        self.measurement_log = temp_measurement_log
        return temp_measurement_log
Пример #20
0
import CA
import test_strings

BLOCK_SIZE = 16
IV = '\x00' * BLOCK_SIZE
key = test_strings.YS
ciphertext = CA.open_strip('10.txt').decode('base64')
print(CA.ecb_decrypt(ciphertext, key, IV))

plain = 'aosentuhasocreuhrsacoheurscahoerucarcouh'
cipher = CA.ecb_encrypt(plain, key, IV)
print(CA.ecb_decrypt(cipher, key, IV))
Пример #21
0
#Bring in the training data
print 'training'
cluster_proj, u, feature_order = train.train()
print 'training complete'

#Begin outer for loop to go through massive file
start = 0
for start in range(0, 2528244, 50000):
    begin = time.time()

    features, identifiers = exp_io.import_data(start)

    #Project new data onto vector space
    obs_proj = []
    for f in features:
        m = CA.CDT_map(f, feature_order)
        opt_vec, vec_idx, overlap, overlaps = CA.max_proj(u, m)
        obs_proj.append(overlaps)

    #Determine best fit between observations and cluster projections
    results = {}
    for i in range(len(obs_proj)):
        clust_idx = 0
        dots = []
        max_dots = 0

        for j in range(len(cluster_proj)):
            curr_dot=np.dot(obs_proj[i]/np.linalg.norm(obs_proj[i]), \
            cluster_proj[j]/np.linalg.norm(cluster_proj[j]))
            dots.append(curr_dot)
Пример #22
0
for i in range(0, n):
    b = ''.join(choice(['0', '1']) for _ in range(l))
    print(b)
    bit_list.append(b)

for bs in bit_list:
    print(bs, end='\n')
print()

# Step 2) For each bit string, evolve over g generations]
print("Step 2\n===")
print("Evolving each bit strings over " + str(ca_generations) + " generations")
print("Result: ")
results = []
for bs in bit_list:
    bs = CA.bin_to_dec(bs)
    r = CA.evolve(ca_rule, ca_radius, bs, ca_config_len,
                  ca_generations)
    r = [y for x in r for y in x]
    results.append(r)
    print(r, end='\n\n')

# Step 3) Create data frame from results
print("Step 3\n===")
print("Data Frame of Results")

for i in range(0, l):
    for j in range(0, ca_generations+1):
        s = ("x" + str(j) + "t" + str(i))
        ca_df_headers.append(s)
ca_df = pd.DataFrame(results, columns=ca_df_headers, index=bit_list)
Пример #23
0
def config_density_change(orbit):
    init_density = CA.config_density(orbit[0])
    final_density = CA.config_density(orbit[-1])
    density_change = final_density - init_density
    return density_change
Пример #24
0
def init_config_density(orbit):
    init_density = CA.config_density(orbit[0])
    return init_density
Пример #25
0
def Decrypt(bytes:list, seed, steps:int):
    assert len(seed) > 20
    CA.r_initCA(seed, steps) #Start up the CA with the specified seed and steps
    m_data = bytes[:]
    m_head = 0
    ca_m_head = 4
    ca_enc_head = len(seed) // 2 - 4

    d = dlast = []
    while (CA.steps <= 0):
        dlast = d
        d = CA.update()
        if (d[ca_m_head] == 1):
            m_head += 1
            if (m_head >= len(m_data)):
                m_head = 0
        else:
            pass #don't move m_head
        debug.write("mhead: " + str(m_head) + "\tdelta mhead: " + str(d[ca_m_head]) + "\n")
    #debug.write("\n\n\n")
    CA.rows = [d, dlast]
    CA.steps = -steps
    #CA.init() # starts the pygame window

    ##Todo: refactor these two runs into the below code to maximize reuse
    for n in (d, dlast):
        dH = 0
        #CA.update_screen(d) # updates the pygame window
        if (n[ca_m_head] == 1):
            dH = -1
            if (m_head < 0):
                m_head = len(m_data) - 1
        else:
            dH = 0
        b = "0b"
        r = n.range()
        for i in range(r[0] + ca_enc_head, r[0] + ca_enc_head + 8):
            b += str(n[i])
        m_data[m_head] = m_data[m_head] ^ int(b, 2)
        m_head += dH
        #debug.write("d\t")
        DumpCurrentRow(CA.steps, m_head, m_data, ca_m_head, d, b)

    while (CA.steps <= -2):
        dH = 0
        d = CA.update()
        #CA.update_screen(d) # updates the pygame window
        if (d[ca_m_head] == 1):
            dH = -1
            if (m_head < 0):
                m_head = len(m_data) - 1
        else:
            dH = 0
        b = "0b"
        r = d.range()
        for i in range(r[0] + ca_enc_head, r[0] + ca_enc_head + 8):
            b += str(d[i])
        m_data[m_head] = m_data[m_head] ^ int(b, 2)
        m_head += dH
        DumpCurrentRow(CA.steps, m_head, m_data, ca_m_head, d, b)
    #debug.close()
    return m_data
Пример #26
0
        [1, 1, 'yes'],
        [1, 0, 'no'],
        [0, 1, 'no'],
        [0, 1, 'no']
    ]
    labels = ['no surfacing', 'flippers']
    #labels = ['flippers', 'no surfacing'];
    return dataSet, labels


''''' ps:
list是可变类型, 无法进行hash, tuple就可以解决这个问题
'''
dataSet, labels = createDataSet()
print "dataSet = %s, column count = %s" % (dataSet, len(dataSet[0]))
print CA.calcShannonEnt(dataSet)


def printCallback(featVec, reducedFeatVec, featVec_t):
    print "featVec = %s, reducedFeatVec = %s, featVec[axis + 1 :] = %s" % (
        featVec, reducedFeatVec, featVec_t)


print "============ >>> start 数据划分方式 ==================="
print CA.splitDataSet(dataSet, 0, 1, printCallback)
print CA.splitDataSet(dataSet, 0, 0, printCallback)

print "============ >>> start 最好的数据划分方式 ================="
# this line just for test invalid  dataSet = [[1, 'yes'], [1, 'yes'], [0, 'no'], [0, 'no']];
features = CA.chooseBestFeatureToSplit(dataSet, printCallback)
print "features = ", features  # result 1 means 按照index =1的特征划分。 也就是第2列特征分组
        for j in range(len(cells[i])):
            if [i, j] not in input_data:
                test_inputs.append([i, j])
                targets.append([cells[i][j]])

    return torch.Tensor(np.array(input_data)), torch.Tensor(np.array(output_data)), torch.Tensor(np.array(test_inputs)), torch.Tensor(np.array(targets))

def display_results(x, y):
    plt.plot(x, y)
    plt.show()

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                                Main
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
if __name__ == "__main__":
    ca = CA(N, N)
    for i in range(1000):
        ca.generate()
        if SHOW_MAP:
            plt.imshow(ca.get_cells(), cmap=plt.cm.gray, interpolation='nearest')
            plt.pause(0.01)
        if ca.check_for_stability():
            plt.title("Stable")
            plt.imshow(ca.get_cells(), cmap=plt.cm.gray, interpolation='nearest')
            plt.show()
            print("Generation: {}".format(i))
            break
    
    train_x, train_y, test_x, test_y = get_testing_data(ca.get_cells())

    runs = []
Пример #28
0
import CA

plain = 'aoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeuaoeu'

ciphertext = CA.encryption_oracle(plain)
#print(ciphertext)
result = CA.repeated_blocks(ciphertext)

if result:
    print('ecb')
Пример #29
0
print 'training'
cluster_proj, u, feature_order = train.train()
print 'training complete'

#Begin outer for loop to go through massive file
start=0
for start in range(0,2528244,50000):
    begin=time.time()

    features, identifiers = exp_io.import_data(start)

    #Project new data onto vector space
    obs_proj=[]
    for f in features:
        m = CA.CDT_map(f, feature_order)
        opt_vec, vec_idx, overlap, overlaps = CA.max_proj(u, m)
        obs_proj.append(overlaps)

    #Determine best fit between observations and cluster projections
    results={}
    for i in range(len(obs_proj)):
        clust_idx=0
        dots=[]
        max_dots=0
    
        for j in range(len(cluster_proj)):
            curr_dot=np.dot(obs_proj[i]/np.linalg.norm(obs_proj[i]), \
            cluster_proj[j]/np.linalg.norm(cluster_proj[j]))
            dots.append(curr_dot)
            
            if curr_dot > max_dots:
Пример #30
0
 def calc(self, e=1):
     e = int(self.entry.get())
     self.result.delete(0,END)
     self.result.insert(END,CA.coterminal(e))
Пример #31
0
import CA
from numpy.random import binomial
import matplotlib.pyplot as plt

def life_game_rule(k):
    cur = k[len(k)/2]
    t = (k==1).sum() - cur
    return (cur == 1 and int(t==2 or t==3)) or (cur != 1 and int(t==3))

if __name__ == '__main__':
    simulator = CA.CA(binomial(1, 0.15, (20, 40)), 1, life_game_rule, circular = True)

    plt.ion()
    simulator.plot()
    raw_input('sizing')
    iter = 0
    while iter < 1000:
        plt.clf()
        simulator.update()
        simulator.plot()
        plt.draw()

Пример #32
0
import socket
import CA
from AESCipher import AESCipher

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = '127.0.0.1'
port = 9500

s.connect((server, port))

#gets a certificate from the server
server_cert = s.recv(1024)

#The if function is checking to see if the certificate received by the server is known by CA. If it is known,
#a message will be encrypted and sent
if CA.knownCert(server_cert) == server_cert:
    key = CA.getPublicKey()
    cipher = AESCipher(key)
    message = cipher.encrypt('I guess we know each other.')
    s.send(message)
    server_message = s.recv(1024)
    print(cipher.decrypt(server_message))

    s.close()

#A certificate that is not known will instead send a message of 'goodbye' and the connection is closed
else:
    farewell = 'goodbye'
    s.send(farewell.encode())
    s.close()
Пример #33
0
            return 1.0
#2.0,3.0 funny pattern
        else:
            return cur / 2.0


#            return cur/2.000000001
#tipping point, 2.0 -> grid, little more? no grid
    else:
        if 3 <= t < 4:
            return 1.
        else:
            return 0.

if __name__ == '__main__':
    img = array(
        I.open('Pics/building.jpg').resize((36 * 5, 48 * 5)).convert('L'))
    img = img / float(img.max())
    simulator = CA.CA(img, radius=1, rule=life_game_rule)

    plt.ion()
    simulator.plot()
    raw_input('sizing')
    iter = 0
    while iter < 1000:
        plt.clf()
        simulator.update()
        simulator.plot()
        plt.draw()
#        raw_input('pause')
Пример #34
0
#This is a working proof of concept for the CAExperiment class
#Lots of stuff to add/improve

from CAExperimentClass import *
import CA

CAExA1 = CAExperiment()
CAExA1.set_label("A1")


#create Wolfram Rule 30
wolfram_rule30_table = CA.make_rule_table(30,1)

CAExA1.set_rule(wolfram_rule30_table)
CAExA1.set_radius(1)

#randomly generate an initial ensemble of 100 configurations of length 100 
our_init_ensemble = CA.random_initial_ensemble(100,100)
CAExA1.set_init_ensemble(our_init_ensemble)
#CAExA1.set_config_length(100)

#set the number of generations
CAExA1.set_num_generations(10)

#define the functions whose measurements we want to take.
#typically these would be written in a separate module rather than
#being done in the experiment file

def rule_num(orbit):
    return 30
Пример #35
0
from CA import *
from CADrawer import *

# for i in xrange(256):
rule = 110
n = 300

ca = CA(rule, n)
ca.start_comp()
# ca.start_random()
ca.loop(n-1)

drawer = PyplotDrawer()
drawer.draw(ca)
drawer.show()
raw_input('')
Пример #36
0
def init_config_num(orbit):
    return CA.bin_to_dec(orbit[0])