Esempio n. 1
0
    def createSubmodels(self, initialState):

        # initializing sub modules
        self.meteo = meteo.Meteo(self._configuration,self.landmask,initialState)
        self.landSurface = landSurface.LandSurface(self._configuration,self.landmask,initialState)
        self.groundwater = groundwater.Groundwater(self._configuration,self.landmask,initialState)
        self.routing = routing.Routing(self._configuration, initialState, self.lddMap)
 
        # short name for every land cover type (needed for file name)
        self.shortNames = ['f','g','p','n']
Esempio n. 2
0
	def __init__(self, i, exp_name, sack, snoop):
		self.routing = routing.Routing(1000, i, exp_name)
		self.addr = self.routing.addr
		self.queues = {}
		self.sack = sack
		self.snoop = snoop
		self.queues[1] = queue.SimpleQueue()
		self.ack_queues = {}
		self.default_rwnd = 50
		self.exp_name = exp_name
		if not os.path.exists(exp_name):
			os.mkdir(exp_name)
		threading.Thread(target = self.listener).start()
Esempio n. 3
0
import hashlib

config = int(sys.argv[1])
#config = 1


def receiver():
    while True:
        try:
            data, addr = r.recv()
            print(data, addr)
        except queue.Empty:
            print("Timed out.")


r = routing.Routing(10, config)
threading.Thread(target=receiver).start()

if len(sys.argv) > 2:
    host = sys.argv[2]
    port = int(sys.argv[3])
    alph = ["a", "b", "c", "d", "e", "f"]
    for a in alph:
        p = packet.Packet()
        data = a * 650
        p.add_data(data)
        p.add_UDP_layer(r.addr[1], port,
                        hashlib.md5(data.encode("utf-8")).hexdigest())
        p.add_IP_layer(r.addr[0], r.addr[1], host, port)
        pkt = p.generate_packet()
        print("Sending to:", host, port)
Esempio n. 4
0
def main():
    with open('m.json', 'r') as _file:
        j = json.load(_file)
    r = routing.Routing(j['map'])
Esempio n. 5
0
from flask_cors import CORS
from flask import jsonify
import uuid
import datetime

import routing
from routing import Reasoning

import logging

value_map = {}

server = Flask(__name__)
CORS(server)

r = routing.Routing()
reasoner = Reasoning()

