Example #1
    def add_node(self, node=None, pos=None, ori=None, commRange=None):
        Add node to network.

          `node` -- node to add, default: new node is created
          `pos` -- position (x,y), default: random free position in environment
          `ori` -- orientation from 0 to 2*pi, default: random orientation

        if not node:
            node = Node(commRange=commRange)
        assert isinstance(node, Node)
        if not node.network:
            node.network = self
            logger.warning("Node is already in another network, can't add.")
            return None

        pos = pos if pos is not None else self.find_random_pos(n=100)
        ori = ori if ori is not None else rand() * 2 * pi
        ori = ori % (2 * pi)

        if self._environment.is_space(pos):
            Graph.add_node(self, node)
            self.pos[node] = array(pos)
            self.ori[node] = ori
            self.labels[node] = str(node.id)
            logger.debug("Node %d is placed on position %s." % (node.id, pos))
            logger.error("Given position is not free space.")
        return node
Example #2
 def remove_node(self, node):
     """ Remove node from network. """
     if node not in self.nodes():
         logger.error("Node not in network")
     Graph.remove_node(self, node)
     del self.pos[node]
     del self.labels[node]
     node.network = None
     logger.debug("Node with id %d is removed." % node.id)
Example #3
 def _are_conditions_satisfied(self, net):
     cr = net.nodes()[0].commRange
     if self.connected and not is_connected(net):
         logger.debug("Not connected")
         return round(0.2 * cr)
     elif self.degree:
         logger.debug("Degree not satisfied %f" % net.avg_degree())
         diff = self.degree - net.avg_degree()
         diff = sign(diff) * min(abs(diff), 7)
         return round((sign(diff) * (round(diff)) ** 2) * cr / 100)
     return 0
Example #4
    def __init__(self, network, **kwargs):
        self.network = network
        self.name = self.__class__.__name__
        logger.debug("Instance of %s class has been initialized." % self.name)

        for required_param in self.required_params:
            if required_param not in kwargs.keys():
                raise PymoteAlgorithmException("Missing required param.")

        # set default params
        for dp, val in self.default_params.items():
            self.__setattr__(dp, val)

        # override default params
        for kw, arg in kwargs.items():
            self.__setattr__(kw, arg)
Example #5
    def send(self, message):
        Send a message to nodes listed in message's destination field.

        Note: Destination should be a list of nodes or one node.

        Update message's source field and  inserts in node's outbox one copy
        of it for each destination.

        message.source = self
        if not isinstance(message.destination, collections.Iterable):
            message.destination = [message.destination]
        for destination in message.destination:
            logger.debug("Node %d sent message %s." % (self.id, message.__repr__()))
            m = message.copy()
            m.destination = destination
            self.outbox.insert(0, m)
Example #6
 def modify_avg_degree(self, value):
     Modifies (increases) average degree based on given value by
     modifying nodes commRange."""
     # assert all nodes have same commRange
     assert allclose([n.commRange for n in self], self.nodes()[0].commRange)
     # TODO: implement decreasing of degree, preserve connected network
     assert value + settings.DEG_ATOL > self.avg_degree()  # only increment
     step_factor = 7.0
     steps = [0]
     # TODO: while condition should call validate
     while not allclose(self.avg_degree(), value, atol=settings.DEG_ATOL):
         steps.append((value - self.avg_degree()) * step_factor)
         for node in self:
             node.commRange += steps[-1]
         # variable step_factor for step size for over/undershoot cases
         if len(steps) > 2 and sign(steps[-2]) != sign(steps[-1]):
             step_factor /= 2
     logger.debug("Modified degree to %f" % self.avg_degree())
Example #7
    def receive(self):
        Pop message from inbox but only if it has been there at least one step.

        Messages should be delayed for one step for visualization purposes.
        Messages are processed without delay only if they are pushed into empty
        inbox. So if inbox is empty when push_to_inbox is called _inboxDelay is
        set to True.

        This method is used only internally and is not supposed to be used
        inside algorithms.

        if self._inbox and not self._inboxDelay:
            message = self._inbox.pop()
            logger.debug("Node %d received message %s" % (self.id, message.__repr__()))
            message = None
        self._inboxDelay = False
        return message
Example #8
    def _create_modify_network(self, net=None, step=1):
        """Helper method for creating new or modifying given network.

            net (int):
                network to modify, if None create from scratch
                if >0 new network should be more dense for <0 less dense

        if net is None:
            net = Network(**self.kwargs)
            for _n in range(self.n_count):
                node = Node(commRange=self.comm_range, **self.kwargs)
            if step > 0:
                if len(net) < self.n_max:
                    node = Node(**self.kwargs)
                    logger.debug("Added node, number of nodes: %d" % len(net))
                elif not self.comm_range:
                    for node in net.nodes():
                        node.commRange += step
                    logger.debug("Increased commRange to %d" % node.commRange)
                    return None
                if len(net) > self.n_min and len(net) > 1:
                    logger.debug("Removed node, nodes left: %d" % len(net))
                elif not self.comm_range:
                    for node in net:
                        node.commRange += step
                    logger.debug("Decreased commRange to %d" % net.nodes()[0].commRange)
                    return None
        return net
Example #9
 def send(self, destination, message):
     logger.debug("Sending message from %s to %s." % (repr(message.source), destination))
     if destination in self.nodes():
         raise PymoteMessageUndeliverable("Destination not in network.", message)