Exemplo n.º 1
0
    def __init__(self, serialport=None):

        # store params
        self.serialport = serialport

        # local variables
        self.framelength = 0
        self.busyReceiving = False
        self.inputBuf = ''
        self.dataLock = threading.Lock()
        self.rxByte = 0
        self.prevByte = 0

        # flag to permit exit from read loop
        self.goOn = True

        self.parser_data = ParserData()

        self.routing_instance = Routing()

        # initialize the parent class
        threading.Thread.__init__(self)

        # give this thread a name
        self.name = 'moteProbe@' + self.serialport

        try:
            self.serial = serial.Serial(self.serialport, '115200', timeout=1)
        except Exception as err:
            print err

        # start myself
        self.start()
        print "serial thread: " + self.name + " started successfully"
Exemplo n.º 2
0
def algorithm(instance):
    valid = False
    while not valid:
        initSchedule = ScheduleMaker(instance)
        routing = Routing(instance)
        for day, scheduleDay in initSchedule.schedule.scheduleDays.items():
            cw = ClarkeWright(instance, scheduleDay)
            routing.addRoutingDay(day, cw.routingDay)
        valid = routing.isValid()
    return TwoOpt(instance, routing).routing
Exemplo n.º 3
0
    def query_routing(self, routeType, start_coord, end_coord):
        from Routing import Routing
        ro = Routing(routeType)
        ret = ro.findRoute(start_coord, end_coord)
        self.mc.clear()
        if ret[0] == 'success':
            self.mc.add_root_point(tuple(start_coord))
            self.mc.add_root_point(tuple(end_coord))
            self.mc.add_target_line([(nd[1][0] / DistanceUtils.coord_scale,
                                      nd[1][1] / DistanceUtils.coord_scale)
                                     for nd in ret[2]])

        self.mc.convert(qname=sys._getframe().f_code.co_name)
        # self.mc.save(WORK_DIR+"MapConverter.dump")
        return ret
Exemplo n.º 4
0
    def __init__(self, serialport=None):

        # store params
        self.serialport = serialport

        # local variables
        self.framelength = 0
        self.busyReceiving = False
        self.inputBuf = ''
        self.dataLock = threading.Lock()
        self.rxByte = 0
        self.prevByte = 0
        self.prev_packet_time = 0
        self.latency = [
            0.0, 0.0
        ]  #Here first element represents prev_latency, and second element represents sample count used to calculate the average latency
        self.prev_pkt = None
        self.rframe_latency = 0

        # flag to permit exit from read loop
        self.goOn = True

        self.parser_data = ParserData()

        self.routing_instance = Routing()

        # initialize the parent class
        threading.Thread.__init__(self)

        # give this thread a name
        self.name = 'moteProbe@' + self.serialport

        try:
            self.serial = serial.Serial(self.serialport, '115200')
        except Exception as err:
            print err

        # start myself
        self.start()
        print "serial thread: " + self.name + " started successfully"
