Exemplo n.º 1
0
 def test_small_fetch(self):
     system = System()
     system.memory = [0xDA, 0xBF]
     cpu = C8cpu(False)
     opcode = cpu.fetch(system)
     self.assertEqual(opcode, 0xBFDA)
     self.assertEqual(system.pc, 2)
Exemplo n.º 2
0
def main():
    
    sun = Body(SUN_MASS, 0, 0, 0, 0, 24, 1, 1, 0,)                           # Yellow Sun
    earth = Body(EARTH_MASS, SUN_EARTH, 0, 0, 30000, 8, 0, 0, 1)            # blue earth
    mercury = Body(MERCURY_MASS, SUN_MERCURY, 0, 0, 48000, 3, 1, 0.6, 0)    # Brown Mercury
    venus = Body(VENUS_MASS, SUN_VENUS, 0, 0, 35000, 6.5, 0, 1, 0)          # Green Venus
    mars = Body(MARS_MASS, SUN_MARS, 0, 0, 24000, 5, 1, 0, 0)               # Red Mars
    
    solar = System([sun, mercury, venus, earth, mars])                      # Create the system
    
    set_clear_color(0, 0, 0)    # black background
    enable_smoothing()

    while not window_closed(): 
        clear()
        
        
        # Draw the system in its current state.
        solar.draw(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, PIXELS_PER_METER)
    
        # Update the system for its next state.
        solar.update(TIMESTEP * TIME_SCALE)
    
        # Draw the frame and take a brief nap.
        request_redraw()
        sleep(TIMESTEP)
Exemplo n.º 3
0
 def test_ShouldMoveAtConstantVelocitySingleMovingBody(self):
     body = CelestialBody("N", 1e25, self.zero, Vector(10, 15, 50),
                          self.zero)
     system = System("Single Body", [body])
     system.update(10)
     self.assertTrue(body.velocity == Vector(10, 15, 50))
     self.assertTrue(body.position == Vector(100, 150, 500))
def generate_planet(name, type='random', color='random', rings='random'):

    # color ------------------------------------------------------------------------
    if color == 'random':
        rgb_color = random.choice(planet_colors)
    else:
        rgb_color = color

    # size --------------------------------------------------------------------------

    if type == 'random':
        type, size_limits = random.choice(list(planet_types.items()))
        planet_size = random.uniform(size_limits[0], size_limits[1])
    else:
        planet_size = random.uniform(planet_types[type][0],
                                     planet_types[type][1])

    # rings -------------------------------------------------------------------------

    rings_size = 0
    rings_color = random.choice([(110, 99, 77), (45, 200, 200)])
    if rings == 'random':
        if random.choice(list(range(0, 10))) == 0:  # 10% change rings
            rings_size = random.uniform(1.25 * planet_size, 3 * planet_size)
    else:
        rings_size = rings

    return System(name, 0, 0, planet_size * ER, rgb_color, rings_size * ER,
                  rings_color, [])
Exemplo n.º 5
0
    def prepare(self):
        """
            prepare new root system suitable to create an initrd from it
        """
        self.__load_boot_xml_description()
        boot_image_name = self.boot_xml_state.xml_data.get_name()

        self.__import_system_description_elements()

        log.info('Preparing boot image')
        system = System(xml_state=self.boot_xml_state,
                        root_dir=self.boot_root_directory,
                        allow_existing=True)
        manager = system.setup_repositories()
        system.install_bootstrap(manager)
        system.install_system(manager)

        profile = Profile(self.boot_xml_state)
        profile.add('kiwi_initrdname', boot_image_name)

        defaults = Defaults()
        defaults.to_profile(profile)

        setup = SystemSetup(self.boot_xml_state,
                            self.__boot_description_directory(),
                            self.boot_root_directory)
        setup.import_shell_environment(profile)
        setup.import_description()
        setup.import_overlay_files(follow_links=True)
        setup.call_config_script()

        system.pinch_system(manager=manager, force=True)

        setup.call_image_script()
        setup.create_init_link_from_linuxrc()
