def test_part_two(self):
        "Test part two example of Swarm object"

        # 1. Create Spinlock object from text
        myobj = swarm.Swarm(part2=True, text=aoc_20.from_text(PART_TWO_TEXT))

        # 2. Check the part two
        self.assertEqual(myobj.part_two(verbose=True), PART_TWO_RESULT)
    def test_part_one(self):
        "Test part one example of Swarm object"

        # 1. Create Spinlock object from text
        myobj = swarm.Swarm(text=aoc_20.from_text(PART_ONE_TEXT))

        # 2. Check the part one result
        self.assertEqual(myobj.part_one(verbose=True), PART_ONE_RESULT)
Example #3
0
def main():

    parser = argparse.ArgumentParser(description='Run PSO on a benchmark')
    parser.add_argument('--pop',
                        default=120,
                        type=int,
                        help='swarm population size')
    # parser.add_argument('--d', default=2, type=int,
    #                     help='solution dimension size')
    parser.add_argument('--c',
                        default=2.0,
                        type=float,
                        help='particle acceration constant')
    parser.add_argument('--err_crit',
                        default=0.0000000001,
                        type=float,
                        help='error criteria for stopping PSO')
    parser.add_argument('--iter_max',
                        default=10000,
                        type=float,
                        help='maximum iterations for stopping PSO')
    parser.add_argument('--data',
                        required=True,
                        type=str,
                        help='required data csv')
    args = parser.parse_args()

    data = []
    with open(args.data, 'rb') as csvfile:
        reader = csv.reader(csvfile)
        for index, row in enumerate(reader):
            if index == 0:
                continue
            row = [float(i) for i in row]
            data.append(row)

    input_nodes = 2

    # func = nn.NodeMap().evaluate
    # func = benchmark.Benchmark().f6
    n1 = nn.NodeMap(input_node_population=input_nodes,
                    latent_node_population=10)
    n1.construct_map()

    d = n1.calculate_dimensions()

    func = n1.train

    sw = swarm.Swarm(population_size=args.pop, \
                        dimensions=d, c1=args.c, c2=args.c)

    pso = swarm.PSO(iter_max=args.iter_max, err_crit=args.err_crit)

    pso.optimize(func, sw, data)
Example #4
0
def initializeKernelBias5Fold(st):
    #Swarm intelligence to get initial weights and biases
    print("Weights and biases initialization in progress...")
    initializer = sm.Swarm([x_size, hidden, y_size], sm.Activation.relu)
    initializer.cso(100, x_batches[st][:, 0].reshape(x_size, 1),
                    y_batches[st][:, 0].reshape(y_size, 1),
                    initializer.multiObjectiveFunction, -0.6, 0.6,
                    initializer.dim, 100)

    initializer.set_weight_bias(np.array(initializer.get_Gbest()))

    fname = "kernelBias5Fold" + st + ".npy"
    np.save(fname, [initializer.weights, initializer.biases])