Exemplo n.º 5
0
class moteProbe(threading.Thread):
    def __init__(self, serialport=None):

        # store params
        self.serialport = serialport

        # local variables
        self.framelength = 0
        self.busyReceiving = False
        self.inputBuf = ''
        self.dataLock = threading.Lock()
        self.rxByte = 0
        self.prevByte = 0

        # flag to permit exit from read loop
        self.goOn = True

        self.parser_data = ParserData()

        self.routing_instance = Routing()

        # initialize the parent class
        threading.Thread.__init__(self)

        # give this thread a name
        self.name = 'moteProbe@' + self.serialport

        try:
            self.serial = serial.Serial(self.serialport, '115200', timeout=1)
        except Exception as err:
            print err

        # start myself
        self.start()
        print "serial thread: " + self.name + " started successfully"
        #======================== thread ==========================================

    def run(self):
        while self.goOn:  # read bytes from serial port
            #Sending commands to mote
            #Here I am using global variables
            global outputBuf
            global outputBufLock
            if (len(outputBuf) > 0) and not outputBufLock:
                self.serial.write(outputBuf)
                #print ':'.join('{:02x}'.format(x) for x in outputBuf)
                outputBuf = ''

            try:
                self.rxByte = self.serial.read(1)
                if not self.rxByte:
                    continue
                elif (int(binascii.hexlify(self.rxByte), 16)
                      == 0x7e) and not self.busyReceiving:
                    self.busyReceiving = True
                    self.prevByte = self.rxByte
                    continue
            except Exception as err:
                print err
                time.sleep(1)
                break
            else:
                if self.busyReceiving and (int(binascii.hexlify(self.prevByte),
                                               16) == 0x7e):
                    #Converting string to integer to make comparison easier
                    self.framelength = int(binascii.hexlify(self.rxByte), 16)
                    self.inputBuf += self.rxByte
                    self.prevByte = self.rxByte
                    continue
                else:
                    self.inputBuf += self.rxByte
                    if len(self.inputBuf) == self.framelength:
                        self.busyReceiving = False
                        self._process_inputbuf()

    def _process_inputbuf(self):
        if self.inputBuf[1].upper() == 'P':
            print "This is a packet"
            print ":".join("{:02x}".format(ord(c)) for c in self.inputBuf[2:])
            data = [int(binascii.hexlify(x), 16) for x in self.inputBuf]
            data_tuple = self.parser_data.parseInput(data[2:])
            global isDAOReceived
            isDAOReceived = self.routing_instance.meshToLbr_notify(data_tuple)
            #print packet_ipv6['next_header']
        elif self.inputBuf[1] == 'D':
            print "This is debug message"
            print ":".join("{:02x}".format(ord(c)) for c in self.inputBuf[2:])
        elif self.inputBuf[1] == 'R':
            print "This is a command response"
            print ":".join("{:02x}".format(ord(c)) for c in self.inputBuf[2:])
        self.inputBuf = ''

    def _process_packet(self, packet):
        print "process_packet_func"

    def _fill_outputbuf(self):
        #When user wants to send some data, data will be pushed to this buffer
        print __name__

    def close(self):
        self.goOn = False
Exemplo n.º 6
0
 def __init__(self):
     self.routing_obj = Routing()
     self.routing_obj.set_family("inet6")
     self.route_cache = []
Exemplo n.º 7
0
class RouteCache(object):
    routing_obj = None
    route_cache = []

    def __init__(self):
        self.routing_obj = Routing()
        self.routing_obj.set_family("inet6")
        self.route_cache = []

    def remove_route(self, route):
        """Remove a route from the route cache"""
        if route not in self.route_cache:
            return False

        target, nexthop, nexthop_iface = route.to_tuple()

        logger.debug("Remove route to %s through %s on iface %s" % (target, nexthop, nexthop_iface))

        self.routing_obj.remove(target, (nexthop, nexthop_iface), table="local")
        self.route_cache.remove(route)
        return True


    def remove_routes(self, routes):
        """Remove a list of routes from the route cache"""
        route_update = False
        for route in routes:
            route_update += self.remove_route(route)
        return bool(route_update)


    def lookup_nexthop(self, nexthop, target=None):
        """Lookup a next hop in the route cache.
        The point is to make it easier to remove routes going through a specific router"""
        if target:
            return [route for route in self.route_cache if route.nexthop == nexthop and route.target == target]
        else:
            return [route for route in self.route_cache if route.nexthop == nexthop]


    def remove_nexthop(self, nexthop, target=None):
        route_update = False
        for route in self.lookup_nexthop(nexthop, target):
            route_update += self.remove_route(route)
        return bool(route_update)


    def add_route(self, route):
        """add a route to a target through a next hop"""

        if route in self.route_cache:
            return False

        (target, nexthop, nexthop_iface) = route.to_tuple()

        logger.debug("Add route to %s through %s on iface %s" % (target, nexthop, nexthop_iface))

        # sanity check: do not add a route to an address that is assigned on
        # the node
        assert target == "default" or not gv.address_cache.is_assigned(target.split("/")[0])

        try:
            self.routing_obj.add(target, (nexthop, nexthop_iface), table="local")
        except: pass

        self.route_cache.append(route)
        return True


    def add_routes(self, routes):
        """Add a list of routes to the route cache"""
        route_update = False
        for route in routes:
            route_update += self.add_route(route)
        return bool(route_update)


    def empty_cache(self):
        """Empty the route cache"""
        for route in copy(self.route_cache):
            self.remove_route(route)

        assert self.route_cache == []


    def __str__(self):
        """Print the complete route cache"""
        return self.routing_obj.__str__()