Exemplo n.º 6
0
    def create(cls,
               agent,
               antennas=10,
               limit_time=40000,
               seed=0,
               verbose=False):
        """Función para crear un ambiente completo

        Args:
            agent (string | Agent): Simulation agent
            antennas (int, optional): Number of antennas. Defaults to 10.
            limit_time (int, optional): Simulation limit time. Defaults to 40000.
            seed (int, optional): Seed of random generator. Defaults to 0.
            verbose (bool, optional): Verbose mode. Defaults to False.

        Returns:
            Environment
        """
        sys = System(antennas=antennas, seed=seed)
        if isinstance(agent, str):
            if agent == 'dsatur':
                _agent = DSaturAgent(sys.get_antennas())
            elif agent == 'naive':
                _agent = NaiveAgent(sys.get_antennas())
            elif agent == 'dummy':
                _agent = DummyAgent(sys.get_antennas())
        else:
            _agent = agent(sys.get_antennas())
        return cls(sys, _agent, limit_time=limit_time, verbose=verbose)
Exemplo n.º 7
0
def test_chocolate_sizes(inventory_fixture, ingredient_cost_fixture):
    system1 = System(inventory_fixture, ingredient_cost_fixture)
    assert (isinstance(system1, System))
    inventory_fixture["chocolate sundae"] = 10000
    orig = inventory_fixture["chocolate sundae"]
    order1 = system1.Create_Order()
    sun = order1.Create_Item("chocolate sundae")
    sun.Size = "small"
    order1.Add_To_Order(sun)
    assert (inventory_fixture["chocolate sundae"] == orig - 200)
    assert (order1.Calculate_Cost() == 4)
    inventory_fixture["chocolate sundae"] = 10000
    orig = inventory_fixture["chocolate sundae"]

    sun2 = order1.Create_Item("chocolate sundae")
    sun2.Size = "medium"
    order1.Add_To_Order(sun2)
    assert (inventory_fixture["chocolate sundae"] == orig - 400)
    assert (order1.Calculate_Cost() == 10)
    inventory_fixture["chocolate sundae"] = 10000
    orig = inventory_fixture["chocolate sundae"]

    sun3 = order1.Create_Item("chocolate sundae")
    sun3.Size = "large"
    order1.Add_To_Order(sun3)
    assert (inventory_fixture["chocolate sundae"] == orig - 600)
    assert (order1.Calculate_Cost() == 21)
Exemplo n.º 8
0
    def __init__(self):
        from codec import Codec
        from window import Window
        from system import System
        from datajar import DataJar
        from filesystem import FileSystem

        try:
            manifest = json.load(codecs.open('manifest.json', 'r', 'utf-8'))
        except:
            manifest = {}

        for key in assets.manifest:
            if key in manifest:
                assets.manifest[key] = manifest[key]

        self.app = QApplication(sys.argv)
        self.app.setApplicationName(assets.manifest['name'])
        self.app.setApplicationVersion(assets.manifest['version'])

        assets.sys = System()
        assets.codec = Codec()
        assets.fs = FileSystem()
        assets.dataJar = DataJar()

        translator = QTranslator()
        if translator.load("zh_CN.qm"):
            self.app.installTranslator(translator)

        self.window = Window(None, assets.manifest['path'] + 'index.html')

        sys.exit(self.app.exec_())
Exemplo n.º 9
0
def test_2ndOrderID(inventory_fixture, ingredient_cost_fixture):
    system1 = System(inventory_fixture, ingredient_cost_fixture)
    assert (isinstance(system1, System))
    order1 = system1.Create_Order()
    burg1 = order1.Create_Item("Burger")
    burg1.Bun_Type = "white"
    burg1.Add_Bun()
    burg1.Add_Bun()
    burg1.Patty_Type = "beef"
    burg1.Add_Patty()
    burg1.Add_Other("cheese")
    order1.Add_To_Order(burg1)
    assert (burg1 in order1.Items)
    system1.Submit_Order(order1)
    assert (order1.ID == 0)
    order2 = system1.Create_Order()
    burg2 = order2.Create_Item("Burger")
    burg2.Bun_Type = "white"
    burg2.Add_Bun()
    burg2.Add_Bun()
    burg2.Patty_Type = "beef"
    burg2.Add_Patty()
    burg2.Add_Other("cheese")
    order2.Add_To_Order(burg1)
    system1.Submit_Order(order2)
    assert (order2.ID == 1)
