Beispiel #1
0
    def instantiate_graph(self):
        graph = Graph()
        try:
            with open(self.__file_name) as f:
                for line in f:
                    # check if the line defines nodes or edges
                    if line[1] is ':':
                        nodes = line.split(' ')
                        for node in nodes:
                            name = node.split(':')[0]
                            x, y = node.split(':')[1].split(',')
                            graph.add_node(name.strip(), {
                                'X': x.strip(),
                                'Y': y.strip()
                            })
                    elif line[1] is ',':
                        edges = line.split(' ')
                        for edge in edges:
                            source = edge.split(',')[0]
                            destination, weight = edge.split(',')[1].split(':')
                            graph.add_edge(source.strip(), destination.strip(),
                                           weight.strip())
                    else:
                        raise SyntaxError("Unknown line type in %s" %
                                          (this.file_name))
        except Exception as e:
            raise e
        finally:
            f.close()

        return graph
Beispiel #2
0
def kMean(clusterNum):
    g = Graph(r"E:\ds2018")
    vocaDir = r"temp/vocabulary/"
    if not os.path.exists(vocaDir):
        os.makedirs(vocaDir)
    sift = SIFT()
    centers = []
    for i in range(g.getTypeNum()):
        print("[kmeans]:" + str(i))
        imgPaths = g.getTrainSet(i)
        features = np.float32([]).reshape((0, 128))
        for imgPath, type in imgPaths:
            imgMat = g.getGreyGraph(imgPath)
            if imgMat is None:
                print("[kmean]:" + imgPath + " is None")
                continue
            feature = sift.getFeature(imgMat)
            features = np.append(features, feature, axis=0)

        kmeans = KMeans(n_clusters=clusterNum).fit(features)
        filename = os.path.join(vocaDir, str(i) + ".npy")
        np.save(filename, kmeans.cluster_centers_)

        centers.append(kmeans.cluster_centers_)

    return centers
Beispiel #3
0
def loadVoca():
    g = Graph(r"E:\dataset")
    vocaDir = r"temp/vocabulary/"
    centers = []
    for i in range(g.getTypeNum()):
        filePath = os.path.join(vocaDir, str(i) + '.npy')
        _, center = np.load(filePath)
        centers.append(centers)

    return centers
Beispiel #4
0
def prepare_clusters(rfpath, wfpath):
    basic_net = load_data(rfpath)
    pid_dict = load_data(settings.PID_INDEX)
    pubs = load_json(settings.PUBS_JSON)
    components = {}
    for name, pairs in basic_net.items():
        pid_index = pid_dict[name]
        num_papers = len(pubs[name])
        G = Graph()
        G.add_nodes_from(range(num_papers))
        G.add_edges_from(pairs)
        C = Connectivity(G)
        components[name] = [list(map(pid_index.get(), compo)) for compo in C.connected_components().values()]
        print('prepare clusters', name, 'done')
    dump_data(components, wfpath)
Beispiel #5
0
    def getFeatVecForSvm(self, imgList, load=0):

        if load == 1:
            feats = np.load(r"temp/featVectHog.npy")
            return feats

        g = Graph(r"E:\ds2018")

        feats = np.float32([]).reshape((0, self.getVecLength()))
        for imgPath, type in imgList:
            mat = g.getGreyGraph(imgPath)
            if mat is None:
                continue
            feat = self.getFeature(mat)
            feats = np.append(feats, feat, axis=0)

        np.save(r"temp/featVectHog.npy", feats)
        return feats
Beispiel #6
0
    def calcVectorForSvm(self, imgList, n_cluster, load=0):
        if load == 1:
            types = np.load(r"temp/types.npy")
            featVec = np.load(r"temp/featVectSift.npy")
            centers = np.load(r"temp/centersSift.npy")
            return (types, featVec, centers)

        g = Graph(r"E:\ds2018")
        featMat = np.float32([]).reshape((0, 128))
        featList = []
        featVec = np.float32([]).reshape((0, n_cluster))
        types = np.float32([])
        i = 0
        for imgPath, type in imgList:
            print("[kmeans before]:" + str(i))
            i += 1
            mat = g.getGreyGraph(imgPath)
            if mat is None:
                continue
            feat = self.getFeature(mat)
            featList.append(feat)
            featMat = np.append(featMat, feat, axis=0)
            types = np.append(types, np.float32([type]))

        kmeans = KMeans(n_cluster)

        kmeans.fit(featMat)

        centers = kmeans.cluster_centers_

        i = 0
        for feature in featList:
            print("[kmeans after]:" + str(i))
            i += 1
            featVec = np.append(featVec,
                                self._calcFeatVec(feature, kmeans, n_cluster,
                                                  centers),
                                axis=0)

        np.save(r"temp/types.npy", types)
        np.save(r"temp/featVectSift.npy", featVec)
        np.save(r"temp/centersSift.npy", centers)

        return (types, featVec, centers)
