예제 #1
0
    def environment__get_agent_by_id(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment

        text = "This test checks environment.get_agent_by_id \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test environment__get_agent_by_id in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory,  identifier)

        #
        # TESTING
        #
        print("Getting a bank with id: bank_test_config_id")
        print(environment.get_agent_by_id("bank_test_config_id"))
예제 #2
0
    def environment__write_environment_file(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment

        text = "This test checks environment.write_environment_file \n"
        text = "and writes a mirror of the config file \n"
        text = "in the directory from which it was called \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test environment__write_environment_file in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory,  identifier)

        #
        # TESTING
        #
        print("Writing the environment file")
        environment.write_environment_file(identifier)
예제 #3
0
    def environment__check_global_transaction_balance(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment

        text = "This test checks environment.check_global_transaction_balance \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test environment__check_global_transaction_balance in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory,  identifier)

        #
        # TESTING
        #

        print("Checking global consistency of deposits:")
        if environment.check_global_transaction_balance("deposits") == True:
            print("Consistent")
        else:
            print("Not consistent")
예제 #4
0
    def environment__add_static_parameter(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment

        text = "This test checks environment.add_static_parameter \n"
        text = "Should add 'test':0.66 to static parameters \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test environment__add_static_parameter in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory,  identifier)

        #
        # TESTING
        #

        print(environment.static_parameters)
        print("Adding 'test':0.66")
        environment.add_static_parameter("test", 0.66)
        print(environment.static_parameters)
예제 #5
0
    def environment__read_transactions_for_banks(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment

        text = "This test checks environment.read_transactions_for_banks \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test environment__read_transactions_for_banks in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory,  identifier)

        #
        # TESTING
        #

        print("Clearing accounts of the bank:")
        environment.banks[0].clear_accounts()  # let's use the first bank
        print(environment.banks[0])
        print("Reading transactions: ")
        environment.read_transactions_for_banks(environment.bank_directory)
        print(environment.banks[0])
예제 #6
0
    def transaction__add_transaction(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment
        from src.transaction import Transaction

        text = "This test checks transaction.add_transaction \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test transaction__add_transaction in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory,  identifier)

        # generate a bank
        bank = Bank()
        bank.identifier = "test_bank"
        environment.banks.append(bank)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.firms.append(firm)

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.households.append(household)

        #
        # TESTING
        #

        print("Creating a transaction")
        transaction = Transaction()
        print("Assigning values")
        transaction.this_transaction("type", "asset", "test_household", "test_firm", 1,  2,  3, 4)
        print("Adding the transaction to the books")
        transaction.add_transaction(environment)
        print("The transaction:")
        print(transaction)
        print("The firm:")
        print(environment.get_agent_by_id("test_firm"))
        print("The household:")
        print(environment.get_agent_by_id("test_household"))
예제 #7
0
    def setUp(self):
        self.w1 = WeatherModel(1)
        self.w2 = WeatherModel(2)
        self.e1 = Environment(10,15)
        self.e2 = Environment(20,25)

        loc = [2, 1]
        self.tile = self.e1.get_tile(loc)
        self.teff1 = Teff(self.tile)
예제 #8
0
    def transaction__clear_accounts(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment
        from src.transaction import Transaction

        text = "This test checks transaction.clear_accounts \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test transaction__clear_accounts in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory,  identifier)

        # generate a bank
        # bank = Bank()
        # bank.identifier = "test_bank"
        # environment.banks.append(bank)

        # generate a firm
        # firm = Firm()
        # firm.identifier = "test_firm"
        # environment.firms.append(firm)

        # generate a household
        # household = Household()
        # household.identifier = "test_household"
        # environment.households.append(household)

        #
        # TESTING
        #

        print("Before clearing one bank's accounts")
        for bank in environment.banks:
            print(bank)
        for household in environment.households:
            print(household)
        environment.get_agent_by_id("bank_test_config_id").clear_accounts()
        print("After clearing one bank's accounts")
        for bank in environment.banks:
            print(bank)
        for household in environment.households:
            print(household)
예제 #9
0
    def updater__endow_labour(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment
        from src.transaction import Transaction
        from src.market import Market
        from src.updater import Updater

        text = "This test checks updater.endow_labour \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test updater__endow_labour in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory,  identifier)

        # generate a bank
        bank = Bank()
        bank.identifier = "test_bank"
        environment.banks.append(bank)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.firms.append(firm)

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.households.append(household)

        #
        # TESTING
        #
        model = Updater(environment)
        environment.get_agent_by_id("test_household").sweep_labour = 0
        print(environment.get_agent_by_id("test_household").sweep_labour)
        print("Endowing labour")
        model.endow_labour(environment, 0)
        print(environment.get_agent_by_id("test_household").sweep_labour)
예제 #10
0
파일: test_pickle.py 프로젝트: blendit/env
    def test_mountains(self):
        mount = ImageFeature("tests/img/mount_200.png")
        
        gen_model = AbstractModel(os.path.abspath(os.path.dirname(sys.argv[0])) + "/tests/models/pine_tree/Pine_4m.obj", 0.01, (0, 0))
        v1 = Vegetation(geom.box(20, 20, 180, 180), gen_model, 10)
        v1.models.append(Model((5, 5), gen_model))
        v1.models.append(Model((195, 195), gen_model))

        env = Environment([mount, v1])
        env.init_heightmap(200, 200)
        
        f = open('mountains.pickle', 'wb')
        pickle.dump(env, f)
        f.close()

        env.export_heightmap("bla.png", 200, 200)
예제 #11
0
파일: test_pickle.py 프로젝트: blendit/env
    def test_pickle(self):
        a = Environment([Feature()])
        # moche mais en attendant que ça marche...
        a.init_heightmap(10, 10)
        b = HeightMap(10, 10, z_func=lambda z: 100 * z[0] + z[1])
        a.heightmap = b

        f = open('/tmp/waves.p', 'wb')
        pickle.dump(a, f)
        f.close()

        g = open('/tmp/waves.p', 'rb')
        b = pickle.load(g)
        g.close()

        self.assertEqual(a.heightmap, b.heightmap)
예제 #12
0
class TestClassEnvironment(unittest.TestCase):
    def setUp(self):
        self.background = FeatureTest(100, influence="notall", val_influence=1)
        self.background.shape = geom.box(5, 5, 45, 45)
        
        self.up = FeatureTest(150, influence="notall", val_influence=1)
        self.up.shape = geom.box(10, 10, 30, 30)
        
        self.rep = FeatureTestReplace(0, influence="notall", val_influence=1)
        self.rep.shape = geom.box(10, 10, 30, 30)
        
        self.forest = Vegetation(geom.box(5, 5, 45, 45), model=AbstractModel(), tree_number=50)

        self.env = Environment([self.rep, self.up, self.background, self.forest])
        
    def test_models(self):
        self.assertLess(len(self.env.models), 50)
        self.assertGreater(len(self.env.models), 25)

        self.env.export_heightmap("temp_env.png", 50, 50)
예제 #13
0
    def environment__check_agent_homogeneity(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment

        text = "This test checks environment.check_agent_homogeneity \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test environment__check_agent_homogeneity in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory,  identifier)

        #
        # TESTING
        #
        bank = Bank()
        bank.identifier = "new bank"
        environment.banks.append(bank)
        environment.agents = [environment.banks, environment.firms, environment.households]

        print("Are banks homogeneous?")
        print(environment.check_agent_homogeneity("banks"))
        print("Changing one of the banks...")
        environment.get_agent_by_id("new bank").parameters["active"] = 4
        print("Are banks homogeneous?")
        print(environment.check_agent_homogeneity("banks"))
예제 #14
0
    def setUp(self):
        self.background = FeatureTest(100, influence="notall", val_influence=1)
        self.background.shape = geom.box(5, 5, 45, 45)
        
        self.up = FeatureTest(150, influence="notall", val_influence=1)
        self.up.shape = geom.box(10, 10, 30, 30)
        
        self.rep = FeatureTestReplace(0, influence="notall", val_influence=1)
        self.rep.shape = geom.box(10, 10, 30, 30)
        
        self.forest = Vegetation(geom.box(5, 5, 45, 45), model=AbstractModel(), tree_number=50)

        self.env = Environment([self.rep, self.up, self.background, self.forest])
예제 #15
0
    def environment__set_identifier(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment

        text = "This test checks environment.set_identifier \n"
        text = "and sets the identifier to XYZ \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test environment__set_identifier in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory,  identifier)

        #
        # TESTING
        #

        text = "Identifier: "
        text = text + environment.identifier
        print(text)
        print("Changing identifier to XYZ")
        environment.set_identifier("XYZ")
        text = "Identifier: "
        text = text + environment.identifier
        print(text)
예제 #16
0
    def environment__set_variable_parameters(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment

        text = "This test checks environment.set_variable_parameters \n"
        text = "and sets them to 'test': 0.55-0.66 \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test environment__set_variable_parameters in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory,  identifier)

        #
        # TESTING
        #

        print("Variable parameters:")
        print(environment.get_variable_parameters())
        print("Changing variable parameters to 'test': 0.55-0.66")
        environment.set_variable_parameters({'test': [0.55, 0.66]})
        print("Variable parameters:")
        print(environment.get_variable_parameters())
예제 #17
0
    def environment__add_shock(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment

        text = "This test checks environment.add_shock \n"
        text = text + "and adds to them [3, 4, 'test']\n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test environment__add_shock in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory,  identifier)

        #
        # TESTING
        #

        print("Shocks:")
        print(environment.get_shocks())
        print("Adding shock [3, 4, 'test']")
        environment.add_shock([3, 4, "test"])
        print("Shocks:")
        print(environment.get_shocks())
예제 #18
0
    def updater__consume_rationed(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment
        from src.transaction import Transaction
        from src.market import Market
        from src.updater import Updater

        text = "This test checks updater.consume_rationed \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s',
                            datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log",
                            level=logging.INFO)
        logging.info(
            'START logging for test updater__consume_rationed in run: %s',
            environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory, identifier)

        #
        # TESTING
        #
        model = Updater(environment)
        model.sell_labour(environment, 0)
        print(environment.households[0])
        print("Consuming the production")
        model.consume_rationed(environment, 0)
        print(environment.households[0])
예제 #19
0
    def network__subnetwork_by_type(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment
        from src.transaction import Transaction
        from src.network import Network

        text = "This test checks network.subnetwork_by_type \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s',
                            datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log",
                            level=logging.INFO)
        logging.info(
            'START logging for test network__subnetwork_by_type in run: %s',
            environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory, identifier)

        #
        # TESTING
        #

        print("Properties of the full network:")
        print(nx.info(environment.network.transactions))
        print("Creating the subnetwork by type")
        G = environment.network.subnetwork_by_type("loans")
        print("Properties of the subnetwork:")
        print(nx.info(G))
예제 #20
0
    def network__set_transactions(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment
        from src.transaction import Transaction
        from src.network import Network

        text = "This test checks network.set_transactions \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s',
                            datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log",
                            level=logging.INFO)
        logging.info(
            'START logging for test network__set_transactions in run: %s',
            environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory, identifier)

        #
        # TESTING
        #

        print(nx.info(environment.network.get_transactions()))
        print("Setting transactions to an empty graph")
        empty_graph = nx.MultiDiGraph()
        environment.network.set_transactions(empty_graph)
        print(nx.info(environment.network.get_transactions()))
예제 #21
0
    def helper__translog(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment
        from src.transaction import Transaction
        from src.helper import Helper

        text = "This test checks helper.translog \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s',
                            datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log",
                            level=logging.INFO)
        logging.info('START logging for test helper__translog in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory, identifier)

        #
        # TESTING
        #

        helper = Helper()
        production = helper.translog(3, 2, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5)
        print("Calculating production in translog:")
        print(production)
예제 #22
0
    def test_standard_environment_creation(self):
        dummy_map = "/o/..\n" \
                    "S.../"

        e = Environment(self.settings, dummy_map)
        self.assertEqual(15, len(e.get_all_tiles()))

        # First tile is walkable grass and not dirt
        first_tile = e.tile_at(Position(0, 0))
        self.assertTrue(first_tile.is_walkable())
        self.assertFalse(first_tile.is_dirt())
        self.assertTrue(first_tile.is_grass())

        # Second tile is walkable stone and not dirt
        second_tile = e.tile_at(Position(1, 0))
        self.assertTrue(second_tile.is_walkable())
        self.assertFalse(second_tile.is_dirt())
        self.assertTrue(second_tile.is_stone())

        # Last tile is walkable grass with dirt
        last_tile = e.tile_at(Position(4, 1))
        self.assertTrue(last_tile.is_walkable())
        self.assertTrue(last_tile.is_dirt())
        self.assertTrue(last_tile.is_grass())
예제 #23
0
 def setUp(self):
     self.__env = Environment()
     self.__env.set_var_value('x', '10')
     self.__env.set_var_value('var_name', 'kek')
예제 #24
0
class TestPreprocessor(unittest.TestCase):

        def setUp(self):
            self.__env = Environment()
            self.__env.set_var_value('x', '10')
            self.__env.set_var_value('var_name', 'kek')

        def test_find_var(self):
            var_name, rest = Preprocessor.find_var('var')
            self.assertEqual(var_name, 'var')
            self.assertEqual(rest, '')

        def test_find_var_in_string(self):
            var_name, rest = Preprocessor.find_var('var_1 567')
            self.assertEqual(var_name, 'var_1')
            self.assertEqual(rest, ' 567')

        def test_substitute_vars_single(self):
            result = Preprocessor.substitute_vars('$x', self.__env)
            self.assertEqual('10',result)

        def test_substitute_vars_in_single_quotes(self):
            result = Preprocessor.substitute_vars('\'$x\'', self.__env)
            self.assertEqual('$x', result)

        def test_substitute_vars_in_double_quotes(self):
            result = Preprocessor.substitute_vars('\"$x\"', self.__env)
            self.assertEqual('10', result)

        def test_substitute_vars_double_in_single_quotes(self):
            result = Preprocessor.substitute_vars('\'$var_name\"$x\"kek\'', self.__env)
            self.assertEqual('$var_name\"$x\"kek', result)

        def test_substitute_vars_single_in_double_quotes(self):
            result = Preprocessor.substitute_vars('\"$var_name\'$x\'kek\"', self.__env)
            self.assertEqual('kek\'10\'kek', result)

        def test_substitute_vars_single_in_single_quotes(self):
            result = Preprocessor.substitute_vars('\'$var_name\'$x\'kek\'', self.__env)
            self.assertEqual('$var_name10kek', result)

        def test_substitute_vars_double_in_double_quotes(self):
            result = Preprocessor.substitute_vars('\"$var_name\"$x\"kek\"', self.__env)
            self.assertEqual('kek10kek', result)

        def test_substitute_vars_single_quotes_in_text(self):
            result = Preprocessor.substitute_vars('kek\'$var_name\'kek', self.__env)
            self.assertEqual('kek$var_namekek', result)

        def test_substitute_vars_double_quotes_in_text(self):
            result = Preprocessor.substitute_vars('kek\"$var_name\"kek', self.__env)
            self.assertEqual('kekkekkek', result)

        def test_substitute_two_vars(self):
            result = Preprocessor.substitute_vars('$x$var_name', self.__env)
            self.assertEqual('10kek', result)

        def test_substitute_two_vars_in_single_quotes(self):
            result = Preprocessor.substitute_vars('\'$x$var_name\'', self.__env)
            self.assertEqual('$x$var_name', result)

        def test_substitute_two_vars_in_double_quotes(self):
            result = Preprocessor.substitute_vars('\"$x$var_name\"', self.__env)
            self.assertEqual('10kek', result)

        def test_substitute_no_var_in_text_in_double_quotes(self):
            result = Preprocessor.substitute_vars('\"kek$xl\"', self.__env)
            self.assertEqual('kek', result)

        def test_substitute_var_in_text_in_double_quotes(self):
            result = Preprocessor.substitute_vars('\"kek$var_name 10\"', self.__env)
            self.assertEqual('kekkek 10', result)

        def test_substitute_var_in_three_double_quotes(self):
            result = Preprocessor.substitute_vars('\"\"\"$var_name\"\"\"', self.__env)
            self.assertEqual('kek', result)

        def test_substitute_var_in_three_single_quotes(self):
            result = Preprocessor.substitute_vars('\'\'\'$var_name\'\'\'', self.__env)
            self.assertEqual('$var_name', result)

        def test_exception_one_single_quote(self):
            self.assertRaises(ParserException,
                              Preprocessor.substitute_vars, '\'xx', self.__env)

        def test_exception_one_double_quote(self):
            self.assertRaises(ParserException,
                              Preprocessor.substitute_vars, '\"xx', self.__env)

        def test_exception_one_single_and_one_double_quote(self):
            self.assertRaises(ParserException,
                              Preprocessor.substitute_vars, '\"x\'x', self.__env)
예제 #25
0
    def bank__set_state_variables(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment  # needed for the bankDirectory

        text = "This test checks bank.set_state_variables \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s',
                            datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log",
                            level=logging.INFO)
        logging.info(
            'START logging for test bank__set_state_variables in run: %s',
            environment_directory + identifier + ".xml")

        # Construct bank filename
        environment = Environment(environment_directory, identifier)

        # get the bank_directory from the environment
        bank_directory = environment.bank_directory
        # and loop over all banks in the directory
        listing = os.listdir(bank_directory)
        bank_filename = bank_directory + listing[0]

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.households.append(household)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.firms.append(firm)

        # generate the bank
        bank = Bank()
        environment.banks.append(bank)
        helper = Helper()
        helper.initialize_standard_bank(bank, environment)

        #
        # TESTING
        #

        text = "Original state variables:"
        print(text)
        print(bank.get_state_variables())
        text = "New state variables:"
        print(text)
        bank.set_state_variables({'test': 0.66})
        print(bank.get_state_variables())
예제 #26
0
    import logging
    import pandas as pd
    import numpy as np
    import random
    from src.frange import frange
    import matplotlib.pyplot as plt
    import sys
    import decimal
    
# INITIALIZATION
#
    environment_directory = str("configs/environment/")
    identifier = str("firesales")

############
    environment = Environment(environment_directory, identifier)
    runner = Runner(environment)
   
############ 
    #Declare variables of interest for the simulation

    print("the illiquidity paramer is"), environment.static_parameters['illiquidity']  #is declared inside ENV config
    print("the num_simulations paramer is"), environment.static_parameters['num_simulations'] # is declared inside ENV config 


    environment.static_parameters['leverage_increase'] = (1/3)
    print environment.static_parameters['leverage_increase']
    for i in range(int(environment.static_parameters['num_simulations'])):

        if i == 0:
예제 #27
0
    def bank__clear_accounts(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment  # needed for the bankDirectory

        text = "This test checks bank.clear_accounts \n"
        text = text + "  Checking if after the clear_accounts the total amount    \n"
        text = text + "  of transactions in zero.  \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test bank__clear_accounts in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct bank filename
        environment = Environment(environment_directory,  identifier)

        # get the bank_directory from the environment
        bank_directory = environment.bank_directory
        # and loop over all banks in the directory
        listing = os.listdir(bank_directory)
        bank_filename = bank_directory + listing[0]

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.households.append(household)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.firms.append(firm)

        # generate the bank
        bank = Bank()
        environment.banks.append(bank)
        helper = Helper()
        helper.initialize_standard_bank(bank, environment)

        #
        # TESTING
        #

        account = 0.0
        tranx = 0

        for transaction in bank.accounts:
            account = account + transaction.amount
            tranx = tranx + 1

        print(tranx)
        print(account)

        bank.add_transaction("deposits", "", "test_household",
                             bank.identifier, 0.0,  0.09,  0, -1, environment)

        account = 0.0
        tranx = 0

        for transaction in bank.accounts:
            account = account + transaction.amount
            tranx = tranx + 1

        print(tranx)
        print(account)

        for bank in environment.banks:
            print(bank)
        for firm in environment.firms:
            print(firm)
        for household in environment.households:
            print(household)
        bank.clear_accounts(environment)

        account = 0.0
        tranx = 0

        for transaction in bank.accounts:
            account = account + transaction.amount
            tranx = tranx + 1

        print(tranx)
        print(account)
예제 #28
0
    def bank__check_consistency(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment  # needed for the bankDirectory

        text = "This test checks bank.check_consitency \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test bank__check_consistency in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct bank filename
        environment = Environment(environment_directory,  identifier)

        # get the bank_directory from the environment
        bank_directory = environment.bank_directory
        # and loop over all banks in the directory
        listing = os.listdir(bank_directory)
        bank_filename = bank_directory + listing[0]

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.households.append(household)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.firms.append(firm)

        # generate the bank
        bank = Bank()
        environment.banks.append(bank)
        helper = Helper()
        helper.initialize_standard_bank(bank, environment)

        #
        # TESTING
        #

        print("Checking consistency of the standard bank: ")
        print(bank.check_consistency())
        print("Adding additional deposits without adding appropriate cash/loans.")
        bank.add_transaction("deposits", "", environment.get_agent_by_id("test_household"),
                             bank, 150, bank.interest_rate_deposits, 0, -1, environment)
        # environment.households[0:1][0] is only for testing purposes DO NOT USE IN PRODUCTION
        # what it does is is takes the first household in environment, but if there are no
        # households (which happens in testing) it doesn't break down
        print("Checking consistency of the standard bank: ")
        print(bank.check_consistency())
예제 #29
0
# -------------------------------------------------------------------------
#
#  MAIN
#
# -------------------------------------------------------------------------
if __name__ == '__main__':

    from src.environment import Environment
    from src.runner import Runner

    args = ["configs/environment/", "environment_config", "log/"]

#
# INITIALIZATION
#
    environment_directory = str(args[0])
    identifier = str(args[1])
    log_directory = str(args[2])

    environment = Environment(environment_directory, identifier)
    runner = Runner(environment)

#
# UPDATE STEP
#
    # for i in range(int(environment.static_parameters['num_simulations'])):
    #     environment.initialize(environment_directory, identifier)
    #     runner.initialize(environment)
    #     # do the run
    #     runner.do_run(environment)
예제 #30
0
    def bank__add_transaction(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment  # needed for the bankDirectory

        text = "This test checks bank.add_transaction \n"
        text = text + "  The most simple way to test this function is to assign an new    \n"
        text = text + "  transaction to our bank. Therefore, lets just assign the following  \n"
        text = text + "  transaction and check whether it has been added: \n"
        text = text + '  (type = "deposits",  fromID = -1,  toID = bank.identifier,  amount = 10,  \n'
        text = text + "   interest = 0.09, maturity = 0, timeOfDefault = -1) \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test bank__add_transaction in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct bank filename
        environment = Environment(environment_directory,  identifier)

        # get the bank_directory from the environment
        bank_directory = environment.bank_directory
        # and loop over all banks in the directory
        listing = os.listdir(bank_directory)
        bank_filename = bank_directory + listing[0]

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.households.append(household)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.firms.append(firm)

        # generate the bank
        bank = Bank()
        environment.banks.append(bank)
        helper = Helper()
        helper.initialize_standard_bank(bank, environment)

        #
        # TESTING
        #

        print(bank)
        print("Adding new transaction: \n")
        print(environment.get_agent_by_id(bank.identifier))
        bank.add_transaction("deposits", "", "test_household",
                             bank.identifier,  10,  0.09,  0, -1, environment)
        # environment.households[0:1][0] is only for testing purposes DO NOT USE IN PRODUCTION
        # what it does is is takes the first household in environment, but if there are no
        # households (which happens in testing) it doesn't break down
        print(bank)
예제 #31
0
    def bank__check_consistency(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment  # needed for the bankDirectory

        text = "This test checks bank.check_consitency \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test bank__check_consistency in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct bank filename
        environment = Environment(environment_directory,  identifier)

        # get the bank_directory from the environment
        bank_directory = environment.bank_directory
        # and loop over all banks in the directory
        listing = os.listdir(bank_directory)
        bank_filename = bank_directory + listing[0]

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.households.append(household)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.firms.append(firm)

        # generate the bank
        bank = Bank()
        environment.banks.append(bank)
        helper = Helper()
        helper.initialize_standard_bank(bank, environment)

        #
        # TESTING
        #

        print("Checking consistency of the standard bank: ")
        print(bank.check_consistency())
        print("Adding additional deposits without adding appropriate cash/loans.")
        bank.add_transaction("deposits", "", environment.get_agent_by_id("test_household"),
                             bank, 150, bank.interest_rate_deposits, 0, -1, environment)
        # environment.households[0:1][0] is only for testing purposes DO NOT USE IN PRODUCTION
        # what it does is is takes the first household in environment, but if there are no
        # households (which happens in testing) it doesn't break down
        print("Checking consistency of the standard bank: ")
        print(bank.check_consistency())
예제 #32
0
 def begin_scope(self):
     self.environment = Environment({}, self.environment)
     return self.environment
예제 #33
0
        sys.exit()


#
# INITIALIZATION
#
    environment_directory = str(args[1])
    identifier = str(args[2])
    log_directory = str(args[3])

    # Configure logging parameters so we get output while the program runs
    logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                        filename=log_directory + identifier + ".log", level=logging.INFO)
    logging.info('START logging for run: %s',  environment_directory + identifier + ".xml")

    environment = Environment(environment_directory,  identifier)
    runner = Runner(environment)

#
# UPDATE STEP
#
    for i in range(int(environment.num_simulations)):
        logging.info('  STARTED with run %s',  str(i))
        environment.initialize(environment_directory,  identifier)
        runner.initialize(environment)
        # do the run
        runner.do_run(environment)
        logging.info('  DONE')

#
# MEASUREMENT AND LOGGING
예제 #34
0
To test a trained agent on an environment from the carl/ directory run

python3 -m scripts.run_test
"""

import argparse
import os.path

from src.agent import DQLAgent
from src.circuit import Circuit
from src.environment import Environment

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--max_steps', type=int, default=200)
    parser.add_argument('--gamma', type=float, default=1.0)
    parser.add_argument('--model', type=str)
    args = parser.parse_args()

    agent = DQLAgent(gamma=args.gamma, max_steps=args.max_steps)
    circuit = Circuit([(0, 0), (0.5, 1), (0, 2), (2, 2), (3, 1), (6, 2),
                       (6, 0)],
                      width=0.3)

    env = Environment(circuit, render=True)
    if agent.load(args.model):
        name = os.path.basename(args.model)
        agent.run_once(env, train=False, greedy=True, name=name[:-3])
        print("{:.2f} laps in {} steps".format(
            circuit.laps + circuit.progression, args.max_steps))
def test(): 
    data = Data(cargs.min_size, cargs.max_size)
    env = Environment(data.get_random_map(), cargs.show_screen, cargs.max_size)
    agent = [Agent(env, args[0], 'agent_1'), Agent(env, args[1], 'agent_2')]
    wl_mean, score_mean = [[deque(maxlen = 10000), deque(maxlen = 10000)]  for _ in range(2)]
    wl, score = [[deque(maxlen = 1000), deque(maxlen = 1000)] for _ in range(2)]
    cnt_w, cnt_l = 0, 0
    # agent[0].model.load_state_dict(torch.load(checkpoint_path_1, map_location = agent[0].model.device))
    # agent[1].model.load_state_dict(torch.load(checkpoint_path_2, map_location = agent[1].model.device))
        
    for _ep in range(cargs.n_epochs):
        if _ep % 10 == 9:
            print('Testing_epochs: {}'.format(_ep + 1))
        done = False
        start = time.time()
        for _iter in count():
            if cargs.show_screen:
                env.render()
                
            """ initialize """
            actions, soft_state, soft_agent_pos = [[[], []] for i in range(3)]
                
            """ update by step """
            for i in range(env.num_players):
                soft_state[i] = env.get_observation(i)
                soft_agent_pos[i] = env.get_agent_pos(i)
               
            """ select action for each agent """
            for agent_id in range(env.n_agents):
                for i in range(env.num_players):
                    agent_state = env.get_states_for_step(soft_state[i])
                    agent_step = env.get_agent_for_step(agent_id, soft_agent_pos[i])
                    act, log_p, state_val = agent[i].select_action(agent_state, agent_step)
                            
                    soft_state[i] = env.soft_step_(agent_id, soft_state[i], act, soft_agent_pos[i])
                    actions[i].append(act)
            # actions[1] = [np.random.randint(0, env.n_actions - 1) for _ in range(env.n_agents)]
            # actions[1] = [0] * env.n_agents
            # actions[1] = pred_acts[1]
            next_state, final_reward, done, _ = env.step(actions[0], actions[1], cargs.show_screen)
            if done:
                score[0].append(env.players[0].total_score)
                score[1].append(env.players[1].total_score)
                if env.players[0].total_score > env.players[1].total_score:
                    cnt_w += 1
                else:
                    cnt_l += 1
                break
            
        end = time.time()
            
        wl[0].append(cnt_w)
        wl[1].append(cnt_l)
        for i in range(2):
            wl_mean[i].append(np.mean(wl[i]))
            score_mean[i].append(np.mean(score[i]))
                
        if _ep % 50 == 49:
            plot(wl_mean, vtype = 'Win')
            plot(score_mean, vtype = 'Score')
            print("Time: {0: >#.3f}s". format(1000*(end - start)))
        env = Environment(data.get_random_map(), cargs.show_screen, cargs.max_size)
예제 #36
0
    parser = argparse.ArgumentParser()
    parser.add_argument("--num_episodes", type=int, default=1000)
    parser.add_argument("--max_steps", type=int, default=200)
    parser.add_argument("--minibatch_size", type=int, default=32)
    parser.add_argument("--gamma", type=float, default=1.0)
    parser.add_argument("--learning_rate", type=float, default=0.1)
    parser.add_argument("--output", type=str, default="weights.h5")
    parser.add_argument("--ui", type=str, default="true")
    args = parser.parse_args()

    circuit = Circuit([(0, 0), (0.5, 1), (0, 2), (2, 2), (3, 1), (6, 2),
                       (6, 0)],
                      width=0.3)

    render = args.ui.lower() != "false"
    env = Environment(circuit=circuit, render=render)

    agent = DQLAgent(
        state_size=len(env.current_state),
        action_size=len(env.actions),
        gamma=args.gamma,
        learning_rate=args.learning_rate,
    )

    agent.train(
        env,
        episodes=args.num_episodes,
        minibatch=args.minibatch_size,
        output=args.output,
    )
예제 #37
0
 def create():
     self.environment = Environment(settings, dummy_map)
     return self.environment
예제 #38
0
 def setUp(self):
     self.env = Environment()
     self.file = 'test_text.txt'
예제 #39
0
def main():
    games = [
        [[[10, 0], [9, 10]], [[8, 18], [9, 8]]],
        [[[9, 0], [6, 8]], [[4, 13], [7, 5]]],
        [[[8, 0], [7, 10]], [[6, 14], [7, 4]]],
        [[[7, 0], [5, 9]], [[4, 11], [6, 2]]],
        [[[7, 0], [4, 8]], [[2, 9], [5, 1]]],
        [[[7, 1], [3, 8]], [[1, 7], [5, 0]]],
        [[[10, 4], [9, 14]], [[12, 22], [9, 8]]],
        [[[9, 3], [6, 11]], [[7, 16], [7, 5]]],
        [[[8, 3], [7, 13]], [[9, 17], [7, 4]]],
        [[[7, 2], [5, 11]], [[6, 13], [6, 2]]],
        [[[7, 2], [4, 10]], [[4, 11], [5, 1]]],
        [[[7, 3], [3, 10]], [[3, 9], [5, 0]]],
    ]
    # add Bimatrix Games
    env = Environment()
    env.iterations = iterations
    for game in games:
        env.add_game(np.asarray(game))

    if save:
        n = 1
        folder = os.path.join(os.getcwd(), "data", "game_histories")
        directory = os.path.join(folder, str(n))
        path = os.path.exists(directory)
        while path:
            n += 1
            directory = os.path.join(folder, str(n))
            path = os.path.exists(directory)
        os.mkdir(directory)
        print("saving directory: {}".format(directory))
    if grid:
        if exp_decay:
            range_decay = (0.9999, 0.94)
        else:
            range_decay = (0.001, 0.01)
        t_init = (0.5, 1.8)
        t_final = (0.1, 1)
        points_t_final = 3
        points_t_init = intervals
        points_decay = 1
        a_range = (0.01, 0.65)
        best_fit, parameter_space = grid_search(
            t_init,
            points_t_init,
            a_range,
            intervals,
            range_decay,
            points_decay,
            t_final,
            points_t_final,
            env,
            runs,
            agents,
            kwargs_agent={
                "d_exp": d_exp,
                "exponential_decay": exp_decay,
                "strategy": strategy,
            },
            kwargs_averages={"begin": begin},
        )
        mse = best_fit["mse"]
        print("Mean Squared Error {}".format(mse))
        print("params {}".format(best_fit["params"]))
        histories = best_fit["history"]
        if save:
            with open(os.path.join(directory, "config.pkl"), "wb") as f:
                pickle.dump(best_fit, f, pickle.HIGHEST_PROTOCOL)
            np.save(os.path.join(directory, "params.npy"), parameter_space)
            print("history saved to {}".format(os.path.join(directory, "params.npy")))
            open_results(directory)
        if show_fig:
            plot_average_run(histories, save_fig, directory)
            plt.show()
    elif simulate:
        for _ in range(agents):
            env.add_player(
                Agent(
                    strategy=strategy,
                    t=t,
                    alpha=a,
                    player_type=0,
                    exponential_decay=exp_decay,
                    d_exp=d_exp,
                    decay_rate=decay_rate,
                )
            )
            env.add_player(
                Agent(
                    strategy=strategy,
                    t=t,
                    alpha=a,
                    player_type=1,
                    exponential_decay=exp_decay,
                    d_exp=d_exp,
                    decay_rate=decay_rate,
                )
            )
        histories = []
        for _ in range(runs):
            history = env.play()
            histories.append(history)
        mse = mean_squared_error(histories)
        print("MSD {}".format(mse))
        if show_fig:
            plot_average_run(histories, save_fig)
            plt.show()
        # save history
        if save:
            np.save(os.path.join(directory, "histories.npy"), histories)
            print(
                "history saved to {}".format(os.path.join(directory, "histories.npy"))
            )
        if save_fig:
            directory = os.path.join(os.getcwd(), "figures")

    if experimental:
        plot_data()

    if save:
        return directory
예제 #40
0
    def updater__accrue_interests(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment
        from src.transaction import Transaction
        from src.market import Market
        from src.updater import Updater

        text = "This test checks updater.accrue_interests \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s',
                            datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log",
                            level=logging.INFO)
        logging.info(
            'START logging for test updater__accrue_interests in run: %s',
            environment_directory + identifier + ".xml")

        # Construct household filename
        environment = Environment(environment_directory, identifier)

        # generate a bank
        bank = Bank()
        bank.identifier = "test_bank"
        bank.interest_rate_deposits = 0.05
        environment.banks.append(bank)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.firms.append(firm)

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.households.append(household)

        #
        # TESTING
        #
        model = Updater(environment)
        model.__init__(environment)
        environment.new_transaction(
            "deposits", "",
            environment.get_agent_by_id("test_household").identifier,
            environment.get_agent_by_id("test_bank"), 10.0,
            environment.get_agent_by_id("test_bank").interest_rate_deposits, 0,
            -1)
        print(environment.get_agent_by_id("test_household"))
        print("Accruing interests\n")
        model.accrue_interests(environment, 0)
        print(environment.get_agent_by_id("test_household"))
예제 #41
0
파일: test_parser.py 프로젝트: lergor/SD
class TestParser(unittest.TestCase):
    def setUp(self):
        self.env = Environment()
        self.env.set_var_value('x', '10')
        self.env.set_var_value('t', 'text')
        self.env.set_var_value('e', 'exit')
        self.env.set_var_value('echo', 'echo')
        self.env.set_var_value('p', 'pwd')
        self.parser = Parser(self.env)
        self.exseptions_lexemes = [
            Lexeme('|', Lexeme_type.PIPE),
            Lexeme('m=', Lexeme_type.ASSIGNMENT),
            Lexeme('|', Lexeme_type.PIPE)
        ]

    def test_echo(self):
        lexems = [
            Lexeme('$echo', Lexeme_type.VAR),
            Lexeme('\'word\'', Lexeme_type.STRING_WITH_QUOTES),
            Lexeme('\"word$x\"', Lexeme_type.STRING_WITH_QUOTES)
        ]
        command = self.parser.build_command(lexems)
        self.assertEqual(CommandECHO, type(command))

    def test_wc(self):
        lexems = [
            Lexeme('wc', Lexeme_type.STRING),
            Lexeme('test1.txt', Lexeme_type.STRING_WITH_QUOTES),
            Lexeme('test2.txt', Lexeme_type.STRING_WITH_QUOTES),
            Lexeme('test3.txt', Lexeme_type.STRING_WITH_QUOTES)
        ]
        command = self.parser.build_command(lexems)
        self.assertEqual(CommandWC, type(command))

    def test_cat(self):
        lexems = [
            Lexeme('cat', Lexeme_type.STRING),
            Lexeme('test.txt', Lexeme_type.STRING)
        ]
        command = self.parser.build_command(lexems)
        self.assertEqual(CommandCAT, type(command))

    def test_pwd(self):
        lexems = [
            Lexeme('pwd', Lexeme_type.STRING),
            Lexeme('$t$x', Lexeme_type.VAR)
        ]
        command = self.parser.build_command(lexems)
        self.assertEqual(CommandPWD, type(command))

    def test_var(self):
        lexems = [Lexeme('$e', Lexeme_type.VAR)]
        self.assertRaises(ExitException, self.parser.build_command, lexems)

    def test_assignment(self):
        lexems = [Lexeme('m=$echo', Lexeme_type.ASSIGNMENT)]
        command = self.parser.build_command(lexems)
        self.assertEqual(CommandASSIGNMENT, type(command))

    def test_unknown(self):
        lexems = [
            Lexeme('ls', Lexeme_type.STRING),
            Lexeme('-la', Lexeme_type.STRING)
        ]
        command = self.parser.build_command(lexems)
        self.assertEqual(UnknownCommand, type(command))

    def test_echo_pipe_cat(self):
        lexems = [
            Lexeme('$echo', Lexeme_type.VAR),
            Lexeme('\"t\"', Lexeme_type.STRING_WITH_QUOTES),
            Lexeme('|', Lexeme_type.PIPE),
            Lexeme('cat', Lexeme_type.STRING)
        ]
        command = self.parser.build_command(lexems)
        self.assertEqual(CommandPIPE, type(command))

    def test_echo_pipe_cat_pipe_pwd(self):
        lexems = [
            Lexeme('$echo', Lexeme_type.VAR),
            Lexeme('\"t\"', Lexeme_type.STRING_WITH_QUOTES),
            Lexeme('|', Lexeme_type.PIPE),
            Lexeme('cat', Lexeme_type.STRING),
            Lexeme('test_text.txt', Lexeme_type.STRING),
            Lexeme('|', Lexeme_type.PIPE),
            Lexeme('pwd', Lexeme_type.STRING)
        ]
        command = self.parser.build_command(lexems)
        self.assertEqual(CommandPIPE, type(command))

    def test_exception_start_with_pipe(self):
        self.assertRaises(ParserException, self.parser.build_command,
                          self.exseptions_lexemes)

    def test_exception_assignment_without_value(self):
        self.assertRaises(ParserException, self.parser.build_command,
                          self.exseptions_lexemes[1:])

    def test_exception_ends_with_pipe(self):
        self.assertRaises(ParserException, self.parser.build_command,
                          self.exseptions_lexemes[1:2])

    def test_exception_bad_assignment(self):
        self.assertRaises(ParserException, self.parser.build_command,
                          [Lexeme('$a=10', Lexeme_type.VAR)])
예제 #42
0
    def bank__get_account(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment  # needed for the bankDirectory

        text = "This test checks bank.get_account \n"
        text = text + "  The purpose of this method is to establish an account for our bank which contains  \n"
        text = text + "  all kinds of assets and liabilities. The method simply adds all kinds of assets  \n"
        text = text + "  and stores them in one volume. As our Banks holds 250.0 assets \n"
        text = text + "  and 250 liabilites the total volume of our account should be 500.0 \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test bank__get_account in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct bank filename
        environment = Environment(environment_directory,  identifier)

        # get the bank_directory from the environment
        bank_directory = environment.bank_directory
        # and loop over all banks in the directory
        listing = os.listdir(bank_directory)
        bank_filename = bank_directory + listing[0]

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.households.append(household)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.firms.append(firm)

        # generate the bank
        bank = Bank()
        environment.banks.append(bank)
        helper = Helper()
        helper.initialize_standard_bank(bank, environment)

        #
        # TESTING
        #

        account = 0.0                                           # counting all types in account together
        print(bank)                                              # and checking how much is the total
        # volume of the account
        for type in ["deposits",  "cash",  "loans"]:
                        if type == "deposits":
                                account = account + bank.get_account(type)
                                print("D = " + str(account))
                        if type == "cash":
                                account = account + bank.get_account(type)
                                print("D+M = " + str(account))
                        if type == "loans":
                                account = account + bank.get_account(type)
                                print("D+M+L = " + str(account))
예제 #43
0
    def bank__get_account_num_transactions(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment  # needed for the bankDirectory

        text = "This test checks bank.get_account_num_transactions \n"
        text = text + "  The purpose of this method is to count the numbers of transaction for   \n"
        text = text + "  accounts banks hold. Our standard bank has 3 transactions by default. \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test bank__get_account_num_transactions in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct bank filename
        environment = Environment(environment_directory,  identifier)

        # get the bank_directory from the environment
        bank_directory = environment.bank_directory
        # and loop over all banks in the directory
        listing = os.listdir(bank_directory)
        bank_filename = bank_directory + listing[0]

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.households.append(household)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.firms.append(firm)

        # generate the bank
        bank = Bank()
        environment.banks.append(bank)
        helper = Helper()
        helper.initialize_standard_bank(bank, environment)

        #
        # TESTING
        #

        num_transactions = 0.0          # counting all types in account together
        print(bank)
        # and checking if the number of transaction
        # is increasing by one
        for type in ["deposits",  "cash",  "loans"]:
                        if type == "deposits":
                                num_transactions = num_transactions + bank.get_account_num_transactions(type)
                                print("D = " + str(num_transactions))
                        if type == "cash":
                                num_transactions = num_transactions + bank.get_account_num_transactions(type)
                                print("D+M = " + str(num_transactions))
                        if type == "loans":
                                num_transactions = num_transactions + bank.get_account_num_transactions(type)
                                print("D+M+L = " + str(num_transactions))
예제 #44
0
    def bank__add_transaction(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment  # needed for the bankDirectory

        text = "This test checks bank.add_transaction \n"
        text = text + "  The most simple way to test this function is to assign an new    \n"
        text = text + "  transaction to our bank. Therefore, lets just assign the following  \n"
        text = text + "  transaction and check whether it has been added: \n"
        text = text + '  (type = "deposits",  fromID = -1,  toID = bank.identifier,  amount = 10,  \n'
        text = text + "   interest = 0.09, maturity = 0, timeOfDefault = -1) \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test bank__add_transaction in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct bank filename
        environment = Environment(environment_directory,  identifier)

        # get the bank_directory from the environment
        bank_directory = environment.bank_directory
        # and loop over all banks in the directory
        listing = os.listdir(bank_directory)
        bank_filename = bank_directory + listing[0]

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.households.append(household)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.firms.append(firm)

        # generate the bank
        bank = Bank()
        environment.banks.append(bank)
        helper = Helper()
        helper.initialize_standard_bank(bank, environment)

        #
        # TESTING
        #

        print(bank)
        print("Adding new transaction: \n")
        print(environment.get_agent_by_id(bank.identifier))
        bank.add_transaction("deposits", "", "test_household",
                             bank.identifier,  10,  0.09,  0, -1, environment)
        # environment.households[0:1][0] is only for testing purposes DO NOT USE IN PRODUCTION
        # what it does is is takes the first household in environment, but if there are no
        # households (which happens in testing) it doesn't break down
        print(bank)
예제 #45
0
 def test_mountain(self):
     m2 = Mountain(10**3, 0, (50, 50))
     t = Environment([m2])
     t.export_heightmap("mountain_as_env.png", res_x=100, res_y=100)
예제 #46
0
    def bank__purge_accounts(self, args):
        import os
        from src.bank import Bank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment  # needed for the bankDirectory

        text = "This test checks bank.purge_accounts \n"
        text = text + "  Checking if after the purge_accounts the total amount    \n"
        text = text + "  of transactions in the bank stays the same.  \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test bank__purge_accounts in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct bank filename
        environment = Environment(environment_directory,  identifier)

        # get the bank_directory from the environment
        bank_directory = environment.bank_directory
        # and loop over all banks in the directory
        listing = os.listdir(bank_directory)
        bank_filename = bank_directory + listing[0]

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.network.transactions.add_node(household.identifier)
        environment.households.append(household)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.network.transactions.add_node(firm.identifier)
        environment.firms.append(firm)

        # generate the bank
        bank = Bank()
        environment.banks.append(bank)
        environment.network.transactions.add_node(bank.identifier)
        helper = Helper()
        helper.initialize_standard_bank(bank, environment)

        #
        # TESTING
        #

        account = 0.0
        tranx = 0

        for transaction in bank.accounts:
            account = account + transaction.amount
            tranx = tranx + 1

        print(tranx)
        print(account)

        bank.add_transaction("deposits", "", environment.get_agent_by_id("test_household"),
                             bank.identifier, 0.0,  0.09,  0, -1, environment)
        # environment.households[0:1][0] is only for testing purposes DO NOT USE IN PRODUCTION
        # what it does is is takes the first household in environment, but if there are no
        # households (which happens in testing) it doesn't break down

        account = 0.0
        tranx = 0

        for transaction in bank.accounts:
            account = account + transaction.amount
            tranx = tranx + 1

        print(tranx)
        print(account)

        bank.accounts[0].purge_accounts(environment)

        account = 0.0
        tranx = 0

        for transaction in bank.accounts:
            account = account + transaction.amount
            tranx = tranx + 1

        print(tranx)
        print(account)
예제 #47
0
import argparse
from src.environment import Environment

"""
Helper script for the Viper tool chain.
Runs tests, measures time and kills processes that take too long.
"""


def print_header():
    print()
    print("Viper tool chain runner")
    print("-----------------------")
    print()


print_header()
parser = argparse.ArgumentParser(description='Viper tool chain runner.')
parser.add_argument('config_file', help='the configuration file for this script.')
args = parser.parse_args()
env = Environment()
env.exec(args.config_file)
env.analyze()
def train(): 
    data = Data(cargs.min_size, cargs.max_size)
    env = Environment(data.get_random_map(), cargs.show_screen, cargs.max_size)
    agent = [Agent(env, args[0], 'agent_1'), Agent(env, args[1], 'agent_2')]
    wl_mean, score_mean, l_val_mean =\
        [[deque(maxlen = 10000), deque(maxlen = 10000)]  for _ in range(3)]
    wl, score, l_val = [[deque(maxlen = 1000), deque(maxlen = 1000)] for _ in range(3)]
    lr_super = [args[0].exp_rate, args[1].exp_rate]
    cnt_w, cnt_l = 0, 0
    # agent[0].model.load_state_dict(torch.load(checkpoint_path_1, map_location = agent[0].model.device))
    # agent[1].model.load_state_dict(torch.load(checkpoint_path_2, map_location = agent[1].model.device))
        
    for _ep in range(cargs.n_epochs):
        if _ep % 10 == 9:
            print('Training_epochs: {}'.format(_ep + 1))
        for _game in range(cargs.n_games):
            done = False
            start = time.time()
            for _iter in count():
                if cargs.show_screen:
                    env.render()
                    
                """ initialize """
                actions, state_vals, log_probs, rewards, soft_state, \
                    soft_agent_pos, pred_acts, exp_rewards = [[[], []] for i in range(8)]
                    
                """ update by step """
                for i in range(env.num_players):
                    soft_state[i] = env.get_observation(i)
                    soft_agent_pos[i] = env.get_agent_pos(i)
                    pred_acts[i], exp_rewards[i] = agent[i].select_action_smart(soft_state[i], soft_agent_pos[i], env)

                """ select action for each agent """
                for agent_id in range(env.n_agents):
                    for i in range(env.num_players):
                        agent_state = env.get_states_for_step(soft_state[i])
                        # not change
                        agent_step = env.get_agent_for_step(agent_id, soft_agent_pos)
                        act, log_p, state_val = 0, 0, 0
                        if random.random() < lr_super[i]:
                            act, log_p, state_val = agent[i].select_action_by_exp(
                                agent_state, agent_step, pred_acts[i][agent_id])
                        else:
                            act, log_p, state_val = agent[i].select_action(agent_state, agent_step)
                                
                        soft_state[i] = env.soft_step_(agent_id, soft_state[i], act, soft_agent_pos[i])
                        state_vals[i].append(state_val)
                        actions[i].append(act)
                        log_probs[i].append(log_p)
                # actions[1] = [np.random.randint(0, env.n_actions - 1) for _ in range(env.n_agents)]
                # actions[1] = [0] * env.n_agents
                # actions[1] = pred_acts[1]
                next_state, final_reward, done, _ = env.step(actions[0], actions[1], cargs.show_screen)
                for i in range(env.n_agents):
                    rewards[0].append(final_reward)
                    rewards[1].append(- final_reward)
                    for j in range(env.num_players):
                        if pred_acts[j][i] == actions[j][i]:
                            reward = exp_rewards[j][i]
                            beta = 0.9
                            rewards[j][i] = rewards[j][i] * (1 - beta)  + beta * reward
                        agent[j].model.store(log_probs[j][i], state_vals[j][i], rewards[j][i])
                if done:
                    score[0].append(env.players[0].total_score)
                    score[1].append(env.players[1].total_score)
                    if env.players[0].total_score > env.players[1].total_score:
                        cnt_w += 1
                    else:
                        cnt_l += 1
                    break
            agent[0].learn()
            agent[1].learn()
            end = time.time()
            if _ep > 3:
                l_val[0].append(agent[0].value_loss)
                l_val[1].append(agent[1].value_loss)
                wl[0].append(cnt_w)
                wl[1].append(cnt_l)
                for i in range(2):
                    wl_mean[i].append(np.mean(wl[i]))
                    score_mean[i].append(np.mean(score[i]))
                    l_val_mean[i].append(np.mean(l_val[i]))
            
            env.soft_reset()
        if _ep % 50 == 49:
            if cargs.visualize:
                plot(wl_mean, vtype = 'Win')
                plot(score_mean, vtype = 'Score')
                plot(l_val_mean, vtype = 'Loss_Value')
                print("Time: {0: >#.3f}s". format(1000*(end - start)))
            if args[0].saved_checkpoint:
                agent[0].save_models()
                # torch.save(agent[0].model.state_dict(), checkpoint_path_1)
            if args[1].saved_checkpoint:
                agent[1].save_models()
                # torch.save(agent[1].model.state_dict(), checkpoint_path_2)
                # print('Completed episodes')
        # lr_super *= 0.999
        env = Environment(data.get_random_map(), cargs.show_screen, cargs.max_size)
예제 #49
0
class TestUM(unittest.TestCase):

    def setUp(self):
        self.w1 = WeatherModel(1)
        self.w2 = WeatherModel(2)
        self.e1 = Environment(10,15)
        self.e2 = Environment(20,25)

        loc = [2, 1]
        self.tile = self.e1.get_tile(loc)
        self.teff1 = Teff(self.tile)

        # self.d1 = Deer(self.tile)

    def tearDown(self):
        pass

    # Weather Model Tests
    def test_weatherModel_days_in_year(self):
        self.assertEqual(self.w1.totalDays, 365, "Total days is incorrect")
        self.assertEqual(self.w2.totalDays, 730, "Total days is incorrect")

    def test_weatherModel_years(self):
        self.assertEqual(self.w1.numYears, 1, "Number of years is incorrect")
        self.assertEqual(self.w2.numYears, 2, "Number of years is incorrect")

    def test_weatherModel_days_property(self):
        self.assertEqual(self.w1.totalDays, len(self.w1.days), "Total days must equal length of day property")

    def test_weatherModel_sunlight(self):
        for i in range(0, self.w1.days.size):
            self.assertLess(self.w1.days[i].sun, 24, "A day cannot have more than 24 hours of sunlight")
            self.assertGreater(self.w1.days[0].sun, 0, "A day cannot have less than 0 hours of sunlight")

        for i in range(0, self.w2.days.size):
            self.assertLess(self.w2.days[i].sun, 24, "A day cannot have more than 24 hours of sunlight")
            self.assertGreater(self.w2.days[0].sun, 0, "A day cannot have less than 0 hours of sunlight")

    def test_weatherModel_precipitation(self):
        for i in range(0, self.w1.days.size):
            self.assertGreaterEqual(self.w1.days[0].rain, 0, "A day cannot have less than 0 inches of precipitation")

        for i in range(0, self.w2.days.size):
            self.assertGreaterEqual(self.w2.days[0].rain, 0, "A day cannot have less than 0 inches of precipitation")

    # Environment Tests
    def test_environment_width(self):
        self.assertEqual(self.e1.width, 10, "Initial width for e1 is 10")
        self.assertEqual(self.e2.width, 20, "Initial width for e2 is 20")

    def test_environment_height(self):
        self.assertEqual(self.e1.height, 15, "Initial height for e1 is 15")
        self.assertEqual(self.e2.height, 25, "Initial height for e2 is 25")

    def test_environment_teff_mass(self):
        self.assertEqual(self.e1.teff_total_mass, 0, "Initial mass for e1 is 0")
        self.assertEqual(self.e2.teff_total_mass, 0, "Initial mass for e2 is 0")

    def test_environment_valid_location(self):
        loc1 = [2,2]
        self.assertEqual(self.e1.is_location_valid(loc1), True, "Location [2, 2] is valid")
        self.assertEqual(self.e2.is_location_valid(loc1), True, "Location [2, 2] is valid")

        loc2 = [-1, -1]
        self.assertEqual(self.e1.is_location_valid(loc2), False, "Location [-1, -1] is invalid")
        self.assertEqual(self.e2.is_location_valid(loc2), False, "Location [-1, -1] is invalid")

        loc3 = [-1, 1]
        self.assertEqual(self.e1.is_location_valid(loc3), False, "Location [-1, 1] is invalid")
        self.assertEqual(self.e2.is_location_valid(loc3), False, "Location [-1, 1] is invalid")

        loc4 = [1, -1]
        self.assertEqual(self.e1.is_location_valid(loc4), False, "Location [1, -1] is invalid")
        self.assertEqual(self.e2.is_location_valid(loc4), False, "Location [1, -1] is invalid")

        loc5 = [40, 40]
        self.assertEqual(self.e1.is_location_valid(loc5), False, "Location [40, 40] is invalid")
        self.assertEqual(self.e2.is_location_valid(loc5), False, "Location [40, 40] is invalid")

    def test_environment_distance(self):
        loc1 = [0, 1]
        loc2 = [0, 2]
        loc3 = [0, 3]
        loc4 = [-1, 1]
        loc5 = [1, 2]

        self.assertEqual(self.e1.get_distance(loc1, loc2), 1, "Distance is one")
        self.assertEqual(self.e2.get_distance(loc1, loc2), 1, "Distance is one")

        self.assertEqual(self.e1.get_distance(loc1, loc3), 2, "Distance is two")
        self.assertEqual(self.e2.get_distance(loc1, loc3), 2, "Distance is two")

        self.assertEqual(self.e1.get_distance(loc1, loc4), 1, "Distance is one")
        self.assertEqual(self.e2.get_distance(loc1, loc4), 1, "Distance is one")

        self.assertEqual(self.e1.get_distance(loc1, loc5), math.sqrt(2), "Distance is square root of two")
        self.assertEqual(self.e2.get_distance(loc1, loc5), math.sqrt(2), "Distance is square root of two")


        self.assertEqual(self.e1.get_distance(loc2, loc1), 1, "Distance is one")
        self.assertEqual(self.e2.get_distance(loc2, loc1), 1, "Distance is one")

        self.assertEqual(self.e1.get_distance(loc3, loc1), 2, "Distance is two")
        self.assertEqual(self.e2.get_distance(loc3, loc1), 2, "Distance is two")

        self.assertEqual(self.e1.get_distance(loc4, loc1), 1, "Distance is one")
        self.assertEqual(self.e2.get_distance(loc4, loc1), 1, "Distance is one")

        self.assertEqual(self.e1.get_distance(loc5, loc1), math.sqrt(2), "Distance is square root of two")
        self.assertEqual(self.e2.get_distance(loc5, loc1), math.sqrt(2), "Distance is square root of two")

    def test_environment_tile_location(self):
        loc1 = [2, 1]
        t1 = self.e1.get_tile(loc1)
        t2 = self.e2.get_tile(loc1)

        self.assertEqual(t1.tile_x, 2, "X coordinate is 2")
        self.assertEqual(t1.tile_y, 1, "Y coordinate is 1")

        self.assertEqual(t2.tile_x, 2, "X coordinate is 2")
        self.assertEqual(t2.tile_y, 1, "Y coordinate is 1")


        loc2 = [-1 ,1]
        t3 = self.e1.get_tile(loc2)
        t4 = self.e2.get_tile(loc2)

        self.assertEqual(t3, None, "-1 is and invalid x coordinate")
        self.assertEqual(t4, None, "-1 is and invalid x coordinate")


    # Teff tests
    def test_teff_initial_weight(self):
        self.assertEqual(self.teff1.current_weight, 167, "Initial weight is 167 pounds")
        self.assertEqual(self.teff1.get_amount(), 167, "Initial weight is 167 pounds")

    # def test_teff_weight_change(self):
    #     newWeight = 10
    #     self.teff1.set_weight(newWeight)
    #
    #     self.assertEqual(self.teff1.current_weight, newWeight, "Weight must be updated by set_weight method")
    #
    #     self.teff1.set_weight(-1)
    #
    #     self.assertEqual(self.teff1.current_weight, newWeight, "Weight cannot be updated to be negative")
    #     self.assertNotEqual(self.teff1.current_weight, -1, "Weight cannot be negative")

    def test_teff_update(self):
        self.teff1.updates = False

        self.assertEqual(self.teff1.update(), None, "Updates is set to false")

    # Deer Tests
    def test_deer_initial_weight(self):
        self.assertLess(self.d1.weight, 300, "Starting weight must be less than 300 pounds")
        self.assertGreaterEqual(self.d1.weight, 110,
                                "Starting weight must be greater or equal to 110 pounds")

    def test_deer_starve(self):

        self.assertEqual(self.d1.state, State.alive, "Deer should be alive")

        self.d1.weight = self.d1.max_weight * 0.6
        self.d1.check_starve()

        self.assertEqual(self.d1.state, State.dead, "Deer should die once it's weight is below 70% of it's max weight")

        self.d1.weight = self.d1.max_weight
        self.d1.check_starve()

        self.assertEqual(self.d1.state, State.dead, "Animal state should not change from dead to alive")

    # Tile Tests
    def test_tile_location(self):
        self.assertEqual(self.tile.tile_x, 2, "Tile's x location is set to 2 in set up method")
        self.assertEqual(self.tile.tile_y, 1, "Tile's y location is set to 1 in set up method")

    def test_tile_add_agent(self):
        preAgents = len(self.tile.agent_mapping)
        self.tile.add_agent(self.d1)
        postAgents = len(self.tile.agent_mapping)
        self.assertGreater(postAgents, preAgents,
                           "Adding an agent to a tile should increase agent_mapping")

    def test_tile_weight_changed(self):
        s = Soil(1, self.tile)
        preWeight = self.tile.get_mass_and_totals()
        self.tile.weight_changed(type(s), 10)
        postWeight = self.tile.get_mass_and_totals()
        self.assertNotEqual(preWeight,postWeight, "Adding weight should change total mass")
예제 #50
0
import argparse
from src.environment import Environment
"""
Helper script for the Viper tool chain.
Runs tests, measures time and kills processes that take too long.
"""


def print_header():
    print()
    print("Viper tool chain runner")
    print("-----------------------")
    print()


print_header()
parser = argparse.ArgumentParser(description='Viper tool chain runner.')
parser.add_argument('config_file',
                    help='the configuration file for this script.')
args = parser.parse_args()
env = Environment()
env.exec(args.config_file)
env.analyze()
예제 #51
0
from argparse import ArgumentParser
from src.agents import TDAgent, KPlyAgent, HumanAgent
from src.environment import Environment

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('--export_dir')
    parser.add_argument('--sign',
                        type=int,
                        choices=[-1, 1],
                        default=1,
                        required=False)
    parser.add_argument('--k', type=int, default=1, required=False)
    args = parser.parse_args()
    print(args)

    sgn = args.sign
    human = HumanAgent(sign=sgn)

    opponent = TDAgent.from_saved_model(sign=-sgn, export_dir=args.export_dir)
    opponent = KPlyAgent(sign=-sgn, k=args.k, agent=opponent)

    agents = [human, opponent]
    env = Environment(agents)
    env.play(verbose=True)
예제 #52
0
def test():
    data = Data(cargs.min_size, cargs.max_size)
    env = Environment(data.get_random_map(), cargs.show_screen, cargs.max_size)
    agent = [Agent(env, args[0]), Agent(env, args[1])]
    wl_mean, score_mean = [[deque(maxlen=10000),
                            deque(maxlen=10000)] for _ in range(2)]
    wl, score = [[deque(maxlen=1000), deque(maxlen=1000)] for _ in range(2)]
    cnt_w, cnt_l = 0, 0
    exp_rate = [args[0].exp_rate, args[1].exp_rate]
    # agent[0].model.load_state_dict(torch.load(checkpoint_path_1, map_location = agent[0].model.device))
    # agent[1].model.load_state_dict(torch.load(checkpoint_path_2, map_location = agent[1].model.device))

    for _ep in range(cargs.n_epochs):
        if _ep % 10 == 9:
            print('Testing_epochs: {}'.format(_ep + 1))
        done = False
        start = time.time()
        current_state = env.get_observation(0)
        for _iter in range(env.n_turns):
            if cargs.show_screen:
                env.render()
            """ initialize """
            actions, soft_state, soft_agent_pos, pred_acts, exp_rewards = \
                [[[], []] for i in range(5)]
            """ update by step """
            for i in range(env.num_players):
                soft_state[i] = env.get_observation(i)
                soft_agent_pos[i] = env.get_agent_pos(i)
                pred_acts[i], exp_rewards[i] = agent[i].select_action_smart(
                    soft_state[i], soft_agent_pos[i], env)
            """ select action for each agent """
            for agent_id in range(env.n_agents):
                for i in range(env.num_players):
                    ''' get state to forward '''
                    state_step = env.get_states_for_step(current_state)
                    agent_step = env.get_agent_for_step(
                        agent_id, i, soft_agent_pos)
                    ''' predict from model'''
                    if random.random() < exp_rate[i]:
                        act = pred_acts[i][agent_id]
                    else:
                        # print(i)
                        act = agent[i].get_action(state_step, agent_step)
                        # act, _, _ = agent[i].select_action(state_step, agent_step)
                    ''' convert state to opponent state '''
                    env.convert_to_opn_obs(current_state, soft_agent_pos)
                    ''' storage infomation trainning'''
                    actions[i].append(act)
                ''' last action to fit next state '''
                acts = [actions[0][-1], actions[1][-1]]
                current_state, temp_rewards = env.soft_step_2(
                    agent_id, current_state, acts, soft_agent_pos)

            # actions[1] = [np.random.randint(0, env.n_actions - 1) for _ in range(env.n_agents)]
            # actions[1] = [0] * env.n_agents
            # actions[1] = pred_acts[1]
            current_state, final_reward, done, _ = env.step(
                actions[0], actions[1], cargs.show_screen)
            if done:
                score[0].append(env.players[0].total_score)
                score[1].append(env.players[1].total_score)
                if env.players[0].total_score > env.players[1].total_score:
                    cnt_w += 1
                else:
                    cnt_l += 1
                break

        end = time.time()

        wl[0].append(cnt_w)
        wl[1].append(cnt_l)
        for i in range(2):
            wl_mean[i].append(np.mean(wl[i]))
            score_mean[i].append(np.mean(score[i]))

        if _ep % 50 == 49:
            plot(wl_mean, vtype='Win')
            plot(score_mean, vtype='Score')
            print("Time: {0: >#.3f}s".format(1000 * (end - start)))
        env.soft_reset()
예제 #53
0
    def central_bank__get_account_num_transactions(self, args):
        import os
        from src.bank import Bank
        from src.central_bank import CentralBank
        from src.household import Household
        from src.firm import Firm
        from src.environment import Environment  # needed for the bankDirectory

        text = "This test checks central_bank.get_account_num_transactions \n"
        text = text + "  The purpose of this method is to count the numbers of transaction for   \n"
        text = text + "  accounts banks hold. Our central bank has 3 transactions by default. \n"
        self.print_info(text)
        #
        # INITIALIZATION
        #
        environment_directory = str(args[0])
        identifier = str(args[1])
        log_directory = str(args[2])

        # Configure logging parameters so we get output while the program runs
        logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S',
                            filename=log_directory + identifier + ".log", level=logging.INFO)
        logging.info('START logging for test central_bank__get_account_num_transactions in run: %s',
                     environment_directory + identifier + ".xml")

        # Construct bank filename
        environment = Environment(environment_directory,  identifier)

        # get the bank_directory from the environment
        bank_directory = environment.bank_directory
        # and loop over all banks in the directory
        listing = os.listdir(bank_directory)
        bank_filename = bank_directory + listing[0]

        # generate a household
        household = Household()
        household.identifier = "test_household"
        environment.households.append(household)

        # generate a firm
        firm = Firm()
        firm.identifier = "test_firm"
        environment.firms.append(firm)

        # generate a bank
        bank = Bank()
        bank.identifier = "test_bank"
        environment.banks.append(bank)

        # generate a central bank
        cb = CentralBank()
        cb.identifier = "test_central_bank"
        environment.central_bank.append(cb)

        #
        # TESTING
        #

        environment.new_transaction("deposits", "",  cb.identifier, "test_firm",
                                    100, 0.0,  0, -1)
        environment.new_transaction("cash", "",  cb.identifier, "test_firm",
                                    200, 0.0,  0, -1)
        environment.new_transaction("loans", "",  cb.identifier, "test_firm",
                                    300, 0.0,  0, -1)

        num_transactions = 0.0          # counting all types in account together
        print(cb)
        # and checking if the number of transaction
        # is increasing by one
        for type in ["deposits",  "cash",  "loans"]:
                        if type == "deposits":
                                num_transactions = num_transactions + cb.get_account_num_transactions(type)
                                print("D = " + str(num_transactions))
                        if type == "cash":
                                num_transactions = num_transactions + cb.get_account_num_transactions(type)
                                print("D+M = " + str(num_transactions))
                        if type == "loans":
                                num_transactions = num_transactions + cb.get_account_num_transactions(type)
                                print("D+M+L = " + str(num_transactions))