Exemplo n.º 10
0
 def test_big_fetch(self):
     system = System()
     system.memory = [0xDA, 0xBF]
     cpu = C8cpu()
     opcode = cpu.fetch(system)
     self.assertEqual(opcode, 0xDABF)
     self.assertEqual(system.pc, 2)
Exemplo n.º 11
0
 def test_flow_return(self):
     system = System()
     cpu = C8cpu()
     opcode = 0x8ABD
     system.stack.append(cpu.get_address(opcode))
     cpu.flow_return(0x00EE, system)
     self.assertEqual(system.pc, 0xABD)
Exemplo n.º 12
0
 def test_bit_op_xor(self):
     system = System()
     cpu = C8cpu()
     opcode = 0x8433
     system.registers[3] = 0x44
     cpu.bit_op_xor(opcode, system)
     self.assertEqual(system.registers[4], 0x44)
Exemplo n.º 13
0
 def test_assign_reg(self):
     system = System()
     cpu = C8cpu()
     opcode = 0x8430
     system.registers[3] = 0x77
     cpu.assign_reg(opcode, system)
     self.assertEqual(system.registers[3], system.registers[4])
Exemplo n.º 14
0
 def test_add_val_const(self):
     system = System()
     cpu = C8cpu()
     opcode = 0x7437
     system.registers[4] = 0x11
     cpu.add_val_const(opcode, system)
     self.assertEqual(system.registers[4], 0x48)
Exemplo n.º 15
0
def test_system_derivative_psi_term_3d():
    num_particles = 1
    num_dimensions = 3
    alpha = 1.0
    beta = 1.0
    a = 0.0
    s = System(num_particles, num_dimensions, alpha, beta, a)
    positions = np.zeros(shape=(num_particles, num_dimensions))

    for _ in range(50):
        alpha = np.random.uniform(1e-3, 10)
        beta = np.random.uniform(1e-3, 10)
        s.alpha = alpha
        s.beta = beta

        x = np.random.uniform(-20, 20)
        y = np.random.uniform(-20, 20)
        z = np.random.uniform(-20, 20)

        positions[0, 0] = x
        positions[0, 1] = y
        positions[0, 2] = z
        wf = s.derivative_psi_term(positions)

        assert wf == pytest.approx((-x**2 - y**2 - beta * z**2), abs=1e-12)
Exemplo n.º 16
0
def generate_xml(stat_file, config_file, out_file, **kwargs):
    def prettify(elem):
        """Return a pretty-printed XML string for the
    Element.  """
        rough_string = ElementTree.tostring(elem, 'utf-8')
        reparsed = minidom.parseString(rough_string)
        return reparsed.toprettyxml(indent="  ")

    # Parse & build the context dictionaries:
    stat_dict = build_gem5_stat_dict(stat_file)
    config_dict = build_gem5_config_dict(config_file)
    sim_dict = build_gem5_sim_dict(**kwargs)

    ruby = False
    if "system.ruby.clk_domain.clock" in config_dict:
        ruby = True

    # Build the system
    s = System("system", "system", stat_dict, config_dict, sim_dict, ruby)

    root = ElementTree.Element('component', id='root', name='root')
    root.append(s.xml())

    # write the XML
    with open(out_file, "w") as of:
        of.write(prettify(root))

    return 0
