Ejemplo n.º 1
0
def trivector_cmd(id_vent: str,
                  neighbor_method: str,
                  radius: int,
                  threshold: float,
                  graph: str,
                  header=False):
    propagation = Propagation()
    # Setta i parametri
    if os.path.isfile("graph_gexf/" + graph):
        propagation.set_Graph(utility.load_graph(graph))
    else:
        print("Graph doesn't exist, default are loaded")
    propagation.set_trivector(threshold)
    id_vents = []
    propagation_method = "trivector"
    neighbor = ""
    if neighbor_method != None:
        if neighbor_method == "moore" or neighbor_method == "neumann":
            id_vents = utility.get_neighborhood(id_vent, neighbor_method,
                                                radius)
            neighbor += "_" + neighbor_method + str(radius)
        else:
            print("You must specify a valid neighbor method: moore / neumann.")
            return None
    else:
        id_vents = [id_vent]

    # Esecuzione algoritmo
    sparse_matrix = propagation.trivector(id_vents)
    # Esportazione in ASCII e calcolo metriche
    G = propagation.get_Graph()
    utility.visualize_and_metrics(id_vents, propagation_method, neighbor,
                                  sparse_matrix, G, header)
Ejemplo n.º 2
0
def get_tpr_list(G, vent_list):
    p = Propagation()
    p.set_Graph(G)

    tpr_list = []
    for vent in vent_list:
        sparse_matrix = p.trivector([vent])
        tpr = compute([vent], "", sparse_matrix, G)[2]
        tpr_list.append(tpr)

    return tpr_list
Ejemplo n.º 3
0
def get_ppv_list(G, vent_list):
    p = Propagation()
    p.set_Graph(G)

    ppv_list = []
    for vent in vent_list:
        sparse_matrix = p.trivector([vent])
        ppv = compute([vent], "", sparse_matrix, G)[0]
        ppv_list.append(ppv)

    return ppv_list
Ejemplo n.º 4
0
def test(id_vent, distance=4):
    propagation = Propagation()
    propagation.trivector([id_vent])
    G = propagation.get_Graph()

    # Conversione vent
    id_node = conversion.get_node_from_idvent(int(id_vent))

    # Estrazione sottografo
    for i in range(len(G.nodes)):
        if G.nodes[str(i)]['current_flow'] == 0:
            G.remove_node(str(i))

    # Cambio pesi
    for u, v, data in G.edges(data=True):
        if data['trasmittance'] == 0:
            G.edges[u, v]['trasmittance'] = math.inf
        else:
            G.edges[u, v]['trasmittance'] = -math.log(data['trasmittance'])

    # Lista nodi città
    city_nodes = []
    for n in G.nodes:
        if G.nodes[n]['priority'] > 0:
            city_nodes.append(n)

    # Shortest paths
    shortest_paths = {}
    for n in city_nodes:
        shortest_paths[n] = nx.shortest_path(G,
                                             id_node,
                                             n,
                                             weight='trasmittance')

    cutted_edges = {}
    for n in shortest_paths:
        path = shortest_paths[n]
        for i in range(distance, len(path) - distance):
            edge_id = (path[i - 1], path[i])
            if edge_id not in cutted_edges:
                propagation.set_Graph(utility.load_graph())
                propagation.cut_edges([[path[i - 1], path[i]]])
                sparse_matrix = propagation.trivector([id_vent])
                G = propagation.get_Graph()
                risk = metrics.compute([id_vent], 'trivector', sparse_matrix,
                                       G)[-1]
                cutted_edges[edge_id] = risk
                print(edge_id, risk)

    min_risk = min(cutted_edges, key=cutted_edges.get)
    print(min_risk)
