Пример #1
0
def moore(graph, initial_partition, simple=False):
    iter_count = 0

    if simple:
        p = simplemoore(initial_partition, graph)
        return ps.PartitionSet(p)
    else:
        current_partition = initial_partition
        while True:
            new_partition = moore_iteration(graph, current_partition.partitions)
            iter_count += 1
            if len(current_partition.partitions) == len(new_partition):
                print('Moore finished with {} iterations'.format(iter_count))
                return ps.PartitionSet(new_partition)
            else:
                current_partition = ps.PartitionSet(new_partition)
Пример #2
0
def default_initial_partition(g):
    partitions = []
    already_in_partition = set()
    for s in g.states:
        s_edge_labels = set([oedge[0] for oedge in s.outedges])
        # print("Current state: {}\n\tOutedges: {}".format(s.name, s.outedges))#
        if not partitions:
            prt = pt.Partition(s)
            # print("\tCreating initial partition with s")#
            partitions.append(prt)
            already_in_partition.add(s)
        else:
            # Removed fail_count
            for p in partitions:
                # Solved bug with p.outedges (it was a list, so we must index position)
                p_edge_labels = set([oedge[0] for oedge in p.outedges[0]])
                # print("\tCurrent partition: {}\n\t\tOutedges: {}".format(p.name, p.outedges))#
                if (p_edge_labels == s_edge_labels):
                    # print("\t\t s added to partition")
                    p.add_to_partition(s)
                    already_in_partition.add(s)

            if s not in already_in_partition:
                # print("\t\tCreating new partition with s")
                prt = pt.Partition(s)
                partitions.append(prt)
                already_in_partition.add(s)

        # print()
        # print()
    return ps.PartitionSet(partitions)
Пример #3
0
def moore_by_parts(graph, initial_partition, n_iter = -1):
    #By default, it applies the regular moore algorithm
    if n_iter == -1:
        current_partition = moore(graph, initial_partition)
    elif n_iter == 0:
        return initial_partition
    else:
        current_partition = initial_partition.partitions
        for i in range(0, n_iter):
            current_partition = moore_iteration(graph, current_partition)
        current_partition = ps.PartitionSet(current_partition)
    return current_partition
Пример #4
0
with open(
        '../dcgram_files/ternary_even_shift/results/machines/dmarkov/dmark_D6.yaml',
        'r') as f:
    machine = yaml.load(f)

all_oedges = [state.outedges for state in machine.states]
morphs = []

for oedges in all_oedges:
    curr_morph = [0, 0, 0]
    for oedge in oedges:
        label = oedge[0]
        curr_morph[int(label)] = oedge[-1]
    morphs.append(curr_morph)

kmeans = k(n_clusters=3, random_state=0).fit(morphs)

clusters = [[] for i in range(kmeans.n_clusters)]
for i in range(len(morphs)):
    clusters[kmeans.labels_[i]].append(machine.states[i])
initial_pt = []

for p in clusters:
    partition = pt.Partition()
    for state in p:
        partition.add_to_partition(state)
    initial_pt.append(partition)

initial_pt = ps.PartitionSet(initial_pt, alphabet=['0', '1', '2'])
final_pt = m.moore_by_parts(machine, initial_pt, n_iter=3)
Пример #5
0
def clusterize(machine, L, D, K, moore_iter = -1, label_length = 1, machine_original = None, \
                name = 'ternary_even_shift', save_plot = True, version = 'v1'):
    all_oedges = [state.outedges for state in machine.states]
    morphs = []
    # define label for files if not default Moore's algorithm execution
    if moore_iter != -1:
        moore_label = '_moore_{}_iter'.format(moore_iter)
    else:
        moore_label = ''

    # Normalize morphs
    for oedges in all_oedges:
        curr_morph = [0] * len(machine.index_labels)
        for oedge in oedges:
            label = oedge[0]
            curr_morph[machine.index_labels[label]] = oedge[-1]
        morphs.append(curr_morph)
    # print('Morphs:\n{}'.format(morphs))
    centers = get_initial_centroids(morphs, K)
    closest_cluster, kmeans_centers = custom_kmeans(morphs, K, centers,
                                                    machine.state_prob)
    closest_cluster = [int(i) for i in closest_cluster]
    clusters = [[] for i in closest_cluster]
    for i in range(len(morphs)):
        clusters[closest_cluster[i]].append(morphs[i])
    if save_plot:
        idx = 0
        plot_label = ['bo', 'g*', 'c^', 'ms', 'yp', 'kh', 'rd', 'b>', 'r<'] * 5
        for c in clusters:
            plt.plot([x[0] for x in c], [y[1] for y in c],
                     plot_label[idx],
                     alpha=0.7)
            idx += 1

        plt.plot([x[0] for x in kmeans.cluster_centers_],
                 [y[1] for y in kmeans.cluster_centers_],
                 'r+',
                 markersize=15)
        plt.axis([-0.05, 1.05, -0.05, 1.05])
        # plt.title('Agrupamento de morphs para D = {}, K = {}'.format(D, K))
        plt.ylabel('$P(0)$')
        plt.xlabel('$P(1)$')
        plt.savefig(
            f'../dcgram_files/{name}_{version}/results/plots/kmeans_dmark_D{D}_K{K}_clusters{moore_label}_n{label_length}.png'
        )
        plt.gcf().clear()
    #----------------------------------------------------------------------------------
    #MOORE
    clusters = [[] for i in closest_cluster]
    # print(f"Clusterization check")
    for i in range(len(morphs)):
        cluster_index = closest_cluster[i]
        # print(f"\tCenter: {kmeans.cluster_centers_[state_idx]}, Outedge: {machine.states[i].outedges}")
        clusters[cluster_index].append(machine_original.states[i])
    # Fix empty clusters problem
    clusters = [c for c in clusters if c]
    # Split cluster if two or more states have differente outedges

    new_clusters = []

    for c in clusters:
        new_clusters_dict = dict()
        for st in c:
            key = ''.join([oedge[0] for oedge in st.outedges])
            if key in new_clusters_dict:
                new_clusters_dict[key].append(st)
            else:
                new_clusters_dict[key] = [st]
        for new_c in new_clusters_dict.values():
            new_clusters.append(new_c)

    initial_pt = []

    for p in new_clusters:
        partition = pt.Partition()
        for state in p:
            partition.add_to_partition(state)
        initial_pt.append(partition)

    initial_pt = ps.PartitionSet(initial_pt)

    with open(
            f'../dcgram_files/{name}_{version}/results/machines/dcgram/before_redefine/initial_D{D}_K{K}{moore_label}_n{label_length}.yaml',
            'w') as f:
        yaml.dump(initial_pt, f)

    final_pt = m.moore_by_parts(machine_original,
                                initial_pt,
                                n_iter=moore_iter)

    with open(
            f'../dcgram_files/{name}_{version}/results/machines/dcgram/before_redefine/dcgram_D{D}_K{K}{moore_label}_n{label_length}.yaml',
            'w') as f:
        yaml.dump(final_pt, f)
    new_pt = final_pt.redefine_partition(machine_original)

    with open(f'../dcgram_files/{name}_{version}/results/machines/dcgram/dcgram_D{D}_K{K}{moore_label}_n{label_length}.yaml'\
                , 'w') as f:
        yaml.dump(new_pt, f)

    return new_pt