Exemplo n.º 17
0
def test_system_wavefunction_2d():
    num_particles = 1
    num_dimensions = 2
    alpha = 1.0
    beta = 1.0
    a = 0.0
    s = System(num_particles, num_dimensions, alpha, beta, a)
    positions = np.zeros(shape=(num_particles, num_dimensions))
    x = 2.92858925782756
    y = 0.00925285752985
    positions[0, 0] = x
    positions[0, 1] = y

    wf = s.single_particle_function(positions)
    assert wf == pytest.approx(np.exp(-x**2 - y**2), abs=1e-14)

    for _ in range(50):
        alpha = np.random.uniform(1e-3, 10)
        s.alpha = alpha

        x = np.random.uniform(-20, 20)
        y = np.random.uniform(-20, 20)
        positions[0, 0] = x
        positions[0, 1] = y
        wf = s.single_particle_function(positions)
        assert wf == pytest.approx(np.exp(-alpha * (x**2 + y**2)), abs=1e-14)
Exemplo n.º 18
0
def main(bootstrap=False):
    logger = Logger(LOG_FILE, TIME_SERIES_FILE)
    logger.log_config(TEST, STOP_TIME, PROT_DISCR_STEP, NON_PROT_DISCR_STEP,
                      SMALLEST_VALUE, epsilon, delta)
    system = System(MODEL_FOLDER)
    param_bounds = parse_parameters_bounds_xml(XML_PATH)
    constraints = parse_constraints(CONSTRAINTS_PATH)
    system.set_constraints(constraints)
    parameter_space = ParameterSpace(param_bounds, system, PROT_DISCR_STEP,
                                     NON_PROT_DISCR_STEP, SMALLEST_VALUE)
    logger.log_parameter_space(parameter_space)
    if bootstrap:
        admissible_param = algorithm.bootstrap(system, parameter_space,
                                               STOP_TIME)
        utils.utils.save_parameters_to_file(ADM_PARAM_FILE, parameter_space,
                                            [admissible_param])
    adm_parameter_array = utils.utils.get_parameters_from_file(
        ADM_PARAM_FILE, parameter_space)
    # adm_parameter_map = parameter_space.get_map_from_array(adm_parameter_array)
    # system.set_parameters(adm_parameter_map)
    # system.simulate(STOP_TIME, True)
    vps = algorithm.get_virtual_patients(system, parameter_space,
                                         adm_parameter_array, epsilon, delta,
                                         STOP_TIME, POWER_LAW_EXP, logger)
    utils.utils.save_parameters_to_file(PARAM_FILE, parameter_space, vps)
Exemplo n.º 19
0
def system_fixture():
    system = System()

    order = system.new_order(system.generate_id())
    burger = SingleBurger()
    burger.add_ingredient("Sesame bun", 1)
    burger.add_ingredient("Muffin bun", 1)
    burger.add_ingredient("Beef patty", 1)

    order.add_item(burger)
    order.add_item(Drink("Water bottle"))
    order.add_item(Side("Small fries"))
    order.add_item(Side("Nuggets 3P"))

    order2 = system.new_order(system.generate_id())
    burger2 = SingleBurger()
    burger2.add_ingredient("Sesame bun", 1)
    burger2.add_ingredient("Muffin bun", 1)
    burger2.add_ingredient("Beef patty", 1)

    order2.add_item(burger)
    order2.add_item(Drink("Coke Can"))
    order2.add_item(Side("Medium fries"))
    order2.add_item(Side("Nuggets 6P"))

    return system
Exemplo n.º 20
0
def main():
    print('Loading the Classifier, please wait....')
    classifier = joblib.load('svmClassifier.pkl', )
    system = System("data/tweets.csv", "index/frequency-index.txt",
                    "index/tf-idf-index.txt", False)
    print('READY')
    while 1:
        pos = 0
        neg = 0
        query = str(input("Enter your query: "))
        query_results = system.test_system(query)
        print('===============POSITIVE TWEETS=============')
        for tweet in query_results:
            if predict(str(tweet), classifier):
                print(tweet)
                print("-----------------------------------------")
                pos = pos + 1
                if pos > 10:
                    break
        print('===============NEGATIVE TWEETS=============')
        for tweet in query_results:
            if predict(str(tweet), classifier) == 0:
                print(tweet)
                print("-----------------------------------------")
                neg = neg + 1
                if neg > 10:
                    break
        temp = input('Press any key to continue')