Exemplo n.º 8
0
 def __init__(self):
     self.routing_obj = Routing()
     self.routing_obj.set_family("inet6")
     self.route_cache = []
Exemplo n.º 9
0
class RouteCache(object):
    routing_obj = None
    route_cache = []

    def __init__(self):
        self.routing_obj = Routing()
        self.routing_obj.set_family("inet6")
        self.route_cache = []

    def remove_route(self, route):
        """Remove a route from the route cache"""
        if route not in self.route_cache:
            return False

        target, nexthop, nexthop_iface = route.to_tuple()

        logger.debug("Remove route to %s through %s on iface %s" %
                     (target, nexthop, nexthop_iface))

        self.routing_obj.remove(target, (nexthop, nexthop_iface),
                                table="local")
        self.route_cache.remove(route)
        return True

    def remove_routes(self, routes):
        """Remove a list of routes from the route cache"""
        route_update = False
        for route in routes:
            route_update += self.remove_route(route)
        return bool(route_update)

    def lookup_nexthop(self, nexthop, target=None):
        """Lookup a next hop in the route cache.
        The point is to make it easier to remove routes going through a specific router"""
        if target:
            return [
                route for route in self.route_cache
                if route.nexthop == nexthop and route.target == target
            ]
        else:
            return [
                route for route in self.route_cache if route.nexthop == nexthop
            ]

    def remove_nexthop(self, nexthop, target=None):
        route_update = False
        for route in self.lookup_nexthop(nexthop, target):
            route_update += self.remove_route(route)
        return bool(route_update)

    def add_route(self, route):
        """add a route to a target through a next hop"""

        if route in self.route_cache:
            return False

        (target, nexthop, nexthop_iface) = route.to_tuple()

        logger.debug("Add route to %s through %s on iface %s" %
                     (target, nexthop, nexthop_iface))

        # sanity check: do not add a route to an address that is assigned on
        # the node
        assert target == "default" or not gv.address_cache.is_assigned(
            target.split("/")[0])

        try:
            self.routing_obj.add(target, (nexthop, nexthop_iface),
                                 table="local")
        except:
            pass

        self.route_cache.append(route)
        return True

    def add_routes(self, routes):
        """Add a list of routes to the route cache"""
        route_update = False
        for route in routes:
            route_update += self.add_route(route)
        return bool(route_update)

    def empty_cache(self):
        """Empty the route cache"""
        for route in copy(self.route_cache):
            self.remove_route(route)

        assert self.route_cache == []

    def __str__(self):
        """Print the complete route cache"""
        return self.routing_obj.__str__()
Exemplo n.º 10
0
 def __init__(self, host):
     Routing.__init__(self, host)
Exemplo n.º 11
0
 def __init__(self, host):
     Routing.__init__(self, host)
Exemplo n.º 12
0
 def __init__(self, host):
     """initialize NLSR
        advertised: [prefix]"""
     Routing.__init__(self, host)
     self.isStarted = False
     atexit.register(self.stop)
Exemplo n.º 13
0
 def __init__(self, host):
     Routing.__init__(self, host)
     self.net = None