Beispiel #7
0
    def getFeatVecForSvm(self, imgList, load=0):
        if load == 1:
            feats = np.load(r"temp/featVectLbp.npy")
            return feats

        g = Graph(r"E:\ds2018")
        feats = np.float32([]).reshape((0, self.getVecLength()))
        i = 0
        for imgPath, type in imgList:
            print("[lbp]:" + str(i))
            i += 1

            mat = g.getGreyGraph(imgPath)
            if mat is None:
                continue
            feat = self.getFeature(mat)
            feats = np.append(feats, feat.reshape((1, -1)), axis=0)

        np.save(r"temp/featVectLbp.npy", feats)
        return feats
Beispiel #8
0
from Graph.Graph import Graph
from Graph.exception import CantReach

graph = [[1, 2, -2], [1, 3, 4], [3, 2, 3], [3, 4, 1], [4, 3, 2], [5, 5, None]]

g = Graph(st=graph)
#print(g.fw_path(start = 4, end=3))
print('Інциденція:\n')
m = g.matrix_incidence()
for n, i in enumerate(m):
    print(n + 1, ":", i)

print('Суміжність:\n')
mm = g.matrix_adjacency()
for n, i in enumerate(mm):
    print(n + 1, ":", i)

hamilton = g.check_hamilton_cycle(1)
print("Без циклів" if hamilton is None else (
    "Цикл з вершини {} на шляху {}".format(hamilton[0], hamilton[1])))

print("Степені точок: ", g.get_nodes_power())
print("Ізольовані точки: ", g.get_isolated())
dejkstra_path = g.dejkstra_path(1, end=2)

bellman_ford_path = g.bf_path(1)
topological_sorted_list = g.topological_sort()

print(dejkstra_path)
print(bellman_ford_path)
print("Топологічне сортування: ", topological_sorted_list)
Beispiel #9
0
from sklearn import svm
from Graph.Graph import Graph
from Features.LBP import LBP
from sklearn.decomposition import PCA
import numpy as np

g = Graph(r"E:\ds2018")
if not g.isDivided():
    g.divideTrainTest("ds2018")

trainList = g.readTrainCSV()
features = np.float32([]).reshape(0, 128 * 128)
types = []
for imgPath, type in trainList:

    lbp = LBP([8], [1], "default")
    imgMatrix = g.getGreyGraph(imgPath)
    if imgMatrix is None:
        continue
    lbpFeatures = lbp.getFeature(imgMatrix)
    for j in lbpFeatures:
        print(features.shape)
        print(j.shape)
        np.append(features, j.reshape(1, 128 * 128), axis=0)
        types.append(type)

clf = svm.SVC(C=0.8, kernel='rbf', gamma=20, decision_function_shape='ovr')

clf.fit(features, types)
print("done")
Beispiel #10
0
import os
from openpyxl import load_workbook

from Cut.Cut import Cut
from Format.Format import Format
from Graph.Graph import Graph
from TimeModel.TimeModel import Timemodel

DATA_DIR = "C:\\Users\\User\\Google 雲端硬碟\\畢業專題\\漢翔\\src"
exe_file = []
plan_file = []

print("****File in " + DATA_DIR + "****")
for filename in os.listdir(DATA_DIR):
    print('     ' + filename)
    if filename.endswith("txt"):
        file = open(os.path.join(DATA_DIR, filename), 'r')
        exe_file.append(file)
    elif filename.endswith("xlsx"):
        file = load_workbook(os.path.join(DATA_DIR, filename))
        plan_file.append(file)
    else:
        print('!!!! ' + filename + ' is not available!!!!')

cut = Cut(exe_file, plan_file)
format = Format(cut.load_data, cut.plan_data)
graph = Graph(format.machine_name, format.execute_format)
timemodel = Timemodel(format.machine_name, format.match, format.execute_format,
                      format.plan_format, format.status_format)