Example #1
0
 def add_send_self_loops(self):
     if any([d['action'] == 'receive' for _, _, d in self.get_transitions()]):
         assert False, 'There should be no receive transitions!' 
     for state in self.automaton.nodes():
         for source, target, d in self.get_transitions():
             if d['action'] == 'send':
                 if paths.has_path(self.automaton, state, source):
                     if paths.has_path(self.automaton, target, state):
                         self.add_transition(state, state, d['symbol'], 'send')
def node_dep_ids_iter(
    g: nx.DiGraph,
    c: Optional[nx.DiGraph] = None
) -> Generator[Tuple[nxGraphNodeID, Set[nxGraphNodeID], Set[nxGraphNodeID]],
               None, None]:
    """For a directed graph with unique node IDs with type int and
    optional precomputed condensed DAG of g, iterates over sets of
    strongly connected components from outer / leafmost / least depended
    upon nodes to inner nodes.

    For each set of strongly connected components, yield each node by
    decreasing ID with its sets of immediate or direct dependencies
    (path length one) and transitive or indirect dependencies (path
    length greater than one).

    Properties:

    * yields each node ID once
    * successive node IDs only depend on/point to previously visited
    nodes or other nodes within their set?
    """
    if not c:
        c = condensation(g)

    for node_ids, indirect_node_ids in outer_in_graph_iter(g, c):
        for node_id in sorted(node_ids, reverse=True):
            direct_dep_ids: Set[int] = set(g.successors(node_id))
            indirect_dep_ids: Set[int] = (
                set([
                    dest_id for dest_id in node_ids if has_path(
                        g, node_id, dest_id)  # i.e. have a scc in common
                ])
                | indirect_node_ids) - direct_dep_ids - set([node_id])

            yield node_id, direct_dep_ids, indirect_dep_ids
def get_spot_prices_in_eth_from_dune(swaps, pool_ids, token_info, block_interval = 1):
    from_block = min(s['block_number'] for s in swaps)
    to_block = max(s['block_number'] for s in swaps)
    reserves = get_reserves_from_dune(from_block - 1, to_block, pool_ids, token_info)
    reserves = compute_reserves_for_blocks(range(from_block, to_block + 1), reserves)

    token_graph = Graph(list(reserves.keys()))

    for t1, t2 in reserves.keys():
        block = list(reserves[t1, t2].keys())[0]
        token_graph[t1][t2]['weight'] = -reserves[t1, t2][block][0] * reserves[t1, t2][block][1]
    WETH = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
    tokens = {t1 for (t1, _) in reserves.keys()} | {t2 for (_, t2) in reserves.keys()}
    tokens = {t for t in tokens if has_path(token_graph, t, WETH)}
    exchange_paths = {t: shortest_path(token_graph, t, WETH) for t in tokens}
    prices = {}
    for block in tqdm(range(from_block, to_block + 1, block_interval), "Setting spot prices for every block"):
        block_prices = {}
        for t in tokens:
            xrate = compute_exchange_rate(exchange_paths[t], reserves, block)
            if xrate is None:
                continue
            block_prices[t] = xrate
        prices[block] = block_prices
    return prices
Example #4
0
    def has_path(self, src_sid, dst_sid):
        dst = self.__resolve_sid_to_id(dst_sid)
        if dst is None:
            raise Exception('SID not found!')

        src = self.__resolve_sid_to_id(src_sid)
        if src is None:
            raise Exception('SID not found!')

        return has_path(self.graph, src, dst)
Example #5
0
def hasWon(G, player):
    '''
    Esta función devuelve un booleano para saber si el jugador ha
    ganado la partida.
    '''
    G = G.copy()
    G.remove_edges_from(
        [edge for edge in G.edges if 'possible_movement' in edge])
    all_possible_paths = (list(
        itertools.product(range(7), range(41, 49)) if player ==
        2 else list(itertools.product(range(0, 49, 7), range(6, 49, 7)))))
    return any([
        has_path(G, src, dest) for (src, dest) in all_possible_paths
        if (G.nodes[src]['player'] == player
            and G.nodes[dest]['player'] == player)
    ])
Example #6
0
    def paths(self, source, target):
        """return the paths, if any, from a given source node to a given target node

        Args:
            source (str): name of node which is starting point of path
            target (str): name of node which is end point of path

        Returns:
            list of list of nodes (in order) forming the paths, or None if no path

        """
        assert source in self.node_map
        assert target in self.node_map
        if has_path(self.G2, source, target):
            return nx.all_simple_paths(self.G2, source=source, target=target)
        return None
