コード例 #1
0
ファイル: test2.py プロジェクト: ziqingye0210/AI-with-Pyke
    def __init__(self):
        """A basic test where Alice can move, take and put and wants to change
        the location of an object.
        Expected result : Alice moves to the item, takes it and moves it."""

        alice = UAgent(
            'Alice',
            ['move', 'take', 'put'],
            [
                ('know', 'Alice', ('location', 'pipo', 0)),
            ],
            [
                ('know', 'Alice', ('location', 'pipo', 1)),
            ],
        )
        pipo = UObject('pipo')

        uni = Universe(2)
        uni.add(alice, 0)
        uni.add(pipo, 1)

        self.agents = [alice]
        self.objects = [pipo]
        self.universe = uni
        self.nb_iteration_max = 4
        self.test_name = 'Test with Alice changing an object\'s position.'
コード例 #2
0
    def __init__(self):
        """A basic test where Alice can only order and wants to move the item.
        Bob can move and take/put items.
        Expected result : Alice orders Bob to move, take the item, move, put
        the item."""
        alice = UAgent('Alice',
                       can_do=['order'],
                       goals=[('know', 'Alice', ('location', 'pipo', 0))],
                       knowledge=[
                           ('know', 'Alice', ('location', 'pipo', 2)),
                           ('know', 'Alice', ('location', 'Bob', 1)),
                           ('know', 'Alice', ('free', 'Bob', True)),
                       ])
        bob = UAgent('Bob', ['move', 'take', 'put'],
                     goals=[],
                     knowledge=[('know', 'Bob', ('location', 'pipo', 2))])

        pipo = UObject('pipo')

        uni = Universe(3)
        uni.add(alice, 0)
        uni.add(bob, 1)
        uni.add(pipo, 2)

        self.agents = [alice, bob]
        self.objects = [pipo]
        self.universe = uni
        self.nb_iteration_max = 6
        self.test_name = 'Test with Alice ordering Bob to move the object.'
コード例 #3
0
ファイル: FirstAttempt.py プロジェクト: Mennovl1/Mod2B
def main():
    MODE = "random"
    fig = plt.figure()
    ax = plt.subplot(111)
    ax.set_title(MODE)

    if MODE == "random":
        N = 3
        stars = []
        randomvals = np.random.rand(N, 6)
        while any(
                any((impossiblepos(val1, val2) and val1 is val2)
                    for val2 in randomvals) for val1 in randomvals):
            randomvals = np.random.rand(N, 4)
            print("apprehended")
        for vals in randomvals:
            mass = 4
            color = np.random.rand(3)
            stars += [
                Star((WIDTH * 0.5 * (vals[0] - 0.5), HEIGHT * 0.5 *
                      (vals[1] - 0.5)), (0.00 * vals[2], 0.00 * vals[3]),
                     mass=mass,
                     facecolor=color)
            ]

    universe = Universe(stars, ax, dt=5e-3, trace=TRACE)
    mov = anim.FuncAnimation(fig,
                             universe.update,
                             frames=100,
                             interval=1000 * universe.dt,
                             blit=True)
    try:
        plt.show()
    except AttributeError:
        print("AtrributeError")
コード例 #4
0
def main():

    debug = Debugger()
    chrono = Chrono()
    universe = Universe(debug)
    source = Source(debug).get_source()
    bucket_chain = BucketChain(debug, chrono, universe, source)
    clusters = Clusters(debug, chrono, universe)
    algorithm = OnlineClustering(debug, universe, bucket_chain, clusters)

    while True:
        operation_time = time.time()
        if bucket_chain.is_updated():
            universe.compute_log_n_df()
            bucket_chain.compute_universal_counts()
            bucket_chain.compute_universal_tfidf()
            clusters.update_centroid_counts()
            clusters.update_centroid_tfidf()
            algorithm.pre_clustering_work()
            algorithm.online_clustering()
            clusters.remove_old_clusters()
            universe.prune_terms(clusters)
            debug.log("BUCKET FINISHED IN: " +
                      str(time.time() - operation_time))
            clusters.debug_active_clusters()
            clusters.save_active_clusters()
