Example #1
0
    def breed(self, mother, father):
        """Make two children as parts of their parents.

        Args:
            mother (dict): Network parameters
            father (dict): Network parameters

        Returns:
            (list): Two network objects

        """
        children = []
        for _ in range(2):

            child = {}

            # Loop through the parameters and pick params for the kid.
            for param in self.nn_param_choices:
                child[param] = random.choice(
                    [mother.network[param], father.network[param]])

            # Now create a network object.
            network = Network(self.nn_param_choices)
            network.create_set(child)

            # Randomly mutate some of the children.
            if self.mutate_chance > random.random():
                network = self.mutate(network)

            children.append(network)

        return children
Example #2
0
def run():
    nodes = [Node('0', 0, 0), Node('1', 0, 50), Node('2', 0, 400)]

    edges = [Edge(nodes[0], nodes[1]), Edge(nodes[1], nodes[2])]

    newNet = Network(nodes, edges)

    with open("local\\sumo.path", 'r') as f:
        sumo_path = f.read()
        sumo_tools = sumo_path + '\\tools'
        sumo_path += '\\bin'
        print(sumo_path)

    os.makedirs('simple_2d', exist_ok=True)
    newNet.writeNet(sumo_path, 'simple_2d\\2d')

    vehTypes = []
    vehTypes.append(VehicleType((0, 1, 0), 'smart'))
    vehTypes.append(VehicleType((1, 0, 0), 'dumb'))

    numCars = 100
    starts = Demand._def_rand_departs(numCars, 2)
    prob_smart = .5
    vehicles = []

    dumbcars = []
    for x in [('%s' % i, random.random(), starts[i]) for i in range(numCars)]:
        if x[1] < prob_smart:
            vType = vehTypes[0]
        else:
            vType = vehTypes[1]
            dumbcars.append(x[0])
        route = Route(['0_1', '1_2'])
        vehicles.append(Vehicle(x[0], x[2], vType, route))
    dem = Demand(vehTypes, vehicles)

    dem.genRouteFile('simple_2d\\2d.rou.xml')

    sensorList = []
    lane = '1_2_0'
    sensorList.append(Fusion.Sensor('first', 75, lane, [.25], .95))
    sensorList.append(Fusion.Sensor('second', 200, lane, [.25], .95))
    fus = Fusion.FusionArchitecture(sensorList, None, None)

    runSim.runSim('simple_2d\\2d.net.xml',
                  'simple_2d\\2d.rou.xml',
                  None,
                  fusion=fus)
Example #3
0
def mapa(request):
    idProduto = request.GET.get("idProduto", None)
    markedSectors = []

    if idProduto is not None:
        urlSetoresProduto = 'https://scan-skip-plu-teste.herokuapp.com/setoresProduto/' + idProduto
        network = Network()
        response = network.request(urlSetoresProduto, 'GET')
        if response != -1:
            for setor in response:
                markedSectors.append(setor['idSetor'])

    return render(request, 'mapa.html', {
        'markedSectors': markedSectors,
        'sectorsRange': range(1, 53)
    })
Example #4
0
def produto(request, idProduto):
    urlProduto = 'https://supermercado-carrinho.herokuapp.com/produtos/TesteProduto/'  #'http://143.107.102.48:3000/produto/' + idProduto
    network = Network()
    response = network.request(urlProduto, 'GET')
    nome = response['nome']
    marca = response['marca']
    preco = response['valor']
    preco = ('%.2f' % (float(preco) / 100)).replace('.', ',')
    categoria = response['categoria']
    imagem = response['imagem']
    return render(
        request, 'produto-escaneado-confirmacao.html', {
            'idProduto': idProduto,
            'nome': nome,
            'marca': marca,
            'preco': preco,
            'categoria': categoria,
            'imagem': imagem
        })
Example #5
0
    def create_population(self, count):
        """Create a population of random networks.

        Args:
            count (int): Number of networks to generate, aka the
                size of the population

        Returns:
            (list): Population of network objects

        """
        pop = []
        for _ in range(0, count):
            # Create a random network.
            network = Network(self.nn_param_choices)
            network.create_random()

            # Add the network to our population.
            pop.append(network)

        return pop