Exemplo n.º 21
0
def main():
    # Solar system data comes from
    #   http://hyperphysics.phy-astr.gsu.edu/hbase/solar/soldata2.html
    sun = Body(1.98892e30, 0, 0, 0, 0, 15, 1, 1, 0)
    mercury = Body(.06 * EM, -.3871 * AU, 0, 0, 47890, 3, 1, .4, 0)
    venus = Body(.82 * EM, -.7233 * AU, 0, 0, 35040, 6, 0, .6, .2)
    earth = Body(1.0 * EM, -1.0 * AU, 0, 0, 29790, 7, 0, .4, 1)
    mars = Body(.11 * EM, -1.524 * AU, 0, 0, 24140, 4, .8, .2, 0)

    solar_system = System([sun, mercury, venus, earth, mars])

    set_clear_color(0, 0, 0)  # black background
    enable_smoothing()

    while not window_closed():
        clear()

        # Draw the system in its current state.
        solar_system.draw(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2,
                          PIXELS_PER_METER)

        # Update the system for its next state.
        solar_system.update(TIMESTEP * TIME_SCALE)

        # Draw the frame and take a brief nap.
        request_redraw()
        sleep(TIMESTEP)
Exemplo n.º 22
0
def test_complete_order_list(inventory_fixture, ingredient_cost_fixture):
    system1 = System(inventory_fixture, ingredient_cost_fixture)
    assert (isinstance(system1, System))
    order1 = system1.Create_Order()
    assert (isinstance(order1, Order))

    burg1 = order1.Create_Item("Burger")
    burg1.Bun_Type = "white"
    burg1.Add_Bun()
    burg1.Add_Bun()
    burg1.Patty_Type = "beef"
    burg1.Add_Patty()
    burg1.Add_Other("cheese")
    order1.Add_To_Order(burg1)
    assert (burg1 in order1.Items)
    assert (order1.Calculate_Cost() == 9)

    system1.Submit_Order(order1)
    assert (order1 in system1.View_Incomplete_Orders())
    assert (order1 not in system1.View_Complete_Orders())
    system1.Preparing_Order(order1)
    assert (order1 not in system1.View_Complete_Orders())
    assert (order1 in system1.View_Incomplete_Orders())
    system1.Complete_Order(order1)
    assert (order1 not in system1.View_Incomplete_Orders())
    assert (order1 in system1.View_Complete_Orders())
Exemplo n.º 23
0
def runOptimalRoute():
    """ Returns the optimal route of an already created laby (see random_env parameter above),
    by launching the algorithm """

    # INITIALISATION
    # Variables initialisations

    Epsilon = 1
    Lambda = 1
    Gamma = 0.85
    Nb_episodes = 5000
    maxActionCount = 5000

    # Initialising agent
    qlearning_agent = AgentQLearning(Epsilon, Lambda, Gamma, laby)

    # Initialising system
    qlearning_system = System(laby, qlearning_agent)
    initial_position = qlearning_system.laby.current_position

    for k in range(Nb_episodes):
        qlearning_system.laby.current_position = initial_position
        qlearning_system.runEpisode(maxActionCount)
    Optimal_Route = OptimalRoute(qlearning_system,
                                 qlearning_system.agent.Quality,
                                 initial_position)
    return Optimal_Route
Exemplo n.º 24
0
def test_complete_order_fail(inventory_fixture, ingredient_cost_fixture):
    system1 = System(inventory_fixture, ingredient_cost_fixture)
    assert (isinstance(system1, System))
    order = 1
    with pytest.raises(SystemError) as err:
        system1.Complete_Order(order)
    assert (err)