コード例 #5
0
ファイル: test6.py プロジェクト: ziqingye0210/AI-with-Pyke
    def __init__(self):
        """A basic test where Alice wants to give the object to Bob.
        Expected result : Alice moves to take the object and gives it to Bob."""
        alice = UAgent( 'Alice',
                        ['move', 'take', 'give'],
                        goals = [('know', 'Alice', ('location', 'pipo', 'Bob'))],
                        knowledge = [
                            ('know', 'Alice', ('location', 'pipo', 2)),
                            ('know', 'Alice', ('location', 'Bob', 1)),
                            ('know', 'Alice', ('free', 'Bob', True)),
                        ]
                )
        bob = UAgent( 'Bob',
                      ['move', 'put'],
                      [('know', 'Bob', ('location', 'pipo', 0))],
                      knowledge = [
                      ]
                )
                      
        pipo = UObject('pipo')

        uni = Universe(3)
        uni.add(alice, 0)
        uni.add(bob, 1)
        uni.add(pipo, 2)

        self.agents = [alice, bob]
        self.objects = [pipo]
        self.universe = uni
        self.nb_iteration_max = 6
        self.test_name = 'Test with Alice giving an object to Bob and Bob putting it somewhere else'
コード例 #6
0
    def __init__(self):
        """A basic test where Alice puts objects in a box."""
        alice = UAgent(
            'Alice', ['move', 'take', 'put', 'place_in_box', 'fetch_from_box'],
            [(('know', 'Alice', ('location', 'pipo', 'pipobox')), ),
             (('know', 'Alice', ('location', 'pipo2', 'pipobox')), )],
            knowledge=[
                ('know', 'Alice', ('location', 'pipo', 1)),
                ('know', 'Alice', ('location', 'pipo2', 1)),
                ('know', 'Alice', ('location', 'pipobox', 2)),
                ('know', 'Alice', ('full', 'pipobox', False)),
            ],
            max_length_plan=9)

        pipo = UObject('pipo')
        pipo2 = UObject('pipo2')
        pipobox = Box('pipobox', 2)

        uni = Universe(3)
        uni.add(alice, 0)
        uni.add(pipo, 1)
        uni.add(pipobox, 2)
        uni.add(pipo2, 1)

        self.agents = [alice]
        self.objects = [pipo, pipo2, pipobox]
        self.universe = uni
        self.nb_iteration_max = 9
        self.test_name = 'Test with Alice putting 2 objects in the box'
コード例 #7
0
def main():
    fraction_malicious = 50
    fraction_exposing = 50

    universe = Universe(30, fraction_malicious, fraction_exposing)
    coordinates = universe.coordinates

    earth = universe.civilizations[0]
    earth.broadcasts = True
    if earth.broadcasts:
        earth.send_broadcast()
        neighbours = universe.find_neighbours(earth)
        for i in range(len(neighbours)):
            print(
                f'{neighbours[i].name} was found. Malicious = {neighbours[i].malicious}'
            )
            if neighbours[i].malicious:
                print(f'{neighbours[i].name} destroys {earth.name}')
            elif neighbours[i].broadcasts:
                print(f'{neighbours[i].name} says, "Hi Neighbour!"')
            else:
                print(f'{neighbours[i].name} remains silent')

    # print(coordinates)
    create_plt(coordinates)
コード例 #8
0
def main():
    print(ss.earth.grav_force(ss.sun))

    dt = 60  # a minute
    simple = [ss.sun, ss.earth]
    u = Universe(dt, simple)
    u.init_velocities()

    print("------------------- init speeds --------------------")
    for o in u.oschis:
        print(o.name, np.linalg.norm(o.velocity))
    print()

    counter = 0
    while u.simulate():

        if counter > (370 * 24 * 60):
            break  # after a year

        if counter % (31 * 24 * 60) == 0:  # each month
            print('')
            for o in u.oschis:
                print(
                    '{:10} | {:15e} {:15e} {:15e} | {:15f} {:15f} {:15f} | {:15e} | {:15f}'
                    .format(o.name, o.position[0], o.position[1],
                            o.position[2], o.velocity[0], o.velocity[1],
                            o.velocity[2], np.linalg.norm(o.position),
                            np.linalg.norm(o.velocity)))
        counter += 1

    print()
    print("------------------- After a Year --------------------")
    print(u.oschis)