Exemplo n.º 14
0
class moteProbe(threading.Thread):
    def __init__(self, serialport=None):

        # store params
        self.serialport = serialport

        # local variables
        self.framelength = 0
        self.busyReceiving = False
        self.inputBuf = ''
        self.dataLock = threading.Lock()
        self.rxByte = 0
        self.prevByte = 0
        self.prev_packet_time = 0
        self.latency = [
            0.0, 0.0
        ]  #Here first element represents prev_latency, and second element represents sample count used to calculate the average latency
        self.prev_pkt = None
        self.rframe_latency = 0

        # flag to permit exit from read loop
        self.goOn = True

        self.parser_data = ParserData()

        self.routing_instance = Routing()

        # initialize the parent class
        threading.Thread.__init__(self)

        # give this thread a name
        self.name = 'moteProbe@' + self.serialport

        try:
            self.serial = serial.Serial(self.serialport, '115200')
        except Exception as err:
            print err

        # start myself
        self.start()
        print "serial thread: " + self.name + " started successfully"
        #======================== thread ==========================================

    def run(self):
        while self.goOn:  # read bytes from serial port

            try:
                self.rxByte = self.serial.read(1)
                if not self.rxByte:
                    continue
                #print binascii.hexlify(self.rxByte)
                if (int(binascii.hexlify(self.rxByte), 16)
                        == 0x7e) and not self.busyReceiving:
                    self.busyReceiving = True
                    self.prevByte = self.rxByte
                    continue
            except Exception as err:
                print err
                break
            else:
                if self.busyReceiving and (int(binascii.hexlify(self.prevByte),
                                               16) == 0x7e):
                    #Converting string to integer to make comparison easier
                    self.framelength = int(binascii.hexlify(self.rxByte), 16)
                    self.inputBuf += self.rxByte
                    self.prevByte = self.rxByte
                    continue
                else:
                    self.inputBuf += self.rxByte
                    if len(self.inputBuf) >= self.framelength:
                        self.busyReceiving = False
                        self._process_inputbuf()

    def _process_inputbuf(self):
        if self.inputBuf[1].upper() == 'P':
            print "received packet: " + ":".join("{:02x}".format(ord(c))
                                                 for c in self.inputBuf)
            data = [int(binascii.hexlify(x), 16) for x in self.inputBuf]
            data_tuple = self.parser_data.parseInput(data[2:])
            (result, data) = self.routing_instance.meshToLbr_notify(data_tuple)
            #Added by Nico for error handling
            if data == None and not result:
                self.inputBuf = ''
                print "No correct packet!"
                return
            if not result:
                if self.prev_pkt == data[4:]:
                    print "Duplicate packet"
                    self.inputBuf = ''
                    return
                curr_packet_time = int(round(time.time() * 1000))
                print "received data: " + ':'.join(
                    str(hex(i))
                    for i in data[4:]) + " , Packet Latency: " + str(
                        curr_packet_time - self.prev_packet_time)
                print "received data len : " + str(len(data[4:]))
                x = curr_packet_time - self.prev_packet_time
                self.latency[1] = self.latency[1] + 1.0
                if self.latency[1] > 1.0:
                    x = curr_packet_time - self.prev_packet_time
                    self.running_mean(x)
                    print "average latency: " + str(self.latency[0])
                self.prev_packet_time = curr_packet_time
                self.prev_pkt = data[4:]
        elif self.inputBuf[1] == 'D':
            print "debug msg: " + ":".join("{:02x}".format(ord(c))
                                           for c in self.inputBuf[2:])
            measured_data.append(int(binascii.hexlify(self.inputBuf[2]), 16))
            #if(len(measured_data[str(payload_length)]) == 50):
            #if(len(measured_data) == 50):
            #print(json.dumps(measured_data))
            #f = open('measurement_radio_rcv_to_nxt_slot_127.json','w')
            #f.write(json.dumps(measured_data))
            #f.close()
            #payload_length = -1
            #self.close()

        elif self.inputBuf[1] == 'A':
            print "output message: " + ":".join("{:02x}".format(ord(c) - 48)
                                                for c in self.inputBuf[2:])
            # added by Ayca to print out direct numbers / works differently with letters

        elif self.inputBuf[1] == 'R':
            print "command response: " + ":".join("{:02x}".format(ord(c))
                                                  for c in self.inputBuf[2:])
            response1 = "".join("{:02x}".format(ord(c))
                                for c in self.inputBuf[2:])
            #added by Nico to make the output human readable
            hilf = response1.split(":")
            responseArrayCheck = "".join(hilf)
            # Added by Nico to make the responses human-readable
            if responseArrayCheck[2:4] == "04":
                if len(responseArrayCheck) == 18:
                    print "" + responseArrayCheck[4:6] + " TX , " + responseArrayCheck[
                        6:8] + " RX , " + responseArrayCheck[
                            8:10] + " TXRX (Beacon) , " + responseArrayCheck[
                                10:12] + " SRX , " + responseArrayCheck[
                                    12:
                                    14] + " empty slots " + responseArrayCheck[
                                        14:
                                        16] + " MACRes slots " + responseArrayCheck[
                                            16:18] + " MACInit slots "
                elif len(responseArrayCheck) == 8:
                    print "Channel: " + responseArrayCheck[
                        4:6] + " Sent packets: " + responseArrayCheck[6:8]
                else:
                    print " Slottyp: " + responseArrayCheck[
                        4:6] + " ChannelOffset: " + responseArrayCheck[
                            6:8] + " NumRX: " + responseArrayCheck[
                                8:10] + " NumTX: " + responseArrayCheck[
                                    10:12] + " NumTxAck: " + responseArrayCheck[
                                        12:
                                        14] + " SlotOffset: " + responseArrayCheck[
                                            14:16]
            elif responseArrayCheck[2:4] == "0b":
                if responseArrayCheck[4:6] == "01":
                    print "Measurement is now disabled!"
                elif responseArrayCheck[4:6] == "02":
                    print "Measurement is now enabled!"
            elif responseArrayCheck[2:4] == "09":
                #Now Saving the result in a file
                global seperation
                if seperation == 0:
                    file = open("measurementNicoChannel.txt", "w")
                    file.write(responseArrayCheck[4:])
                    file.close
                    seperation = 1
                elif seperation == 1:
                    file = open("measurementNicoTimes.txt", "w")
                    file.write(responseArrayCheck[4:])
                    file.close
                    seperation = 2
                elif seperation == 2:
                    file = open("measurementNicoOffsets.txt", "w")
                    file.write(responseArrayCheck[4:])
                    file.close
                    seperation = 3
                elif seperation == 3:
                    print "Times sent in INIT or RESOLUTION slots: ", responseArrayCheck[
                        4:
                        6], "Times sent in RESOLUTION slots: ", responseArrayCheck[
                            6:8]
                    seperation = 0
            elif responseArrayCheck[2:4] == "45":
                file = open("measurementNicoEnhancedDAGroot.txt", "a")
                file.write(responseArrayCheck[4:])
                file.write("\n")
                file.close
        elif self.inputBuf[1] == 'E':
            print "------------------------------------------------------------------------"
            print "error msg: " + ":".join("{:02x}".format(ord(c))
                                           for c in self.inputBuf[2:])
            print "------------------------------------------------------------------------"
        elif self.inputBuf[1] == 'S':
            #Sending commands to mote
            #Here I am using global variables
            #curr_packet_time = int(round(time.time() * 1000))
            #print "request frame: " + str(curr_packet_time-self.rframe_latency)
            #self.rframe_latency  =  curr_packet_time
            global outputBuf
            global outputBufLock
            #global latency
            if (len(outputBuf) > 0) and not outputBufLock:
                outputBufLock = True
                dataToWrite = outputBuf.pop(0)
                outputBufLock = False
                #print int(round(time.time() * 1000)) - latency
                self.serial.write(dataToWrite)
                #print len(dataToWrite)
                print "injecting: " + ":".join("{:02x}".format(ord(c))
                                               for c in dataToWrite)
        self.inputBuf = ''

    def _process_packet(self, packet):
        print "process_packet_func"

    def _fill_outputbuf(self):
        #When user wants to send some data, data will be pushed to this buffer
        print __name__

    def close(self):
        self.goOn = False

    def prepare_UDP_packet(self, payload):
        print "prepare_UDP_packet"

        #Running mean implementation by storing only one element, and sample count
    def running_mean(self, x):
        #I have used 300 to make sure that first outlier is rejected, while calculating the average
        tmp = self.latency[0] * max(self.latency[1] - 1, 1) + x
        self.latency[0] = tmp / self.latency[1]