Example #6
0
def produto(request, idProduto):
    urlProduto = 'https://scan-skip-plu-teste.herokuapp.com/produto/' + idProduto
    network = Network()
    response = network.request(urlProduto, 'GET')
    if response != -1:
        quantidade = 1
        nome = response['nome']
        marca = response['marca']
        preco = response['valor']
        preco = ('%.2f' % (float(preco)/100)).replace('.', ',')
        categoria = response['categoria']
        imagem = response['imagem']

        # Salvando ultimo produto escaneado na sessão
        request.session['lastScannedProduct'] = idProduto

        return render(request, 'produto-escaneado-confirmacao.html', {'idProduto': idProduto, 'nome': nome, 'marca': marca, 'preco': preco, 'categoria': categoria, 'imagem': imagem, 'quantidade': quantidade, 'registrado': True})
    else:
        nome = 'Produto não registrado'
        marca = '-------'
        preco = '-------'
        categoria = '-------'
        return render(request, 'produto-escaneado-confirmacao.html', {'idProduto': idProduto, 'nome': nome, 'marca': marca, 'preco': preco, 'categoria': categoria, 'registrado': False})
Example #7
0
def main(arguments):
    print("Loading client...")
    try:
        if len(arguments) != globalsettings.ARGUMENTS_LENGTH:
            raise Exception(f"required 3 arguments received {len(arguments)}.")

        client_frame = window_frame(
            client_app,
            "uSpeak - client",
            GetSystemMetrics(0) / 2 - globalsettings.CLIENT_SCREEN_WIDTH / 2,
            GetSystemMetrics(1) / 2 - globalsettings.CLIENT_SCREEN_HEIGHT / 2,
            globalsettings.CLIENT_SCREEN_WIDTH,
            globalsettings.CLIENT_SCREEN_HEIGHT,
            stylesheet='',
            resizable=False)

        chat_box = text_field(client_frame, 10, 32, '')
        chat_box.setReadOnly(True)
        chat_box.resize(470, 350)

        userlist = QListWidget(client_frame)
        userlist.move(520, 32)
        userlist.resize(100, 120)

        channellist = QListWidget(client_frame)
        channellist.itemClicked.connect(
            lambda item: event.set_selected_channel(item))

        channellist.move(520, 160)
        channellist.resize(100, 200)

        chat_input = input_field(client_frame, 10, 387,
                                 'Message #selected channel')
        chat_input.resize(470, 30)

        message_button = button(
            client_frame,
            "Send message", 520, 387, lambda: client.send_message(
                globalsettings.USER_MESSAGE, event.selected_channel,
                event.get_input_text()))
        chat_input.returnPressed.connect(message_button.click)

        exitAct = QAction(QIcon(''), '&Disconnect', client_frame)
        exitAct.triggered.connect(os._exit)

        menubar = client_frame.menuBar()
        server_menu = menubar.addMenu('Server')
        action = server_menu.addAction(exitAct)

        event = Event(chat_box, chat_input, userlist, channellist)

        client = Network(arguments[0], int(arguments[1]), arguments[2], event)
        client.establish_connection()
        time.sleep(0.3)
        event.set_selected_channel(channellist.item(0))
        client_frame.gui_show()

    except Exception as exception:
        print(f"{exception}")
        print('test')
        exit()

    except IndexError:
        print(f"Required 3 arguments received {len(arguments)}.")
        exit()

    except:
        pass
Example #8
0
    Node('6', 0, 225),
    Node('7', 0, 250)
]

edges = [
    Edge(nodes[0], nodes[1]),
    Edge(nodes[1], nodes[2]),
    Edge(nodes[1], nodes[3]),
    Edge(nodes[2], nodes[4], speed=5),
    Edge(nodes[3], nodes[5], speed=2),
    Edge(nodes[4], nodes[6]),
    Edge(nodes[5], nodes[6]),
    Edge(nodes[6], nodes[7], numLanes=2)
]

newNet = Network(nodes, edges)

sumo_path = 'C:\\dev\\Traffic\\Sumo\\bin'

os.makedirs('oneway_data', exist_ok=True)
newNet.writeNet(sumo_path, 'oneway_data\\oneway')

vehTypes = []
vehTypes.append(VehicleType((0, 1, 0), 'smart'))
vehTypes.append(VehicleType((1, 0, 0), 'dumb'))