Example #7
0
    def upstream_nodes_of_type(self, target_node_name, operation_type):
        """get set of nodes of a given operation type (OperationType.reader, OperationType.writer etc)
            upstream of some given target node

        Args:
            operation_type (OperationType): OperationType

        Returns:
            set of keys, if any, of the given operation type

        """
        assert target_node_name in self.node_map
        nodes = self.nodes_of_type(operation_type)
        nodes = [
            node for node in nodes if has_path(self.G2, node, target_node_name)
        ]
        return set(nodes)
Example #8
0
 def compute_upper_bound(self):
     """
     We have to compute the new upper boundary (nub) starting from the
     root nodes.  If a path exists between a root node and another entry in
     `self.upper` we can ignore the root node because it has been
     specialized by one of its successors.
     """
     nub = set()
     for root in self.roots - self.upper:
         found = False
         for up in self.upper - self.roots:
             domain = self.get_domain()
             if has_path(domain, root, up):
                 found = True
                 break
         if not found:
             nub.add(root)
     return nub | (self.upper - self.roots)
Example #9
0
 def is_contradictory(self, other):
     """
     Does the merge yield the empty set? 
     """
     if not self.is_domain_equal(other):
         return True
     # what would happen if the two were combined? 
     test_lower = self.lower.union(other.lower)
     test_upper = self.upper.union(other.upper)
     # if there is a path from lower to upper nodes, we're in trouble:
     domain = self.get_domain()
     for low in test_lower:
         for high in test_upper:
             if low != high and has_path(domain, low, high):
                 return True
     # lastly, build a merged ordering and see if it has 0 members
     test = self.__class__()
     test.lower = test_lower
     test.upper = test_upper
     return len(test) == 0
Example #10
0
    def SfinDeVieAtteinte(_reseau, _intervalle_roulement):
        """
            Permet de déterminer si le réseau a atteint sa fin de vie. Un ratio du nombre de capteur relié au puit est
            utilisé.

        :param _reseau: Reseau, le réseau à traiter
        :param _intervalle_roulement : float, l'intervalle de temps entre chaque changement de rôle des capteurs
        :return:    boolean, vrai si la fin de vie du réseau a été atteinte
                    int[], liste des noeuds déconnectés
        """
        _log.Linfo("Début ## Simulateur.SfinDeVieAtteinte")

        from Modele.Reseau import Reseau
        if type(_reseau) is not Reseau:
            _log.Lerror("Valeur Argument errone _reseau")
            raise Exception("Valeur Argument errone _reseau")
        if type(_intervalle_roulement
                ) is not float and _intervalle_roulement < -1:
            _log.Lerror("Valeur Argument errone _intervalle_roulement")
            raise Exception("Valeur Argument errone _intervalle_roulement" +
                            str(_intervalle_roulement))

        # Pour chaque noeud, suivre la chaine de routage qui le lie au puit. Si la chaîne est brisée décompter ce noeud
        _noeuds_deconnectes = []
        _fin_de_vie_atteinte = False
        _puit = 0

        # On récupère une copie du réseau sans les noeuds vides puis on le configure topologiquement
        _reseau_sans_capteurs_vides, _noeuds_vides = Simulateur.SreseauSansCapteursVides(
            _reseau)
        _reseau_sans_capteurs_vides = Simulateur.SconfigurationTopologique(
            _reseau_sans_capteurs_vides)

        # Récupération du puit
        for _noeud in _reseau.R_graphe.nodes():
            if _reseau.R_graphe.node[_noeud]['role'] == Roles.PUIT:
                _puit = _noeud
                break

        # Pour tout les noeuds, on teste si le noeud est relié sinon dans le cas du premier cycle on descend de routage
        # en routage vers le puit
        for _noeud in _reseau.R_graphe.nodes():
            # Si on détecte une anomalie : le routage d'un noeud est lui-même, on déconnecte ce noeud
            if _noeud != _puit and _reseau.R_graphe.node[_noeud][
                    'route'] == _noeud:
                _noeuds_deconnectes.append(_noeud)
            # Si il n'y a pas de chemin possible vers le puit on déconnecte le noeud
            elif _noeud in _noeuds_vides or not has_path(
                    _reseau_sans_capteurs_vides.R_graphe, _noeud, _puit):
                _noeuds_deconnectes.append(_noeud)
            # Au premier tour on test si la route n'est pas brisée
            elif _intervalle_roulement == 0:
                # La récurisivité est utilisée pour descendre de routage en routage jusqu'au puit
                _, _noeuds_deconnectes = Simulateur.Sparcourt(
                    _noeud, _reseau, _noeuds_deconnectes)

        # On teste si la fin de vie a été atteinte en fonction du ratio de noeuds déconnecté toléré
        if len(_noeuds_deconnectes) / (_reseau.R_nbr_noeuds -
                                       1) >= Simulateur.S_fin_de_vie:
            _fin_de_vie_atteinte = True

        return _fin_de_vie_atteinte, _noeuds_deconnectes