コード例 #9
0
    def run(self):
        self._status = SimState.INITIALIZING
        self._report_state()

        stats = Stats()
        universe = Universe(ConfigSimulator.RACES, stats)

        self._status = SimState.RUNNING
        self._report_state()

        while self._status == SimState.RUNNING and universe.pass_time():
            stats.accumulate_step_stats(universe)
            printing.print_step_stats(stats)
            self._report(stats)
            stats.initialize_inter_step_stats()

            if universe.get_time() % ConfigSimulator.LOGGING_BATCH_SIZE == 0:
                stats.accumulate_epoch_stats(universe)
                printing.print_epoch_stats(stats)

        if ConfigSimulator.CSV_LOGGING:
            printing.dataframe2csv(
                stats.step_stats_df,
                ConfigSimulator.CSV_FILE_PATH.format(
                    time.strftime("%Y%m%d-%H%M%S")))

        self._status = SimState.IDLE
        self._report_state()
コード例 #10
0
    def main(self, ndays=10):

        # for test
        import time
        from universe import Universe
        u = Universe(tickers=self._universe, time=self._time)

        for i in range(ndays):

            start_time = time.time()
            time_ = self._time + dt.timedelta(days=1)
            print("On", time_)  #############################
            self.get_data(time_)
            print("data ready, time used:",
                  time.time() - start_time)  ##############################
            start_time = time.time()
            self.scoring(time_)
            print("alpha, time used:", time.time() - start_time)
            print(self._alpha)  ########################################
            if len(self._alpha) == 0:
                print("No alpha on this day")
                continue
            start_time = time.time()
            u.updatingPool(time_, self.selection())
            print("selection done, time used:",
                  time.time() - start_time)  #####################
            start_time = time.time()
            u.evaluation()
            print("evaluation done, time used:",
                  time.time() - start_time)  #####################

        return u._networth
コード例 #11
0
    def test_center_of_mass(self):
        sun = Oschi("Sun", (0, 0, 0), 1, (0, 0, 0), 0.2)
        earth = Oschi("Earth", (1, 1, 1), 27 * 10**11, (0, 0, 0), 0.1)

        universe = Universe(60, [sun, earth])

        u = universe.center_of_mass(earth)
        self.assertTrue((universe.center_of_mass(earth) == (0, 0, 0)).all())
コード例 #12
0
def test_single_agent():
    print("### test_single_agent() ###")
    universe = Universe(1, 5, 0.0, debug=False)
    counter = 0
    while not universe.is_finished():
        universe.update()
        counter += 1
    assert counter == 0
コード例 #13
0
def initialize():
    dt = 60*60*24*7  # a minute
    # simple = [ss.sun, ss.earth, ss.mars]
    simple = [ss.sun, ss.mercury, ss.venus, ss.earth, ss.mars, ss.jupiter, ss.saturn, ss.uranus, ss.neptune]
    u = Universe(dt, simple)
    #u.init_velocities()

    return u
コード例 #14
0
    def __init__(self):
        pg.init()
        pg.display.set_caption("gravity")
        self.win = pg.display.set_mode((WIDTH, HEIGHT))
        self.clock = pg.time.Clock()
        self.running = True

        self.universe = Universe()
コード例 #15
0
 def generateUniverses(self):
     result = []
     for assignment in next_permutation(
             sorted(expandrolelist(self.rolelist))):
         assignedroles = dict(zip(self.players, assignment))
         result.append(Universe(assignedroles, self))
     numUniverses = int(self.toKeep * len(result))
     filteredUniverses = random.sample(result, numUniverses)
     return filteredUniverses