Example #5
0
def part_two(args, input_lines):
    "Process part two of the puzzle"

    # 1. Create the puzzle solver
    solver = swarm.Swarm(part2=True, text=input_lines)

    # 2. Determine the solution for part two
    solution = solver.part_two(verbose=args.verbose)
    if solution is None:
        print("There is no solution")
    else:
        print("The solution for part two is %s" % (solution))

    # 3. Return result
    return solution is not None
    def test_empty_init(self):
        "Test the default Swarm creation"

        # 1. Create default Swarm object
        myobj = swarm.Swarm()

        # 2. Make sure it has the default values
        self.assertEqual(myobj.part2, False)
        self.assertEqual(myobj.text, None)
        self.assertEqual(len(myobj.particles), 0)
        self.assertEqual(myobj.clock, 0)

        # 3. Test methods
        myobj.tick()
        self.assertEqual(myobj.clock, 1)
        self.assertEqual(myobj.closest(), None)
    def test_text_init(self):
        "Test the Swarm object creation from text"

        # 1. Create Swarm object from text
        myobj = swarm.Swarm(text=aoc_20.from_text(EXAMPLE_TEXT))

        # 2. Make sure it has the expected values
        self.assertEqual(myobj.part2, False)
        self.assertEqual(len(myobj.text), 2)
        self.assertEqual(len(myobj.particles), 2)
        self.assertEqual(myobj.clock, 0)
        self.assertEqual(myobj.particles[0].position, (3, 0, 0))
        self.assertEqual(myobj.particles[0].velocity, (2, 0, 0))
        self.assertEqual(myobj.particles[0].acceleration, (-1, 0, 0))
        self.assertEqual(myobj.particles[1].position, (4, 0, 0))
        self.assertEqual(myobj.particles[1].velocity, (0, 0, 0))
        self.assertEqual(myobj.particles[1].acceleration, (-2, 0, 0))

        # 3. Test methods
        self.assertEqual(myobj.closest(), 0)
        myobj.tick()
        self.assertEqual(myobj.clock, 1)
        self.assertEqual(myobj.particles[0].position, (4, 0, 0))
        self.assertEqual(myobj.particles[0].velocity, (1, 0, 0))
        self.assertEqual(myobj.particles[0].acceleration, (-1, 0, 0))
        self.assertEqual(myobj.particles[1].position, (2, 0, 0))
        self.assertEqual(myobj.particles[1].velocity, (-2, 0, 0))
        self.assertEqual(myobj.particles[1].acceleration, (-2, 0, 0))
        self.assertEqual(myobj.closest(), 1)
        myobj.tick()
        self.assertEqual(myobj.clock, 2)
        self.assertEqual(myobj.particles[0].position, (4, 0, 0))
        self.assertEqual(myobj.particles[0].velocity, (0, 0, 0))
        self.assertEqual(myobj.particles[0].acceleration, (-1, 0, 0))
        self.assertEqual(myobj.particles[1].position, (-2, 0, 0))
        self.assertEqual(myobj.particles[1].velocity, (-4, 0, 0))
        self.assertEqual(myobj.particles[1].acceleration, (-2, 0, 0))
        self.assertEqual(myobj.closest(), 1)
        myobj.tick()
        self.assertEqual(myobj.clock, 3)
        self.assertEqual(myobj.particles[0].position, (3, 0, 0))
        self.assertEqual(myobj.particles[0].velocity, (-1, 0, 0))
        self.assertEqual(myobj.particles[0].acceleration, (-1, 0, 0))
        self.assertEqual(myobj.particles[1].position, (-8, 0, 0))
        self.assertEqual(myobj.particles[1].velocity, (-6, 0, 0))
        self.assertEqual(myobj.particles[1].acceleration, (-2, 0, 0))
        self.assertEqual(myobj.closest(), 0)
Example #8
0
    def __init__(self, size):
        self.size = size

        self.elapsed = 0
        self.swarm = swarm.Swarm(swarm.Swarm.Params())
        self.last_update_time = time.monotonic()
        self.poses = np.zeros((1, self.swarm.params.size, 3), dtype=np.float32)
        self.ages = np.zeros((1, self.swarm.params.size), dtype=np.float32)

        self.pprogram = particles.PProgram(
            gfx.perspectiveM(math.tau / 8, self.size[0] / self.size[1],
                             0.1, 100),
            gfx.lookatM([5, 2, 5], [0, 0, 0], [0, 1, 0]))

        self.fbo = gllib.framebuffer.Framebuffer(size)
        self.fsquad = gllib.fsquad.FSQuad()

        #		GL.glPointSize(1)
        GL.glClearColor(0., 0., 0., 1.)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