Ejemplo n.º 5
0
def autocut_cmd(id_vent: str, distance: int, neighbor_method: str, radius: int,
                dimension: int, mode: str):
    propagation = Propagation()
    id_vents = []
    propagation_method = "trivector"
    neighbor = ""
    if neighbor_method != None:
        if neighbor_method == "moore" or neighbor_method == "neumann":
            id_vents = utility.get_neighborhood(id_vent, neighbor_method,
                                                radius)
            neighbor += "_" + neighbor_method + str(radius)
        else:
            print("You must specify a valid neighbor method: moore / neumann.")
            return None
    else:
        id_vents = [id_vent]

    # Esecuzione algoritmo prima di tagliare
    no_cutted_sparse = propagation.trivector(id_vents)
    G = propagation.get_Graph()
    # Decommentare se si vuole stampare le metriche del trivector senza taglio
    # utility.visualize_and_metrics(id_vents, propagation_method, no_cutted_sparse, G, False)

    # selezione degli archi da tagliare
    list_edges = ga.get_edges_to_cut(G, id_vents, distance, dimension, mode)

    propagation.set_Graph(utility.load_graph())
    # taglio archi selezionati
    propagation.cut_edges(list_edges)

    # esecuzione trivector dopo il taglio degli archi
    cutted_sparse = propagation.trivector(id_vents)
    G = propagation.get_Graph()
    utility.visualize_and_metrics(id_vents, propagation_method, neighbor,
                                  cutted_sparse, G, False)
    mc.ascii_barrier(id_vent, propagation_method + neighbor, list_edges)
Ejemplo n.º 6
0
class Immunological_solution:
    def __init__(self, id_nodes: list, edges: list, real_vect: list, max_age = 5):
        # Id node
        self.id_nodes = id_nodes
        # Lista dei pesi degli archi
        self.edges = np.array(edges)
        # Real vector
        self.real_vect = real_vect
        # Valore di fitness della soluzione
        self.fitness = 0
        # Età massima della soluzione
        self.max_age = max_age

        # Vita della soluzione
        self.age = np.random.randint(0, (2 * max_age) / 3)

        self.propagation = Propagation()

    def __fbeta_score(self, tri_vect, idx: int):
        tp, fp, tn, fn = 0, 0, 0, 0

        for i in range(0, len(self.real_vect[idx])):
            if tri_vect[i] > 0 and self.real_vect[idx][i] == 1:  # tp
                tp += 1
            if tri_vect[i] > 0 and self.real_vect[idx][i] == 0:  # fp
                fp += 1
            if tri_vect[i] == 0 and self.real_vect[idx][i] == 0:   # tn
                tn += 1
            if tri_vect[i] == 0 and self.real_vect[idx][i] == 1:   # fn 
                fn += 1

        ppv = tp / (tp + fp)
        tpr = tp / (tp + fn)
        # beta grande! 
        beta = 3
        fbeta_score = (1 + beta**2) * ppv * tpr / ((beta**2 * ppv) + tpr)
        return fbeta_score

    def __update_weights(self, edges_dict: dict):
        # Prendere il grafo
        G = self.propagation.get_Graph()
        # Aggiornare i pesi
        i = 0
        for u, v in edges_dict:
            G.edges[u, v]['prop_weight'] = float(self.edges[i])
            i += 1
        # Settare il grafo
        self.propagation.set_Graph(G)

    def compute_fitness(self, edges_dict: dict):
        # Aggiornare i pesi
        self.__update_weights(edges_dict)
        # Trivector
        fit_list = []
        for i in range(len(self.id_nodes)):
            tri_vect = self.propagation.trivector_train(self.id_nodes[i])
            # f_beta score
            fit_list.append(self.__fbeta_score(tri_vect, i))
        
        self.fitness = np.mean(fit_list)

    def hypermutation(self, rho):
        alpha = math.exp(-rho * self.fitness)
        number_of_mutation = math.floor((alpha * len(self.edges)))

        std = (1 - self.fitness) / 5
        for _ in range(number_of_mutation):
            r = np.random.randint(0, len(self.edges)-1)
            w = np.random.normal(self.edges[r], std)
            if w < 0:
                w = 0
            if w > 1:
                w = 1
            self.edges[r] = w

    def increment_age(self):
        self.age += 1

    def set_random_age(self):
        self.age = np.random.randint(0, (2 * self.max_age) / 3)

    def set_fitness(self, fitness):
        self.fitness = fitness