コード例 #16
0
 def start_game(self, name, skill_points, credit):
     self.universe = Universe()
     rand_int = random.randint(0, len(self.universe.region_list) - 1)
     self.player = Player(name, skill_points, credit,
                          self.universe.region_list[rand_int])
     self.net_worth_data.append(self.player.credit)
     self.universe.insert_win(self.player.name)
     utility.bprice_calc(self.player, self.player.curr_region)
     utility.sprice_calc(self.player, self.player.curr_region)
コード例 #17
0
 def __init__(self):
     self.agents = []
     self.objects = []
     self.universe = Universe(1)
     # nb_iteration_max is here to refrain some cases to computer for
     # too long...
     self.nb_iteration_max = 1
     self.test_name = 'default_test_name'
     self.finished = False
コード例 #18
0
def test_two_agents():
    print("### test_two_agents() ###")
    universe = Universe(2, 5, 0.0, debug=False)
    stats = Statistics()
    counter = 0
    while not universe.is_finished():
        universe.update(stats)
        counter += 1

    assert counter <= 10
コード例 #19
0
def main():
    a = Body((DIST, 0, 0), (0, VEL, 0), mass=M, color=(0.8, 0.8, 1))
    b = Body((-DIST, 0, 0), (0, -VEL, 0), mass=M, color=(1, 0.8, 0.8))
    bodies = [a, b]
    universe = Universe(bodies, G=G, dt=DT)
    #universe.draw()
    #print(universe.bodyList)
    while True:
        #(universe.bodyList)
        universe.update()
コード例 #20
0
    def __init__(self,
                 actions: List[int],
                 figure: Figure,
                 runtime: float = 8.6,
                 fps: float = 1.0 / 30):

        self.actions = actions
        self.universe = Universe()
        self.universe.add_figure(figure)
        self.runtime = runtime
        self.fps = fps
コード例 #21
0
def main():
    pg.init()
    screen = pg.display.set_mode([900, 600])
    screen_rect = screen.get_rect()
    screen.fill(BLACK)
    clock = pg.time.Clock()

    u = Universe()

    for i in range(10000):
        BGStar(u)


    e = {
        "rot speed": 360,
        "fly speed": 1000,
        "acceleration": 300,
        "dec": 1.0,
        "shot delay": 0.0,
        "hp": 100,
        "laser color": CYAN,
        "shot spread": 2,
        "shields": 0
    }

    f = PlayerFighter(u, vec(450, 300), e, WHITE)
    u.focus = f

    for i in range(4):
        enemy = AIFighter(u, vec(1000 * i, 0), e, RED)
        # ally = AIFighter(u, vec(1000 * i, 1000 * i), 0)
        # ally.color = GREEN

    t = 0

    while True:
        dt = clock.tick(60) / 1000.0
        t += dt
        evts = pg.event.get()
        for evt in evts:
            if evt.type == QUIT:
                pg.quit()
                sys.exit()

        u.update(dt, t)

        screen.fill(BLACK)
        for b in u.bodies:
            b.draw(screen)
        for p in u.particles:
            if screen_rect.collidepoint(u.get_render_point(p.pos, p.parallax)):
                p.draw(screen)
        pg.display.flip()
コード例 #22
0
 def universe_mv_create(self):
     """
     Create model and view for a universe
     """
     if debug:
         print('create model and view for universe')
     # create the universe model
     self.universe = Universe(self)
     # create the patch model and view
     self.create_settings()
     self.view_patch.setVisible(True)
     self.view_patch.setEnabled(True)
コード例 #23
0
ファイル: game.py プロジェクト: leyanpan/SpaceTrader
 def start_game(self, name, skills):
     names = np.random.choice(LISTOFNAMES, size=10, replace=False)
     x_s = Game.generate_random_sequence(REGION_NUM)
     y_s = Game.generate_random_sequence(REGION_NUM)
     regions = []
     self.name_region = {}
     for i in range(10):
         self.name_region[names[i]] = Region((x_s[i], y_s[i]), names[i])
         regions.append(self.name_region[names[i]])
     self.universe = Universe(regions)
     ship = Ship(np.random.choice(self.universe.regions), MAX_FUEL)
     self.player = Player(name, skills, ship)