Example #11
0
 def predicate_depends_on(self, predicate_name1, predicate_name2):
     return has_path(self.get_predicate_deps_graph(), predicate_name2,
                     predicate_name1)
Example #12
0
    def is_entailed_by(self, other):
        """
        Returns True iff Other 
        (a) has the same domain,
        (b) the same or more specific 'upper' bound; and 
        (c) the same or more general 'lower' bound. 
        
        Approach: Looks for ways to rule out entailment.  If none are found, 
        returns True
        """

        
        if not self.is_domain_equal(other):
            return False
        
        """        
        First we compare the similarity between upper bounds, 
         (1) if Self's upper bound is empty, Other's upper bound will always
            be as or more specific.
         (2) if Self's upper bound is a subset of Other's, Other will always
            be as or more specific.
            
         To prove the other has a more specific upper bound, we eliminate
            cases where it does not.  The first condition ensures the above
            two cases are not true.   Then, for each element in Other's upper
            bound (that is not in Self's),
            
         (3) if, for all elements in other's upper bound, we cannot find a member
           in the complete upper bound that is more general (has path from self[i]
           to other[j]), we return False, indicating Other does not entail
           Self.
        """
        domain = self.get_domain()
        self_full_upper = self.compute_upper_bound()
        if not (len(self.upper) == 0 \
             or other.upper.issuperset(self.upper)):
            for self_up in self_full_upper - other.upper:
                found = False
                # find a more specific member for each member
                # of self.upper that's not in other.upper
                for other_up in other.upper - self_full_upper:
                    if has_path(domain, self_up, other_up):
                        found = True
                        break
                if found:
                    break
                else:
                    return False  # none was found     
        """        
        Other must also share the same or more general 'lower' bound. 

         (3) if, for all elements in other's lower bound, we cannot find a member
           in the complete upper bound that is more general (has path from self[i]
           to other[j]), we stop.

        """
        if not (len(self.lower) == 0 \
            or self.lower.issubset(other.lower)):
            for self_lo in self.lower - other.lower:
                found = False
                for other_lo in other.lower - self.lower:
                    if has_path(domain, self_lo, other_lo):
                        found =True
                        break
                if found:
                    break
                else:
                    return False  # none was found
                    
        # if we got this far, we should have an entailment!
        return True
Example #13
0
            if graph.node[node]['data'].id == id3:
                num3 = graph.nodes().index(node)
    
    n1 = graph.node[graph.nodes()[num1]]
    n2  = graph.node[graph.nodes()[num2]]
    n3  = graph.node[graph.nodes()[num3]]

    """
    print "NUMBER OF NODES: ", len(graph.nodes())
    print "NUMBER OF EDGES: ", len(graph.edges())
    print "1:               ", n1['data'].id
    print "2:               ", n2['data'].id
    print "3:               ", n3['data'].id
    """

    if not (has_path(graph, n1['data'].id, n2['data'].id) and has_path(graph, n2['data'].id, n3['data'].id)):
        continue

    print "\n\n"
    print "UNIFORM_COST:"
    results1 = bfs_ucs(graph, State(n1, None), State(n2, None))
    results2 = bfs_ucs(graph, State(n2, None), State(n3, None))
    results3 = bfs_ucs(graph, State(n3, None), State(n1, None))

    cost = [results1['cost'], results2['cost'], results3['cost']]
    cost.remove(max(cost))
    cost = sum(cost)
    expanded = sum([results1['expanded'], results2['expanded'], results3['expanded']])
    print "Total Path Length: " + str(cost) + ", Expanded: " + str(expanded)
    
    with open('output_uc.txt', 'a') as the_file:
Example #14
0
import networkx as nx
from networkx.algorithms.shortest_paths.generic import has_path

b = lambda s: [] if "no" in s else [x[2:x.rindex(' ')] for x in s.split(', ')]
a = lambda s: ((l := (t := s.split(' contain '))[0])[:l.rindex(' ')], b(t[1]))
t = [a(r.strip()[:-1]) for r in open('i', 'r')]
g = {l: r for l, r in t}
h = {x for y in list(g.values()) for x in y} | set(g.keys())
graph = nx.DiGraph()
graph.add_nodes_from(h)
graph.add_edges_from([(a, b) for a in g.keys() for b in g[a]])
print(
    len([
        x for x in h if has_path(graph, x, 'shiny gold') and x != 'shiny gold'
    ]))