def Swarm_Formations():
    # Set goals to go to
    FORMATIONS = json.load(open('quad_sim/formations.json'))
    # Define the quadcopters
    QUADCOPTERS = json.load(open('quad_sim/quadcopters.json'))
    # Controller parameters
    CONTROLLER_PARAMETERS = {
        'Motor_limits': [4000, 9000],
        'Tilt_limits': [-10, 10],
        'Yaw_Control_Limits': [-900, 900],
        'Z_XY_offset': 500,
        'Linear_PID': {
            'P': [300, 300, 7000],
            'I': [0.04, 0.04, 4.5],
            'D': [450, 450, 5000]
        },
        'Linear_To_Angular_Scaler': [1, 1, 0],
        'Yaw_Rate_Scaler': 0.18,
        'Angular_PID': {
            'P': [22000, 22000, 1500],
            'I': [0, 0, 1.2],
            'D': [12000, 12000, 0]
        },
    }
    # Create controller parameters for each quadcopter
    ctrl_params = [CONTROLLER_PARAMETERS.copy() for q in QUADCOPTERS]
    # Catch Ctrl+C to stop threads
    signal.signal(signal.SIGINT, signal_handler)
    # Make objects for quadcopter, gui and controllers
    s = swarm.Swarm(drones=QUADCOPTERS)
    gui_object = swarm_gui.GUI(drones=QUADCOPTERS, swarm=s)
    controllers = [
        controller.Controller_PID_Point2Point( \
            s.get_state, \
            s.get_time, \
            s.set_motor_speeds, \
            params=param, \
            quad_identifier=q) \
        for q,param in zip(QUADCOPTERS, ctrl_params)
    ]
    # ctrl1 = controller.Controller_PID_Point2Point(s.get_state,s.get_time,s.set_motor_speeds,params=CONTROLLER_1_PARAMETERS,quad_identifier='q1')
    # ctrl2 = controller.Controller_PID_Point2Point(s.get_state,s.get_time,s.set_motor_speeds,params=CONTROLLER_2_PARAMETERS,quad_identifier='q2')
    # Start the threads
    s.start_threads(dt=QUAD_DYNAMICS_UPDATE, time_scaling=TIME_SCALING)
    for ctrl in controllers:
        ctrl.start_thread(update_rate=CONTROLLER_DYNAMICS_UPDATE,
                          time_scaling=TIME_SCALING)
    # Update the GUI while switching between destination poitions
    while (run == True):
        key = input(
            "Which formation would you like to make?\noptions: {}\n:".format(
                [str(key) for key in FORMATIONS.keys()]))
        while key not in FORMATIONS.keys():
            key = input(
                "Did not recognize input. Please select an option below...\noptions: {}\n:"
                .format([str(key) for key in FORMATIONS.keys()]))

        # TODO: Write a smart algorithm to set targets of nearest drones
        for q, ctrl in zip(QUADCOPTERS, controllers):
            ctrl.update_target(tuple(FORMATIONS[key][q]))

        # TODO: Rewrite gui updates to make them more smooth
        gui_object.animate()
        # for i in range(300):
        #     for key in QUADCOPTERS:
        #         gui_object.drones[key]['position'] = s.get_position(key)
        #         gui_object.drones[key]['orientation'] = s.get_orientation(key)
        #     gui_object.update()
    s.stop_threads()
    for ctrl in controllers:
        ctrl.stop_thread()
Example #10
0
    def setUp(self):
        super(TestSwarm, self).setUp()

        self.swarm = swarm.Swarm()
        self.swarm.setConnectionPool(self.getConnectionPool())