numCars = 100
starts = Demand._def_rand_departs(numCars, 2)
prob_smart = .5
vehicles = []
Example #9
0
ap.add_argument("-APRILTAG_16h5", "--DICT_APRILTAG_16h5", required=False, action="store_true", default=False, help="Include DICT_APRILTAG_16h5 into dataset.")
ap.add_argument("-APRILTAG_25h9", "--DICT_APRILTAG_25h9", required=False, action="store_true", default=False, help="Include DICT_APRILTAG_25h9 into dataset.")
ap.add_argument("-APRILTAG_36h10", "--DICT_APRILTAG_36h10", required=False, action="store_true", default=False, help="Include DICT_APRILTAG_36h10 into dataset.")
ap.add_argument("-APRILTAG_36h11", "--DICT_APRILTAG_36h11", required=False, action="store_true", default=False, help="Include DICT_APRILTAG_36h11 into dataset.")
args = vars(ap.parse_args())

# Verify the passed parameters
if not isinstance(args["shape"], tuple) or len(args["shape"]) != 3:
    raise Exception("Shape parameter is invalid. Should be something like '(256,256,3)'.")
if not isinstance(args["learning_rate"], float) or args["learning_rate"] <= 0.0:
    raise Exception("Learning rate parameter is invalid. Should be a float bigger than '0.0'.")
if not isinstance(args["iterations"], int) or args["iterations"] < 1:
    raise Exception("Iterations has an invalid value.")
if not isinstance(args["steps"], int) or args["steps"] < 1:
    raise Exception("Steps argument has an invalid value.")
if not isinstance(args["batch_size"], int) or args["batch_size"] < 1:
    raise Exception("Batch size has an invalid value.")
if not os.path.isdir(os.path.dirname(args["weights"])):
    raise Exception("Path to store weights is invalid.")
if not isinstance(args["saving_iterations"], int) or args["saving_iterations"] < 1:
    raise Exception("Saving iterations has an invalid value.")
if not (args["DICT_4X4_50"] or args["DICT_4X4_100"] or args["DICT_4X4_250"] or args["DICT_4X4_1000"] or args["DICT_5X5_50"] or args["DICT_5X5_100"] or args["DICT_5X5_250"] or args["DICT_5X5_1000"] or args["DICT_6X6_50"] or args["DICT_6X6_100"] or args["DICT_6X6_250"] or args["DICT_6X6_1000"] or args["DICT_7X7_50"] or args["DICT_7X7_100"] or args["DICT_7X7_250"] or args["DICT_7X7_1000"] or args["DICT_ARUCO_ORIGINAL"] or args["DICT_APRILTAG_16h5"] or args["DICT_APRILTAG_25h9"] or args["DICT_APRILTAG_36h10"] or args["DICT_APRILTAG_36h11"]):
    raise Exception("At least one marker family need to be enabled.")

# Initalize the segnet network
network = Network(shape=args["shape"], learning_rate=args["learning_rate"])
# Load checkpoint if is setted
if args["checkpoint"] != '':
	network.load_weights(weights_path=args["weights"])
# Start training
network.train_synthetic_data(iterations=args["iterations"], steps=args["steps"], batch_size=args["batch_size"], weights_path=args["weights"], saving_iterations=args["saving_iterations"], DICT_4X4_50=args["DICT_4X4_50"], DICT_4X4_100=args["DICT_4X4_100"], DICT_4X4_250=args["DICT_4X4_250"], DICT_4X4_1000=args["DICT_4X4_1000"], DICT_5X5_50=args["DICT_5X5_50"], DICT_5X5_100=args["DICT_5X5_100"], DICT_5X5_250=args["DICT_5X5_250"], DICT_5X5_1000=args["DICT_5X5_1000"], DICT_6X6_50=args["DICT_6X6_50"], DICT_6X6_100=args["DICT_6X6_100"], DICT_6X6_250=args["DICT_6X6_250"], DICT_6X6_1000=args["DICT_6X6_1000"], DICT_7X7_50=args["DICT_7X7_50"], DICT_7X7_100=args["DICT_7X7_100"], DICT_7X7_250=args["DICT_7X7_250"], DICT_7X7_1000=args["DICT_7X7_1000"], DICT_ARUCO_ORIGINAL=args["DICT_ARUCO_ORIGINAL"], DICT_APRILTAG_16h5=args["DICT_APRILTAG_16h5"], DICT_APRILTAG_25h9=args["DICT_APRILTAG_25h9"], DICT_APRILTAG_36h10=args["DICT_APRILTAG_36h10"], DICT_APRILTAG_36h11=args["DICT_APRILTAG_36h11"])
Example #10
0
                help="Define the shape of a tile (default=(256,256,3))).")