コード例 #24
0
ファイル: display.py プロジェクト: lukasgarbas/ga-jump
 def __init__(
     self, actions: List[int], figure: Figure, label: Text = '', runtime: float = 8.2
     ):
     super().__init__(width=1000, height=400, caption='Jumping over the ball', resizable=False)
     self.actions = actions 
     self.universe = Universe()
     self.universe.add_figure(figure)
     self.current_action = 1
     self.current_time = 0.0
     self.fps = 1.0/30
     self.add_label(label)
     self.runtime = runtime
コード例 #25
0
def parse_options():
	parser = OptionParser()
	parser.add_option("-f", "--file",
                  help="Read and update file")
	parser.add_option("-d", "--date",
                  help="Enter date in format yyyy-m-d")
	parser.add_option("-l", "--lookback",
                  help="Enter date lookback example 5d, 1Y", default="2d")
	parser.add_option("-a", "--archive",
                  help="Enter archive location", default=Universe().get_archives_location())

	return parser.parse_args()
コード例 #26
0
def main():
    size = 100

    # HEADS UP! Enabling vsync on Linux will cause the app to freeze.
    window = pyglet.window.Window(width=size * 8, height=size * 8, vsync=False)

    universe = Universe(size, CONTENDERS)
    event_loop = asyncio.get_event_loop()
    event_loop.call_soon(run_pyglet, event_loop)
    event_loop.call_soon(universe_tick, universe, event_loop, window)
    event_loop.run_forever()
    event_loop.close()
コード例 #27
0
def test_simulation_run():
    print("### test_simulation_run() ###")
    universe = Universe(2, 5, 0.4, debug=True)
    stats = Statistics()
    print("Start:")
    print_environment(universe)
    print("Agent stats:")
    for agent in universe.agents:
        agent.print_stats()

    while not universe.is_finished():
        universe.update(stats)
        print_environment(universe)
コード例 #28
0
ファイル: app.py プロジェクト: rithikgavvala/spacetrader-web
def add_player():
    print(request.form.to_dict())
    playerDict = request.form.to_dict()
    isValid = True
    sum = 0
    for key, value in playerDict.items():
        print(sum)

        if value == '':
            flash('Name is empty')
            isValid = False

        if key == 'pilot':
            sum += int(value)

        elif key == 'fighter':
            sum += int(value)

        elif key == 'trader':
            sum += int(value)

        elif key == 'engineer':
            sum += int(value)

    if sum != 16:
        flash('Skills must add to 16')
        isValid = False

    #print(playerDict)

    if isValid is True:
        playerDict['spaceship'] = 'gnat'
        playerDict['credits'] = 1000
        u = Universe()
        universe = u.makeUniverse()
        playerDict['universe'] = universe

        db.users.insert_one(playerDict)
        # p = db.users.find_one({})
        player = Player()

        print(universe)
        player.setPlayer(playerDict['name'], playerDict['pilot'],
                         playerDict['fighter'], playerDict['trader'],
                         playerDict['engineer'], playerDict['difficulty'],
                         playerDict['spaceship'], playerDict['credits'],
                         playerDict['universe'])

        return "Success!"
    else:
        return "Try again!"
コード例 #29
0
    def __init__(self):

        self.screen = Screen()
        self.window = pygame.display.set_mode(
            (self.screen.width, self.screen.height))
        self.universe = Universe(self.window, 10, 10)
        self.population_record = 0
        self.hungry_deaths = 0
        self.age_deaths = 0
        self.food_wait = 10
        self.extinction = False

        pygame.display.set_caption("Evolution")
        pygame.init()
コード例 #30
0
ファイル: test0.py プロジェクト: ziqingye0210/AI-with-Pyke
    def __init__(self):
        """ Trivial test
        Alice is at location 0, can move, and wants herself to be in location 1.
        Expected result : Alice moves from 0 to 1."""
        alice = UAgent('Alice', ['move'],
                       [('know', 'Alice', ('location', 'Alice', 1))])

        uni = Universe(2)
        uni.add(alice, 0)

        self.agents = [alice]
        self.objects = []
        self.universe = uni
        self.nb_iteration_max = 2
        self.test_name = 'Test of the move action.'