Example #11
0
def get_malko_architecture(projectDB, expDB, nPosts, df, fetched, angles):
    # establish a connecttion to the project database
    conn = sqlite3.connect(projectDB)
    # connect a cursor that goes through the project database
    cursorProject = conn.cursor()
    # establish a second connecttion to the experiment database
    conn2 = sqlite3.connect(expDB)
    # connect a cursor that goes through the experiment database
    cursorExperiment = conn2.cursor()

    x = df[['rotated_x', 'rotated_y']].values
    x = np.c_[x, x[:, 0] * 0]
    x_Post0 = df[['rotated_post0_x', 'rotated_post0_y']].values
    x_Post0 = np.c_[x_Post0, x_Post0[:, 0] * 0]
    x_Post1 = df[['rotated_post1_x', 'rotated_post1_y']].values
    x_Post1 = np.c_[x_Post1, x_Post1[:, 0] * 0]
    if nPosts == 3:
        x_Post2 = df[['rotated_post2_x', 'rotated_post2_y']].values
        x_Post2 = np.c_[x_Post2, x_Post2[:, 0] * 0]
    t = df['t'].values
    uuids = df['uuid'].values
    nStimuli = df['nStimuli'].values
    events = df['event'].values
    print(x.shape)

    massive_experiment = swarm.Swarm()
    for i in range(0, len(angles) + 2):
        massive_experiment.addFish(swarm.Swarm())

    for uuid in range(0, len(fetched)):
        cursorExperiment.execute("Select exp from experiments where expID = ?",
                                 (fetched[uuid][0], ))
        exp = cursorExperiment.fetchall()
        nStim = len(np.unique(df.loc[df['uuid'] == uuid, 'nStimuli']))
        for n in range(0, nStim):
            stimuli = swarm.Swarm()
            nEvents = len(
                np.unique(df.loc[(df['uuid'] == uuid) & (df['nStimuli'] == n),
                                 'event']))
            for e in range(0, nEvents):
                event = swarm.Swarm()
                idx = np.where((uuids == uuid) & (nStimuli == n)
                               & (events == e))[0]
                if len(idx) > 30:
                    event.addFish(
                        swarm.Fish(x,
                                   t,
                                   idx=idx,
                                   burst=False,
                                   fishId=0,
                                   virtual=False))
                    event.addFish(
                        swarm.Fish(x_Post0,
                                   t,
                                   idx=idx,
                                   burst=False,
                                   fishId=1,
                                   virtual=True))
                    if n != 0 and n != np.max(nStimuli):
                        event.addFish(
                            swarm.Fish(x_Post1,
                                       t,
                                       idx=idx,
                                       burst=False,
                                       fishId=2,
                                       virtual=True))
                        if nPosts > 2:
                            event.addFish(
                                swarm.Fish(x_Post2,
                                           t,
                                           idx=idx,
                                           burst=False,
                                           fishId=3,
                                           virtual=True))
                    event.fishReferential()
                    stimuli.addFish(event)
            if n == 0:
                massive_experiment.swarm[n].addFish(stimuli)
            elif n == np.max(nStimuli):
                massive_experiment.swarm[len(angles) + 1].addFish(stimuli)
            else:
                cursorExperiment.execute(
                    "Select replicate from experiments where expID = ?",
                    (fetched[uuid][0], ))
                rep = cursorExperiment.fetchall()
                cursorProject.execute(
                    "Select post1 from projects where project = ? and exp = ? and replicate = ? and nStimuli = ?",
                    ('DecisionGeometry', exp[0][0], rep[0][0], n))
                post = cursorProject.fetchall()
                s_number = np.where(angles == eval(post[0][0])['angle'])[0][0]
                massive_experiment.swarm[s_number + 1].addFish(stimuli)

    for i in range(0, len(angles) + 2):
        massive_experiment.swarm[i].fillMetaFish()

    return massive_experiment
Example #12
0
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import swarm

s1 = swarm.Swarm(3)

fig, ax = plt.subplots()

for fly in s1.fireflies:
    print(fly.id_num)

duration = 100

for time in range(duration):
    s1.chargeIteration()
    s1.flashPropogationLoop()

s1.plotFlashData(ax, 0)
s1.plotFlashData(ax, 1)
s1.plotFlashData(ax, 2)

plt.show()
Example #13
0
	
	authmgr = Auth(conf['salt'])
	authmgr.setConnectionPool(connPool)
	
	torrents = TorrentStore(conf['trackerUrl'])
	torrents.setConnectionPool(connPool)
		
	httpListenIp = conf['webapi'].get('ip',DEFAULT_LISTEN_IP)
	httpListenPort = conf['webapi'].get('port',DEFAULT_LISTEN_PORT)
	httpPathDepth = conf.get('pathDepth',DEFAULT_PATH_DEPTH)

	users = Users(conf['salt'])
	users.setConnectionPool(connPool)
	
	redisConnPool = vanilla.buildRedisConnectionPool(**conf['redis'])
	
	#Pass in zero and do not spawn the thread associated with the Peers
	#object. It is not needed in this process as it runs in the tracker
	#process.
	peerList = peers.Peers(redisConnPool,0)
	
	swarmConnPool = vanilla.buildConnectionPool(psycopg2,**conf['webapi']['postgresql'])
	swarm = swarm.Swarm()
	swarm.setConnectionPool(swarmConnPool)
	
	webapi = Webapi(swarm,peerList,users,authmgr,torrents,httpPathDepth,conf['webapi']['secure'])
	
	users.createRoles(webapi.getRoles())
	
	wsgi.server(eventlet.listen((httpListenIp, httpListenPort)), webapi)