ap.add_argument("-w",
                "--weights",
                required=False,
                default='./weights/weights.ckpt',
                help="Path to the weights (default='./weights/weights.ckpt').")
ap.add_argument("-o",
                "--output",
                required=True,
                help="Path to save prediction.")
args = vars(ap.parse_args())

# Verify the passed parameters
if not os.path.isfile(args["image"]):
    raise Exception("Path to image is invalid.")
if not isinstance(args["shape"], tuple) or len(args["shape"]) != 3:
    raise Exception(
        "Shape parameter is invalid. Should be something like '(256,256,3)'.")
if not os.path.isdir(os.path.dirname(args["weights"])):
    raise Exception("Path to weights is invalid.")

# Load the image
image = cv2.cvtColor(cv2.imread(args["image"], 3), cv2.COLOR_BGR2RGB)

# Initalize the segnet network
network = Network(shape=args["shape"])
# Load the weights
network.load_weights(weights_path=args["weights"])
# Start prediction and save the results
prediction = network.predict(image)
cv2.imwrite(args["output"], cv2.cvtColor(prediction, cv2.COLOR_RGB2BGR))
dataset = []
index_count = 0
current_sample = args["dataset_path"] + "/" + str(index_count) + ".jpg"
current_sample_gt = args["dataset_path"] + "/" + str(index_count) + "_gt.jpg"
while os.path.isfile(current_sample) and os.path.isfile(current_sample_gt):
    dataset.append([current_sample, current_sample_gt])
    index_count += 1
    current_sample = args["dataset_path"] + "/" + str(index_count) + ".jpg"
    current_sample_gt = args["dataset_path"] + "/" + str(
        index_count) + "_gt.jpg"

if len(dataset) <= 0:
    raise Exception(
        "Cannot finde training samples in the directory " +
        args["dataset_path"] +
        ".\r\n To get more information take a look at the original github repo."
    )

# Initalize the segnet network
network = Network(shape=args["shape"], learning_rate=args["learning_rate"])
# Load checkpoint if is setted
if args["checkpoint"] != '':
    network.load_weights(weights_path=args["weights"])
# Start training
network.train_real_data(iterations=args["iterations"],
                        steps=args["steps"],
                        batch_size=args["batch_size"],
                        weights_path=args["weights"],
                        saving_iterations=args["saving_iterations"],
                        dataset=dataset)
Example #12
0
def main():
	server_settings = config.load_config(globalsettings.CONFIG_FILE_LOCATION)
	server = Network(server_settings['hostname'], server_settings['port'], server_settings['max_users'], server_settings['rcon'], server_settings['channels'])
	
	server.start()
Example #13
0
# Acquisition of Data: FOV, Cropped Original Image and Whole Image
print('Data Generation')
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
Preprocessing = preprocessing.Data(options.train_image, options.train_label,
                                   options.train_probability_map, C)
FOV_Path, LABEL_Path, IMAGE_Path, FOV_size, Fov_num = Preprocessing.create_data(
    options.path)

print('Data Generation finished')
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
# Input of 2 models
FOV_input = Input(shape=FOV_size)
Stack_input = Input(shape=FOV_size)

# Network of two CNNs
Net = Network(options.network, options.structure)
First_Network_Output = Net.get_first_network(FOV_input)
Second_Network_Output = Net.get_second_network(Stack_input)

# Build the model
First_Model = Model(FOV_input, First_Network_Output)
Second_Model = Model(Stack_input, Second_Network_Output)

# print(First_Model.summary())
# load the weight
if options.input_weight_path:
    First_Model.load_weights(options.input_weight_path[0], by_name=True)
    Second_Model.load_weights(options.input_weight_path[1], by_name=True)

# Complie the model
optimizer = RMSprop(lr=1e-5)