Exemplo n.º 15
0
class moteProbe(threading.Thread):
    def __init__(self, serialport=None):

        # store params
        self.serialport = serialport

        # local variables
        self.framelength = 0
        self.busyReceiving = False
        self.inputBuf = ''
        self.dataLock = threading.Lock()
        self.rxByte = 0
        self.prevByte = 0
        self.prev_packet_time = 0
        self.latency = [
            0.0, 0.0
        ]  #Here first element represents prev_latency, and second element represents sample count used to calculate the average latency
        self.prev_pkt = None
        self.rframe_latency = 0

        # flag to permit exit from read loop
        self.goOn = True

        self.parser_data = ParserData()

        self.routing_instance = Routing()

        # initialize the parent class
        threading.Thread.__init__(self)

        # give this thread a name
        self.name = 'moteProbe@' + self.serialport

        try:
            self.serial = serial.Serial(self.serialport, '115200')
        except Exception as err:
            print err

        # start myself
        self.start()
        print "serial thread: " + self.name + " started successfully"
        #======================== thread ==========================================

    def run(self):
        while self.goOn:  # read bytes from serial port

            try:
                self.rxByte = self.serial.read(1)
                if not self.rxByte:
                    continue
                #print binascii.hexlify(self.rxByte)
                if (int(binascii.hexlify(self.rxByte), 16)
                        == 0x7e) and not self.busyReceiving:
                    self.busyReceiving = True
                    self.prevByte = self.rxByte
                    continue
            except Exception as err:
                print err
                break
            else:
                if self.busyReceiving and (int(binascii.hexlify(self.prevByte),
                                               16) == 0x7e):
                    #Converting string to integer to make comparison easier
                    self.framelength = int(binascii.hexlify(self.rxByte), 16)
                    self.inputBuf += self.rxByte
                    self.prevByte = self.rxByte
                    continue
                else:
                    self.inputBuf += self.rxByte
                    if len(self.inputBuf) >= self.framelength:
                        self.busyReceiving = False
                        self._process_inputbuf()

    def _process_inputbuf(self):
        if self.inputBuf[1].upper() == 'P':
            print "received packet: " + ":".join("{:02x}".format(ord(c))
                                                 for c in self.inputBuf)
            data = [int(binascii.hexlify(x), 16) for x in self.inputBuf]
            data_tuple = self.parser_data.parseInput(data[2:])
            (result, data) = self.routing_instance.meshToLbr_notify(data_tuple)
            if not result:
                if self.prev_pkt == data[4:]:
                    print "Duplicate packet"
                    self.inputBuf = ''
                    return
                curr_packet_time = int(round(time.time() * 1000))
                print "received data: " + ':'.join(
                    str(hex(i))
                    for i in data[4:]) + " , Packet Latency: " + str(
                        curr_packet_time - self.prev_packet_time)
                print "received data len : " + str(len(data[4:]))
                x = curr_packet_time - self.prev_packet_time
                self.latency[1] = self.latency[1] + 1.0
                if self.latency[1] > 1.0:
                    x = curr_packet_time - self.prev_packet_time
                    self.running_mean(x)
                    print "average latency: " + str(self.latency[0])
                self.prev_packet_time = curr_packet_time
                self.prev_pkt = data[4:]
        elif self.inputBuf[1] == 'D':
            print "debug msg: " + ":".join("{:02x}".format(ord(c))
                                           for c in self.inputBuf[2:])
            measured_data.append(int(binascii.hexlify(self.inputBuf[2]), 16))
            #if(len(measured_data[str(payload_length)]) == 50):
            if (len(measured_data) == 50):
                print(json.dumps(measured_data))
                f = open('measurement_radio_rcv_to_nxt_slot_127.json', 'w')
                f.write(json.dumps(measured_data))
                f.close()
                payload_length = -1
                self.close()
        elif self.inputBuf[1] == 'R':
            print "command response: " + ":".join("{:02x}".format(ord(c))
                                                  for c in self.inputBuf[2:])
        elif self.inputBuf[1] == 'E':
            print "------------------------------------------------------------------------"
            print "error msg: " + ":".join("{:02x}".format(ord(c))
                                           for c in self.inputBuf[2:])
            print "------------------------------------------------------------------------"
        elif self.inputBuf[1] == 'S':
            #Sending commands to mote
            #Here I am using global variables
            #curr_packet_time = int(round(time.time() * 1000))
            #print "request frame: " + str(curr_packet_time-self.rframe_latency)
            #self.rframe_latency  =  curr_packet_time
            global outputBuf
            global outputBufLock
            #global latency
            if (len(outputBuf) > 0) and not outputBufLock:
                outputBufLock = True
                dataToWrite = outputBuf.pop(0)
                outputBufLock = False
                #print int(round(time.time() * 1000)) - latency
                self.serial.write(dataToWrite)
                #print len(dataToWrite)
                print "injecting: " + ":".join("{:02x}".format(ord(c))
                                               for c in dataToWrite)
        self.inputBuf = ''

    def _process_packet(self, packet):
        print "process_packet_func"

    def _fill_outputbuf(self):
        #When user wants to send some data, data will be pushed to this buffer
        print __name__

    def close(self):
        self.goOn = False

    def prepare_UDP_packet(self, payload):
        print "prepare_UDP_packet"

        #Running mean implementation by storing only one element, and sample count
    def running_mean(self, x):
        #I have used 300 to make sure that first outlier is rejected, while calculating the average
        tmp = self.latency[0] * max(self.latency[1] - 1, 1) + x
        self.latency[0] = tmp / self.latency[1]