Exemplo n.º 25
0
def main(filenames=None, resolutions_filter=None, max_model_count=None):
    if not filenames:
        paths = [
            join(Util.MODEL_DIR(), p) for p in os.listdir(Util.MODEL_DIR())
            if p[0] == 'L'
        ]
        filenames = [f for f in paths if isfile(f)]
    resolutions_counter = defaultdict(int)

    model_count = 0
    for filename in filenames:
        with open(filename, 'rb') as ifile:
            data = ifile.read()
            resolution = data[0]
            resolutions_counter[resolution] += 1
            if (not resolutions_filter) or (resolutions_filter and resolution
                                            in resolutions_filter):
                m = Model(filename, data)
                s = System(m)

                s.trace = s.find_solution()
                ofilename = join(Util.MY_TRACE_DIR(), 'LA001.nbt')
                s.trace_write(ofilename, s.trace)

                if Config.VERBOSE:
                    print(f'Model #{model_count}', end='')
                m.print()
                model_count += 1
                if max_model_count and model_count >= max_model_count:
                    break

    if Config.VERBOSE:
        for res in sorted(resolutions_counter.keys()):
            print(f'{res:3}: {resolutions_counter[res]}')
Exemplo n.º 26
0
def main(argv):
    #starts the game with the given configuration if given a command line param
    if (len(argv) > 0):
        system = System(int(argv[0]))
    
    #starts the game from the System class
    system.startGame()
Exemplo n.º 27
0
def main():
    earth = Body(5.9736e24, 0, 0, 0, 0, 24, 0, 0, 1)  # blue earth
    moon = Body(7.3477e22, 3.84403e8, 0, 0, 1022, 4, 1, 1, 1)  # white moon
    earth_moon = System([earth, moon])

    set_clear_color(0, 0, 0)  # black background
    enable_smoothing()

    while not window_closed():
        clear()

        moon.update_velocity(
            -0.25, -0.00004, TIMESTEP * TIME_SCALE
        )  # This is my new addition. I update the moon's velocity and position
        moon.update_position(
            TIMESTEP * TIME_SCALE
        )  # so that the moon moves and I can check the body class' methods

        # Draw the system in its current state.
        earth_moon.draw(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, PIXELS_PER_METER)

        # Update the system for its next state.
        # earth_moon.update(TIMESTEP * TIME_SCALE)

        # Draw the frame and take a brief nap.
        request_redraw()
        sleep(TIMESTEP)
Exemplo n.º 28
0
def test_system_wavefunction_3d():
    num_particles = 1
    num_dimensions = 3
    alpha = 1.0
    beta = 1.0
    a = 0.0
    s = System(num_particles, num_dimensions, alpha, beta, a)
    positions = np.zeros(shape=(num_particles, num_dimensions))

    for _ in range(50):
        alpha = np.random.uniform(1e-3, 10)
        beta = np.random.uniform(1e-3, 10)
        s.alpha = alpha
        s.beta = beta

        x = np.random.uniform(-20, 20)
        y = np.random.uniform(-20, 20)
        z = np.random.uniform(-20, 20)

        positions[0, 0] = x
        positions[0, 1] = y
        positions[0, 2] = z
        wf = s.single_particle_function(positions)
        assert wf == pytest.approx(np.exp(-alpha *
                                          (x**2 + y**2 + beta * z**2)),
                                   abs=1e-14)
Exemplo n.º 29
0
def on_FileReader_load(e):
    arrayBuffer = e.target.result
    file = e.target.file['name']
    rom = __new__(Uint8Array(arrayBuffer, 0, arrayBuffer.length))
    c = Cart(file, rom)
    document.getElementById('cartName').innerText = file
    s = System(c)
Exemplo n.º 30
0
 def boot(self):
     try:
         self.interface = Interface()
         self.system = System()
         self.manager = Manager(self.system, self.interface)
     except:
         self.stop('Failed to boot Termud:\n\n' + traceback.format_exc())