logging.getLogger().setLevel(logging.DEBUG)
"""
@server.route('/tour', methods=['POST'])
def get_tour():
    logging.debug("Getting tour request")
    content = request.json

    if not content:
        logging.debug("No json content")

        return jsonify({"Message": "No content"})
    try: 
        return jsonify({})
Esempio n. 6
0
    def createSubmodels(self, initialState):

        # initializing sub modules
        self.meteo = meteo.Meteo(self._configuration,self.landmask,initialState)
        self.routing = routing.Routing(self._configuration, initialState, self.lddMap)
Esempio n. 7
0
    def run(self):
        with env.use() as envdata:
            start = envdata.parse_station(self.args.start)
            end = envdata.parse_station(self.args.end)

            if start is None:
                log.error(
                    "Error: start system/station {0} could not be found. Stopping."
                    .format(self.args.start))
                return
            if end is None:
                log.error(
                    "Error: end system/station {0} could not be found. Stopping."
                    .format(self.args.end))
                return

            # Locate all the systems/stations provided and ensure they're valid for our ship
            stations = envdata.parse_stations(self.args.stations)
            for sname in self.args.stations:
                if sname in stations and stations[sname] is not None:
                    sobj = stations[sname]
                    log.debug("Adding system/station: {0}".format(
                        sobj.to_string()))
                    if self.args.pad_size == "L" and sobj.max_pad_size != "L":
                        log.warning(
                            "Warning: station {0} ({1}) is not usable by the specified ship size."
                            .format(sobj.name, sobj.system_name))
                else:
                    log.warning(
                        "Error: system/station {0} could not be found.".format(
                            sname))
                    return
        stations = list(stations.values())

        # Prefer a static jump range if provided, to allow user to override ship's range
        if self.args.jump_range is not None:
            full_jump_range = self.args.jump_range
            jump_range = self.args.jump_range
        else:
            full_jump_range = self.ship.range()
            jump_range = self.ship.max_range(
            ) if self.args.long_jumps else full_jump_range

        calc = c.Calc(ship=self.ship,
                      jump_range=self.args.jump_range,
                      witchspace_time=self.args.witchspace_time,
                      route_strategy=self.args.route_strategy,
                      slf=self.args.slf)
        r = rx.Routing(calc, self.args.rbuffer, self.args.hbuffer,
                       self.args.route_strategy)
        s = solver.Solver(calc, r, jump_range, self.args.diff_limit)

        if self.args.ordered:
            route = [start] + stations + [end]
        else:
            # Add 2 to the jump count for start + end
            route, is_definitive = s.solve(stations, start, end,
                                           self.args.num_jumps + 2,
                                           self.args.solve_mode)

        if self.args.reverse:
            route = [route[0]] + list(reversed(route[1:-1])) + [route[-1]]

        totaldist = 0.0
        totaldist_sl = 0.0
        totaljumps_min = 0
        totaljumps_max = 0
        totalsc = 0
        totalsc_accurate = True

        output_data = []
        total_fuel_cost = 0.0
        total_fuel_cost_exact = True

        if route is not None and len(route) > 0:
            output_data.append({'src': route[0].to_string()})

            for i in range(1, len(route)):
                cur_data = {'src': route[i - 1], 'dst': route[i]}

                if self.args.jump_range is not None:
                    full_max_jump = self.args.jump_range - (
                        self.args.jump_decay * (i - 1))
                    cur_max_jump = full_max_jump
                else:
                    full_max_jump = self.ship.range(cargo=self.args.cargo *
                                                    (i - 1))
                    cur_max_jump = self.ship.max_range(
                        cargo=self.args.cargo *
                        (i - 1)) if self.args.long_jumps else full_max_jump

                cur_data['jumpcount_min'], cur_data[
                    'jumpcount_max'] = calc.jump_count_range(
                        route[i - 1], route[i], i - 1, self.args.long_jumps)
                if self.args.route:
                    log.debug("Doing route plot for {0} --> {1}".format(
                        route[i - 1].system_name, route[i].system_name))
                    if route[i - 1].system != route[i].system and cur_data[
                            'jumpcount_max'] > 1:
                        leg_route = r.plot(route[i - 1].system,
                                           route[i].system, cur_max_jump,
                                           full_max_jump)
                    else:
                        leg_route = [route[i - 1].system, route[i].system]

                    if leg_route is not None:
                        route_jcount = len(leg_route) - 1
                        # For hoppy routes, always use stats for the jumps reported (less confusing)
                        cur_data['jumpcount_min'] = route_jcount
                        cur_data['jumpcount_max'] = route_jcount
                    else:
                        log.warning(
                            "No valid route found for leg: {0} --> {1}".format(
                                route[i - 1].system_name,
                                route[i].system_name))
                        total_fuel_cost_exact = False
                else:
                    total_fuel_cost_exact = False

                cur_data['legsldist'] = route[i - 1].distance_to(route[i])
                totaldist_sl += cur_data['legsldist']
                totaljumps_min += cur_data['jumpcount_min']
                totaljumps_max += cur_data['jumpcount_max']
                if route[i].distance is not None and route[i].distance != 0:
                    totalsc += route[i].distance
                elif route[i].name is not None:
                    # Only say the SC time is inaccurate if it's actually a *station* we don't have the distance for
                    totalsc_accurate = False

                cur_fuel = self.ship.tank_size if self.ship is not None else self.args.tank
                if self.args.route and leg_route is not None:
                    cur_data['leg_route'] = []
                    cur_data['legdist'] = 0.0
                    for j in range(1, len(leg_route)):
                        ldist = leg_route[j - 1].distance_to(leg_route[j])
                        cur_data['legdist'] += ldist
                        is_long = (ldist > full_max_jump)
                        fuel_cost = None
                        min_tank = None
                        max_tank = None
                        if cur_fuel is not None:
                            fuel_cost = min(self.ship.cost(ldist, cur_fuel),
                                            self.ship.fsd.maxfuel)
                            min_tank, max_tank = self.ship.fuel_weight_range(
                                ldist, self.args.cargo * (i - 1))
                            if max_tank is not None and max_tank >= self.ship.tank_size:
                                max_tank = None
                            total_fuel_cost += fuel_cost
                            cur_fuel -= fuel_cost
                            # TODO: Something less arbitrary than this?
                            if cur_fuel < 0:
                                cur_fuel = self.ship.tank_size if self.ship is not None else self.args.tank
                        # Write all data about this jump to the current leg info
                        cur_data['leg_route'].append({
                            'is_long':
                            is_long,
                            'ldist':
                            ldist,
                            'src':
                            Station.none(leg_route[j - 1]),
                            'dst':
                            Station.none(leg_route[j]),
                            'fuel_cost':
                            fuel_cost,
                            'min_tank':
                            min_tank,
                            'max_tank':
                            max_tank
                        })
                    totaldist += cur_data['legdist']

                if route[i].name is not None:
                    cur_data['sc_time'] = "{0:.0f}".format(
                        calc.sc_cost(route[i].distance)) if (
                            route[i].distance is not None
                            and route[i].distance != 0) else "???"
                # Add current route to list
                output_data.append(cur_data)

            # Get suitably formatted ETA string
            est_time_min = calc.route_time(route, totaljumps_min)
            est_time_min_m = math.floor(est_time_min / 60)
            est_time_min_s = int(est_time_min) % 60
            est_time_str = "{0:.0f}:{1:02.0f}".format(est_time_min_m,
                                                      est_time_min_s)
            if totaljumps_min != totaljumps_max:
                est_time_max = calc.route_time(route, totaljumps_max)
                est_time_max_m = math.floor(est_time_max / 60)
                est_time_max_s = int(est_time_max) % 60
                est_time_str += " - {0:.0f}:{1:02.0f}".format(
                    est_time_max_m, est_time_max_s)

            totaljumps_str = "{0:d}".format(
                totaljumps_max
            ) if totaljumps_min == totaljumps_max else "{0:d} - {1:d}".format(
                totaljumps_min, totaljumps_max)

            # Work out the max length of the jump distances and jump counts to be printed
            d_max_len = 1
            jmin_max_len = 1
            jmax_max_len = 1
            has_var_jcounts = False
            for i in range(1, len(output_data)):
                od = output_data[i]
                # If we have a hoppy route, we'll only be printing single-jump ranges. If not, we'll be using full leg distances.
                if self.args.format == 'long' and 'leg_route' in od:
                    if len(od['leg_route']) > 0:
                        d_max_len = max(
                            d_max_len,
                            max([l['ldist'] for l in od['leg_route']]))
                else:
                    d_max_len = max(d_max_len, od['legsldist'])
                # If we have estimated jump counts, work out how long the strings will be
                if 'jumpcount_min' in od:
                    jmin_max_len = max(jmin_max_len, od['jumpcount_min'])
                    jmax_max_len = max(jmax_max_len, od['jumpcount_max'])
                    has_var_jcounts = has_var_jcounts or (
                        od['jumpcount_min'] != od['jumpcount_max'])

            # Length = "NNN.nn", so length = len(NNN) + 3 = log10(NNN) + 4
            d_max_len = str(int(math.floor(math.log10(d_max_len))) + 4)
            # Work out max length of jump counts, ensuring >= 1 char
            jmin_max_len = int(math.floor(max(1,
                                              math.log10(jmin_max_len) + 1)))
            jmax_max_len = int(math.floor(max(1,
                                              math.log10(jmax_max_len) + 1)))
            # If we have the form "N - M" anywhere, pad appropriately. If not, just use the normal length
            jall_max_len = str(jmin_max_len + jmax_max_len +
                               3) if has_var_jcounts else str(jmin_max_len)
            jmin_max_len = str(jmin_max_len)
            jmax_max_len = str(jmax_max_len)

            print_summary = True

            if self.args.format in ['long', 'summary']:
                print("")
                print(route[0].to_string())

                # For each leg (not including start point)
                for i in range(1, len(route)):
                    od = output_data[i]
                    if self.args.format == 'long' and 'leg_route' in od:
                        # For every jump except the last...
                        for j in range(0, len(od['leg_route']) - 1):
                            ld = od['leg_route'][j]
                            ld_fuelstr = ''
                            if ld['max_tank'] is not None:
                                ld_fuelstr = " at {0:.2f}-{1:.2f}T ({2:d}-{3:d}%)".format(
                                    ld['min_tank'], ld['max_tank'],
                                    int(100.0 * ld['min_tank'] /
                                        self.ship.tank_size),
                                    int(100.0 * ld['max_tank'] /
                                        self.ship.tank_size))
                            print(("    -{0}- {1: >" + d_max_len +
                                   ".2f}Ly -{0}-> {2}{3}{4}").format(
                                       "!" if ld['is_long'] else "-",
                                       ld['ldist'], ld['dst'].to_string(),
                                       " [{0:.2f}T]".format(ld['fuel_cost'])
                                       if self.ship is not None else '',
                                       ld_fuelstr))
                        # For the last jump...
                        ld = od['leg_route'][-1]
                        ld_fuelstr = ''
                        if ld['max_tank'] is not None:
                            ld_fuelstr = " at {0:.2f}-{1:.2f}T ({2:d}-{3:d}%)".format(
                                ld['min_tank'], ld['max_tank'],
                                int(100.0 * ld['min_tank'] /
                                    self.ship.tank_size),
                                int(100.0 * ld['max_tank'] /
                                    self.ship.tank_size))

                        print((
                            "    ={0}= {1: >" + d_max_len +
                            ".2f}Ly ={0}=> {2}{5}{6} -- {3:.2f}Ly for {4:.2f}Ly"
                        ).format(
                            "!" if ld['is_long'] else "=", ld['ldist'],
                            od['dst'].to_string(), od['legdist'],
                            od['legsldist'],
                            " [{0:.2f}T]".format(ld['fuel_cost'])
                            if self.ship is not None else '', ld_fuelstr))
                    else:
                        fuel_fewest = None
                        fuel_most = None
                        if self.ship is not None:
                            # Estimate fuel cost assuming average jump size and full tank.
                            fuel_fewest = self.ship.cost(od['legsldist'] / max(
                                0.001, float(od['jumpcount_min']))) * int(
                                    od['jumpcount_min'])
                            fuel_most = self.ship.cost(od['legsldist'] / max(
                                0.001, float(od['jumpcount_max']))) * int(
                                    od['jumpcount_max'])
                            total_fuel_cost += max(fuel_fewest, fuel_most)
                        # If we don't have "N - M", just print simple result
                        if od['jumpcount_min'] == od['jumpcount_max']:
                            jumps_str = ("{0:>" + jall_max_len +
                                         "d} jump{1}").format(
                                             od['jumpcount_max'], "s" if
                                             od['jumpcount_max'] != 1 else " ")
                        else:
                            jumps_str = ("{0:>" + jmin_max_len + "d} - {1:>" +
                                         jmax_max_len + "d} jumps").format(
                                             od['jumpcount_min'],
                                             od['jumpcount_max'])
                        route_str = od['dst'].to_string()
                        # If the destination is a station, include estimated SC time
                        if 'sc_time' in od:
                            route_str += ", SC: ~{0}s".format(od['sc_time'])
                        fuel_str = ""
                        if self.ship is not None:
                            if od['jumpcount_min'] == od['jumpcount_max']:
                                fuel_str = " [{0:.2f}T{1}]".format(
                                    fuel_fewest,
                                    '+' if od['jumpcount_min'] > 1 else '')
                            else:
                                fuel_str = " [{0:.2f}T+ - {1:.2f}T+]".format(
                                    min(fuel_fewest, fuel_most),
                                    max(fuel_fewest, fuel_most))
                        print(("    === {0: >" + d_max_len +
                               ".2f}Ly ({1}) ===> {2}{3}").format(
                                   od['legsldist'], jumps_str, route_str,
                                   fuel_str))

            elif self.args.format == 'short':
                print("")
                sys.stdout.write(str(route[0]))
                for i in range(1, len(route)):
                    od = output_data[i]
                    if 'leg_route' in od:
                        for j in range(0, len(od['leg_route'])):
                            ld = od['leg_route'][j]
                            sys.stdout.write(", {0}".format(str(ld['dst'])))
                    else:
                        sys.stdout.write(", {0}".format(str(od['dst'])))
                print("")

            elif self.args.format == 'csv':
                print("{0},{1},{2},{3}".format(
                    route[0].system_name,
                    route[0].name if route[0].name is not None else '', 0.0,
                    route[0].distance if route[0].uses_sc
                    and route[0].distance is not None else 0))
                for i in range(1, len(route)):
                    od = output_data[i]
                    if 'leg_route' in od:
                        for j in range(0, len(od['leg_route']) - 1):
                            ld = od['leg_route'][j]
                            print("{0},{1},{2},{3}".format(
                                ld['dst'].system_name, ld['dst'].name
                                if ld['dst'].name is not None else '',
                                ld['ldist'],
                                ld['dst'].distance if ld['dst'].uses_sc
                                and ld['dst'].distance is not None else 0))
                        ld = od['leg_route'][-1]
                        print("{0},{1},{2},{3}".format(
                            od['dst'].system_name, od['dst'].name
                            if od['dst'].name is not None else '', ld['ldist'],
                            od['dst'].distance if od['dst'].uses_sc
                            and od['dst'].distance is not None else 0))
                    else:
                        print("{0},{1},{2},{3}".format(
                            od['dst'].system_name, od['dst'].name
                            if od['dst'].name is not None else '',
                            od['legsldist'],
                            od['dst'].distance if od['dst'].uses_sc
                            and od['dst'].distance is not None else 0))
                print_summary = False

            if print_summary:
                totaldist_str = "{0:.2f}Ly ({1:.2f}Ly)".format(
                    totaldist, totaldist_sl
                ) if totaldist >= totaldist_sl else "{0:.2f}Ly".format(
                    totaldist_sl)
                fuel_str = "; fuel cost: {0:.2f}T{1}".format(
                    total_fuel_cost, '+' if not total_fuel_cost_exact else
                    '') if total_fuel_cost else ''
                print("")
                print("Total distance: {0}; total jumps: {1}".format(
                    totaldist_str, totaljumps_str))
                print("Total SC distance: {0:d}Ls{1}; ETT: {2}{3}".format(
                    totalsc, "+" if not totalsc_accurate else "", est_time_str,
                    fuel_str))
                print("")

            if self.ship is not None:
                for i in range(1, len(route)):
                    od = output_data[i]
                    if 'leg_route' in od:
                        fcost = 0.0
                        for j in range(0, len(od['leg_route'])):
                            fcost += self.ship.cost(
                                od['leg_route'][j]['src'].distance_to(
                                    od['leg_route'][j]['dst']))
                        log.debug(
                            "Hop {0} -> {1}, highball fuel cost: {2:.2f}T".
                            format(od['src'].system_name,
                                   od['dst'].system_name, fcost))

        else:
            print("")
            print("No viable route found :(")
            print("")
Esempio n. 8
0
localIP = '0.0.0.0'
localPort = 1337
cSuite = 1
endpoint_address = ('172.18.0.252', 3333)

# create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((localIP, localPort))

# fetch certificate and its status
myCert, myCertStatus = sts_utility.decodeMyCertificate(sock, endpoint_address)
# create an STS (TLS) instance
STS = sts_checks.STS(sock, myCert, myCertStatus)
# create a routing table instance
RT = routing.Routing(STS)
# insert bootstrap node to routing table
RT.insertBootstrap()
# for storing all the recursive nodes in the recursive lookup
recursiveNodes = OrderedDict()
# storage instance
StoreData = storage.Storage()


def packetLengthCheck(data):
    return len(data) >= 13


# check the message validity based on the nonce and insert into message queue
def messageCheck(data):
    if message.Messages().checkResponse(packet.nonceExtract(data)):
Esempio n. 9
0
def openSeam(sm, dr, cost, qbits, paths, qb_conf, pt_conf, tg_fn, par):
    ''' recursively open seam'''

    global _cells, _numAdj, M, N, L, _qbitAdj, _cell_flags, _qubits, _reserved
    ## erase conflicts

    log('Broken qubits: \n %s \n\n' % str(qb_conf))

    # erase qbit conflicts and update broken paths
    log('Erasing %d broken qubits...\n' % len(qb_conf))
    cell_conf = map(lambda x: _cells[x], qb_conf)
    for qb in qb_conf:
        new_paths = forgetQubit(qb)
        log('%s: %s\n' % (str(qb), str(new_paths)))
        pt_conf.update(new_paths)
        for pt in new_paths:
            if pt in paths:
                paths.pop(pt)
    log(' done\n')

    # erase path conflicts
    log('Erasing %d broken paths...\n' % len(pt_conf))
    for path in pt_conf:
        log('path: %s\n' % str(path))
        forgetPath(path)
    log(' done\n')

    # retain path keys between good qbits
    pt_rp = []
    for key in pt_conf:
        if _cell_flags[key[0]]['placed'] and _cell_flags[key[1]]['placed']:
            pt_rp.append(key)

    ## STORE OLD VALUES AND WIPE SEAM TARGET REGION

    # map of new qbits for each cell
    qbit_dict = {_cells[qb]: tg_fn(qb) for qb in qbits}

    # map of new paths
    path_dict = {key: newPath(key, paths[key], tg_fn) for key in paths}

    # wipe old qubits and paths
    log('Wiping old values...\n')
    log('\t qbits...')
    for qb in qbits:
        forgetQubit(qb, False)
    log('done\n')
    log('\t paths...')
    for key in paths:
        forgetPath(key, False)
    log('done\n')

    # assign new qubits and paths
    log('Assigning new values...\n')
    for cell in qbit_dict:
        assignQubit(cell, qbit_dict[cell])

    assignPaths(path_dict.values())

    # update all reserved qubits
    log('updating all reservations...\n')
    reserveQubits(filter(None, _qubits.values()))

    ## repair broken paths

    # only place paths between moved qubits
    log('Attempting to replace broken routes between moved qubits\n')
    routes = []
    for pt in pt_rp:
        rt = map(lambda x: _qubits[x], pt)
        routes.append(rt)
    cost = Routing.Routing(routes, _reserved, writePath=ROUTE_PATH)

    # check successful routing
    if cost >= Routing.COST_BREAK:
        log('routing failed...\n')
        raise KeyError('Routing failed for paths between moved qbits in \
        seam opening... fix code later')

    # get paths
    log('Routing successfull, preparing to assign new paths\n')
    fixed_paths = cp(Routing.getPaths().values())

    # disable path qubits
    log('Disabling new paths\n')
    qbs = list(set([it for path in fixed_paths for it in path]))
    Routing.disableQubits(qbs)

    # assign paths and update reservations
    log('Assigning new paths \n')
    assignPaths(fixed_paths)

    ## repair qbit placements, should automatically deal with paths

    # order qbits to be placed by decreasing adjacency
    log('Preparing new qbit placements \n')
    cell_ord = sorted(cell_conf, key=lambda x: -_numAdj[x])

    for cell in cell_ord:
        log('cell: %s ...' % str(cell))
        new_qb, new_paths = placeCell(cell)  # recursive call

        # abort on failed placement
        if new_qb is None:
            return False
            raise KeyError('Failed cell %s placement in seam \
            opening' % str(cell))

        # assign qubit and paths
        assignQubit(cell, new_qb)
        assignPaths(new_paths)

        # handle reservations
        reserveQubits([new_qb])

    return True
Esempio n. 10
0
def placeCell(cell):
    '''Attempt to find a suitable qbit to place input cell on.

    inputs: cell(int)		: source index of cell to place

    output: qbit(tuple)		: 4-tup for qbit to assign to cell
            paths(list)		: list of paths from placed cell qubits to
                              qbit
    '''

    global _qbitAdj, _source, _qubits
    global _cell_flags, _qbit_flags, _reserved, _vacancy

    log('\n' + '#' * 30 + '\n')
    log('Placing cell: %s\n' % str(cell))

    ### Initialise

    seam_flag = False
    qbit = None

    # find qubits for placed adjacent cells
    adj_qbits = [_qubits[c] for c in _source[cell] if _cell_flags[c]['placed']]
    log('Adjacent qbits: %s\n' % str(adj_qbits))

    # find required availability of target qbit
    avb = len(_source[cell])
    log('Required availability: %d\n' % avb)

    # multisourcesearch parameters
    forb = set()  # list of forbidden qbit for multisourcesearch
    search_count = 0  # counter for number of failed searches

    # every time a seam is opened, we should check to see if there is a
    # better qubit to consider
    while qbit is None:

        ### Open Seam

        if seam_flag:
            log('Running Seam Opening Routine\n')
            seam_flag = False

            # check for vacancies
            if not any(_vacancy):
                log('No vacant columns/rows to open\n\n')
                raise KeyError('Out of room')

            # find available seams
            seams = availableSeams(adj_qbits)

            # analyse seams
            seam_dicts = map(lambda s: genSeamDict(s, adj_qbits), seams)
            seam_dicts = filter(None, seam_dicts)

            if len(seam_dicts) == 0:
                log('No suitable seams detected\n')
                return None, []

            # select seam to open
            seam_dict = selectSeam(seam_dicts)
            log('current vacancy: %s\n' % str(_vacancy))
            log('selected seam %s :: %s\n' %
                (str(seam_dict['sm']), str(seam_dict['dr'])))

            # open seam
            success = openSeam(**seam_dict)

            if not success:
                log('Failed to open seam\n\n')
                return None, []

            # update adjacent qubits
            log('Seam successfully opened... \n')
            adj_qbits = [
                _qubits[c] for c in _source[cell] if _cell_flags[c]['placed']
            ]
            log('New adjacent qbits: %s\n' % str(adj_qbits))

        ### Pick qubit to assign

        # run multisource search method, get list of candidate qbits
        qbits = multiSourceSearch(adj_qbits, avb, forb=forb)

        # check if found
        if not qbits:
            log('multiSourceSearch failed\n')
            seam_flag = True
            continue

        log('Found %d candidate qubits: %s \n' %
            (len(qbits), map(lambda x: str(x[1]), qbits)))

        # check each candidate qbit from multisourcesearch in order
        for qbit in qbits:

            suit, qbit = qbit

            log('Trying qbit: %s with suitability %s ...' %
                (str(qbit), str(suit)))

            ### Find paths

            routes = [[qb, qbit] for qb in adj_qbits]
            end_points = list(set([it for rt in routes for it in rt]))
            # find best consistent paths
            cost = Routing.Routing(routes, _reserved, writePath=ROUTE_PATH)

            # check successful routing

            if cost >= Routing.COST_BREAK:
                log('routing failed...\n')
                # disable end points
                Routing.disableQubits(end_points)
                continue

            log('\t success\n')
            break
        else:
            log('No suitable qbit found\n')
            qbit = None
            search_count += 1
            if search_count >= MAX_SEARCH_COUNT:
                seam_flag = True
                search_count = 0
                forb.clear()
            else:
                forb.update(map(lambda x: x[1], qbits))

    # get paths
    paths = cp(Routing.getPaths().values())

    # disable path qubits
    qbs = list(set([it for path in paths for it in path]))
    Routing.disableQubits(qbs)

    log('Placed on qubit: %s\n\n' % str(qbit))
    #    log('Paths: \n')
    #    for path in paths:
    #        log('\t %s \n' % str(path))
    #    log('\n')
    return qbit, paths
    def __init__(self, mac, ip_v6, ip_v4, interface, iface_idx, sn, ah_i,
                 main_logger):
        """BabelManager initial function.

        Args:
            mac: String value of MAC addres.
            ip_v6: String value of IPv6 address.
            iface_idx: Integer value of interface index.
            main_logger: Pointer to main logger class.
        """
        self.MY_IPV6 = ip_v6
        self.MY_IPV4 = ip_v4
        self.MAC = mac
        self.INTERFACE = interface
        self.IFACE_IDX = iface_idx
        self.ah_i = ah_i
        self.main_logger = main_logger
        self.routing = routing.Routing(main_logger=self.main_logger,
                                       interface=self.INTERFACE)
        self.TIME_FOR_RESPONSE = {
            'ROUTE_CHANGE': 0.3,
            'REQ_TO_EST_RT': 2.0,
            'RES_TO_EST_IP': 0.2,
            'REQ_IP_ADDR': 0.5,
            'ROUTE_INFO': 1.0
        }
        # RFC 6126 Apenix B Constants
        # Intervals are cecified in centiseconds RFC 6126 4.1.1
        self.HELLO_MSG_INTERVAL = 40
        self.IHU_MSG_INTERVAL = 3 * self.HELLO_MSG_INTERVAL
        self.UPDATE_MSG_INTERVAL = 4 * self.HELLO_MSG_INTERVAL
        self.IHU_HOLD_TIME = int(3.5 * self.IHU_MSG_INTERVAL)
        self.ROUTE_EXPIRY_TIME = int(3.5 * self.UPDATE_MSG_INTERVAL)
        self.GC = 1800  # 3 minutes - garbage collection timer (source table)

        self.PLEN = 64  # in bits
        self.HOPCOUNT = 16
        self.ACK_REQ_INTERVAL = 5

        self.MSG_TYPE = {
            'Pad1': 0,
            'PadN': 1,
            'AckReq': 2,
            'Ack': 3,
            'Hello': 4,
            'IHU': 5,
            'RouterID': 6,
            'NextHop': 7,
            'Update': 8,
            'RouteReq': 9,
            'SeqnoReq': 10,
            'RTReq': 11,
            'RTInfo': 12
        }
        self.MY_RID = int(sn, 16) % int(0xFFFFFFFF)
        self.seqno = 0
        self.number_of_init_hello_msgs = 0

        self.interface_table = []
        self.neigh_table = []
        self.source_table = []
        self.route_table = []
        # self.pend_req_table = []
        self.other_nodes_rts = []
        self.ipv6_to_ipv4 = [[self.MY_IPV6], [self.MY_IPV4]]