Exemplo n.º 16
0
 def __init__(self, host):
     Routing.__init__(self, host)
     self.net = None
Exemplo n.º 17
0
 def __init__(self, host):
     Routing.__init__(self, host)
     self.isStarted = False
     atexit.register(self.stop)
Exemplo n.º 18
0
def get_all_responses(user, sname, dbName, sdata):
        u_resps = []
        u_bin = user.BIN
	
	if 'preamble' in sdata.keys() and sdata['preamble'] == True:
		u_resps.append(None)
   
	rt = Routing(sname, dbName)
	curr_q = rt.getFirstQuestion()
	
	while curr_q is not 'end':
		curr_q = str(curr_q)
		question_text = sdata[curr_q]["question_text"]
		question_type = sdata[curr_q]["question_type"]
    
		if sdata[curr_q]["demographic"]:
		    if sdata[curr_q]["choices"] and type(sdata[curr_q]["choices"]) is list:	#works only for household income
			hincp = user.HINCP
			val = sdata[curr_q]["choices"][hincp-1]

		    else:
			mapped_ora_col = sdata[curr_q]["mapped_ora_col"]
			val = getattr(user, mapped_ora_col.upper())

		    u_resps.append({question_text : val})
		    nextq = rt.getNextQuestion(long(curr_q), val)

		    curr_q = nextq		    
	
		else:
		    if sdata[curr_q]["range"]:
			try:
				key = sdata[curr_q]['range']['$ref']
				mapped_ora_col = sdata[curr_q][key]
				maxval = getattr(user, mapped_ora_col.upper())
			except:
				maxval = sdata[curr_q]['range']
				
			val = numpy.random.choice(range(maxval),1) #excluding you
			u_resps.append({question_text : val})
			nextq = rt.getNextQuestion(long(curr_q), val)
			curr_q = nextq


		    else:
			if "Radio" in question_type:
				pick = 1
				ch_probs = sdata[curr_q]["choices"][u_bin]
				choices = [ch for ch in ch_probs]
				probs = [ch_probs[ch] for ch in ch_probs]
				choose = numpy.random.choice(choices, pick, probs)

				u_resps.append({question_text : choose[0]})

				nextq = rt.getNextQuestion(long(curr_q), choose[0])
				curr_q = nextq


			elif "Check" in question_type:
				chosen = []
				temp = []

				choices = sdata[curr_q]["choices"][u_bin]
				#for key,value in choices.items():
				#	print key
				#	print value
				#	res = numpy.random.choice(['yes','no'],1,[value, 1-value])
				#	print res[0]
				#	#if res[0]=='yes':
				#	#	print value
				

				probs = numpy.random.uniform(size=(1, len(choices)))
				samples = probs < choices.values()
				
				print probs
				print choices.values()

				if numpy.any(samples):  #returns True is any of the elements is True
				    resp = numpy.choose(numpy.where(samples[0, :]), choices.keys())
				    for r in range(resp.size):
					chosen.append((question_text, resp.flat[r]))
					temp.append(resp.flat[r])
				else:
				    chosen.append((question_text, sdata[curr_q]["choices"]["default"]))
				    temp.append(sdata[curr_q]["choices"]["default"])
				
				
				u_resps.append(chosen)
				nextq = rt.getNextQuestion(long(curr_q), temp)
				curr_q = nextq

			elif "LineTextField" in question_type:
				u_resps = 'single line or multi-line answers not supported'
				curr_q = nextq


	return u_resps