def household__initialize_standard_household(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 household.initialize_standard_household \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 household__initialize_standard_household in run: %s', environment_directory + identifier + ".xml") # Construct household filename environment = Environment(environment_directory, identifier) # get the firm_directory from the environment household_directory = environment.household_directory # and loop over all firms in the directory listing = os.listdir(household_directory) householdFilename = household_directory + listing[0] # 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() environment.households.append(household) helper = Helper() helper.initialize_standard_household(household, environment) # # TESTING # print(household)
def __init__(self, dim=1): self.helper = Helper() if dim == 1: (self.x_train, self.y_train), (self.x_test, self.y_test) = self.helper.get_cifar10_prepared() elif dim == 3: (self.x_train, self.y_train), (self.x_test, self.y_test) = self.helper.get_cifar10_prepared( dim=3) else: raise Exception( "Cifar 10 couldn't be initialized with dims != 3 or != 1")
def __init__(self, asyncio_event_loop): self.log = Logger.get_logger_instance() self.__helper = Helper() self.loop = asyncio_event_loop current_dir_path = path.dirname(__file__) config_path = path.join(current_dir_path, '../config/production.json') self.__config = read_json(config_path) self.queue_handler = TaskHandler( self.__config["queue"]["job_type"], self.__config["queue"]["task_type"], self.__config["queue"]["job_manager_url"], self.__config["queue"]["heartbeat_manager_url"], self.__config["queue"]["heartbeat_interval_ms"], self.log) self.__exportImage = ExportImage(self.queue_handler, self.loop)
def launch_linear_model(): from src.models.processes.linear import create_model_pp helper = Helper() pp = PlantPathology() # pp.plot_image(5) x_train, y_train = pp.train_generator.next() x_test, y_test = pp.valid_generator.next() model = create_model_pp() helper.fit(model, x_train, y_train, batch_size=1024, epochs=100, validation_data=(x_test, y_test), process_name="linear")
def __init__(self, client: discord.Client): self.h = Helper() self.b = BucketHandler() self.SUCCESS_CHANNEL_ID = self.h.get_success_channel_id() self.VERIFIED_ROLE_ID = self.h.get_verified_role_id() # Set up Twitter API with open("configuration/twitter.json") as f: j = json.load(f) auth = tweepy.OAuthHandler(str(j["twitter_consumer_key"]), str(j["twitter_consumer_secret"])) auth.set_access_token(str(j["twitter_access_token"]), str(j["twitter_access_token_secret"])) self.twitter_api = tweepy.API(auth) print('[VERIFY] Logged into Twitter.') self.client = client
def __init__(self, queue_handler, asyncio_eventloop): self.log = Logger.get_logger_instance() self.__helper = Helper() self.warp_percent = 70 self.upload_percent = 1 self.overview_percent = 100 - self.upload_percent - self.warp_percent self.queue_handler = queue_handler self.loop = asyncio_eventloop # Get current files path current_dir_path = path.dirname(__file__) # Get config path config_path = path.join(current_dir_path, '../config/production.json') self.__config = read_json(config_path) # Get path for "zoom level to resolution" json zoom_resolution_mapping_path = path.join( current_dir_path, 'constant/zoomLevelToResolution.json') self.__zoom_to_resolution = read_json(zoom_resolution_mapping_path)
def model_test_1(): (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() helper = Helper() helper.debug_dataset_shapes("cifar_10", [x_train, y_train, x_test, y_test]) X_train = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [5, 6, 1, 0], [6, 7, 4, 2], [2, 1, 3, 1], [3, 9, 4, 2]]) Y_train = np.array([[1, 1, 1, 1, 0, 0, 0, 0]]) X_test = np.array([[16, 17, 18, 19], [10, 18, 19, 17]]) Y_test = np.array([[1, 0]]) X_train = X_train.reshape(8, 4) Y_train = Y_train.reshape(8, 1) X_test = X_test.reshape(2, 4) Y_test = Y_test.reshape(2, 1) helper.debug_dataset_shapes("dummy", [X_train, Y_train, X_test, Y_test]) model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(128, input_shape=X_train.shape[1:])) model.add(tf.keras.layers.Dense(128)) model.add(tf.keras.layers.Dense(128)) model.compile(optimizer='adam', loss=tf.keras.losses.sparse_categorical_crossentropy, metric=['accuracy']) model.build() model.summary() model.fit(X_train, Y_train, epochs=100, batch_size=64, validation_data=(X_test, Y_test))
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)
def __init__( self, process_name=None, dropouts=None, dropout_values=None, optimizers=None, activation_functions=None, batch_sizes=None, filter_size=None, padding_values=None, kernel_sizes=None ): if process_name is not None: self.process_name = process_name self.dropouts = dropouts self.dropout_values = dropout_values self.optimizers = optimizers self.activation_functions = activation_functions self.batch_sizes = batch_sizes if process_name.lower() == "convnet": self.filter_size = filter_size self.padding_values = padding_values self.kernel_sizes = kernel_sizes self.helper = Helper()
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())
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))
def test_mlp(self): self.assertTrue(Helper().scenarios_works("mlp"))
default='result/', type=str, help='The output path of the trained network model.') parser.add_argument('--logdir', default='logs/', type=str, help='Logging path.', required=False) parser.add_argument('--seed', default=42, type=int, help='Random seed for reproducable results.', required=False) parser.add_argument('--test', action='store_true', help='Test the model.') parser.add_argument('--trained_model', type=str, help='The path of the trained model for test.') parser.add_argument('--verbose', default=1, help='Show all messages.') paras = parser.parse_args() config = yaml.safe_load(open(paras.config, 'r')) if not paras.test: # Train a vulnerability detection model from src.helper import Trainer as Helper else: from src.helper import Tester as Helper helper = Helper(config, paras) helper.exec() K.clear_session()
def test_rnn(self): self.assertTrue(Helper().scenarios_works("rnn"))
def test_convnet(self): self.assertTrue(Helper().scenarios_works("convnet"))
def test_invalid_json_fields_validate(self): with self.assertRaises(Exception): Helper().json_fields_validate(invalid_mock_task)
self.terminal_output.append(f"{HELPER[0].get_current_time()}{output}") self.terminal_output.ensureCursorVisible() def display_end_line(self): """ Possibility to end the line without the timestamp """ #Create and of Line time.sleep(TEXT_DELAY) self.terminal_output.append("<br>") self.terminal_output.ensureCursorVisible() def open_help(self): """ Method to open the help site """ # Load URL from consts and open it url = QUrl(HELP_URL) QDesktopServices.openUrl(url) if __name__ == "__main__": # Create our Helper object HELPER.append(Helper()) app = QApplication(sys.argv) win = Window() win.show() sys.exit(app.exec())
""" Delete all training data """ import sys import os import shutil import zipfile from send2trash import send2trash from src.helper import Helper if __name__ == "__main__": dataset_name = sys.argv[1] helper = Helper() dir_name = f"./data/{dataset_name}/" print(f"Starting dataset zip extraction in {dir_name}...") try: helper.create_dir(dir_name) except Exception: print("Error: Could not create directory.") zip_name = f"{dataset_name}.zip" if not os.path.isfile(zip_name): print( f"Error: {zip_name} is not a file.\nAborted dataset zip extraction." ) else: # move zip to dir full_new_path = f"{dir_name}/{zip_name}" shutil.move(f"{zip_name}", f"{full_new_path}") print(f"Success: {zip_name} moved to {full_new_path}.")
def test_valid_json_fields_validate(self): result = Helper().json_fields_validate(valid_mock_task) self.assertEqual(None, result)
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)
def consume_rationed(self, environment, time): # We want the consumption to be done in random pairs # We use rationing from market clearing class to do that # Price is static for this example, otherwise we can't use rationing # and need some other market clearing price = 10.0 environment.variable_parameters["price_of_goods"] = price # We need a list of agents and their demand or supply # Supply is denoted with positive float, demand with negative float for_rationing = [] # Firms give us their supply, we assume that since the goods are # perishable their supply is all they have in stock from src.helper import Helper helper = Helper() for firm in environment.firms: # Firms produce based on their capital, for generality # we use their net capital, as in their capital stock # minus the capital owned of other agents capital = 0.0 for tranx in firm.accounts: # This is own capital stock if tranx.type_ == "capital" and tranx.from_ == firm: capital = capital + tranx.amount # And here is the ownership of other agents' stock if tranx.type_ == "capital" and tranx.to == firm: capital = capital - tranx.amount # We find the amount produced through the Cobb-Douglas function amount = helper.cobb_douglas(firm.get_account("labour"), capital, firm.total_factor_productivity, firm.labour_elasticity, firm.capital_elasticity) * price # And assume firm wants to sell whole production given the perishable nature of the goods for_rationing.append([firm, amount]) # Households give use their demand, we assume that they want to # consume the part of their wealth (cash and deposits) that they # do not want to save (determined through propensity to save) # We denote demand in units of the goods, so we divide the cash # households want to spend by price to get the demand for household in environment.households: demand = 0.0 wealth = 0.0 # For generality we calculate net wealth for this, that is the # amount of deposits they carry minus the amount of loans for tranx in household.accounts: if tranx.type_ == "deposits" and tranx.from_ == household: wealth = wealth + tranx.amount if tranx.type_ == "loans" and tranx.to == household: wealth = wealth - tranx.amount # Then the demand is determined by the agent's propensity to save # and the wealth calculated above demand = -((wealth * (1 - household.propensity_to_save)) / price) for_rationing.append([household, demand]) # We import the market clearing class from market import Market # Put the appropriate settings, i.e. # tolerance of error, resolution of search # and amplification for exponential search # This does not matter for rationing # But in principle we need to initialize # with these values market = Market("market") # And we find the rationing, ie the amounts # of goods sold between pairs of agents # We find the actual trades rationed = market.rationing_proportional(for_rationing) # Then we go through the rationing # and move the goods and cash appropriately for ration in rationed: # # A (from) L (to) # bank loan deposit # household goods loan # firm deposit goods # # TODO: in the new version this may be irrelevant environment.new_transaction("goods", "", ration[1].identifier, ration[0].identifier, ration[2], 0, 0, -1) # The below makes sure the allocations of loans are correct # That is the banks don't allow overdraft for buying # consumption goods by the households to_finance = ration[2] * price itrange = list(range(0, len(environment.banks))) # And randomise this list for the purposes of iterating randomly random.shuffle(itrange) # And we iterate over the agents randomly by proxy of iterating # through their places on the list [agents] for i in itrange: current_bank = self.environment.banks[i] # We find how much in deposits the household has deposits_available = 0.0 for tranx in ration[1].accounts: if tranx.type_ == "deposits" and tranx.to == current_bank: deposits_available = deposits_available + tranx.amount # This should be irrelevant, but for completeness: if tranx.type_ == "loans" and tranx.from_ == current_bank: deposits_available = deposits_available - tranx.amount # We find the amount of deposits the household can spend for this particular bank current_amount = min(to_finance, deposits_available) # And add the appropriate transactions environment.new_transaction( "deposits", "", ration[0].identifier, current_bank.identifier, current_amount, current_bank.interest_rate_deposits, 0, -1) environment.new_transaction( "loans", "", current_bank.identifier, ration[1].identifier, current_amount, current_bank.interest_rate_loans, 0, -1) to_finance = to_finance - current_amount # We print the action of selling to the screen print("%s sold %d units of goods at a price %f to %s at time %d." ) % (ration[0].identifier, ration[2], price, ration[1].identifier, time) logging.info(" goods consumed on step: %s", time)
model.add(LSTM(n_neurons)) else: if dropout is not None: model.add( LSTM(n_neurons, dropout=dropout, return_sequences=True)) else: model.add(LSTM(n_neurons, return_sequences=True)) model.add(Dense(10, activation="sigmoid")) model.compile(optimizer=optimizer, loss=sparse_categorical_crossentropy, metrics=[sparse_categorical_accuracy]) return model if __name__ == "__main__": model = create_model(2, "adam", 64, None) from src.helper import Helper from src.cifar10 import Cifar10 model.summary() cifar10 = Cifar10(dim=2) Helper().fit(model, cifar10.x_train, cifar10.y_train, 1024, 100, (cifar10.x_test, cifar10.y_test), "rnn", std_logs=True)
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))
def test_resnet(self): self.assertTrue(Helper().scenarios_works("resnet"))
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)
def firm__get_parameters_from_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 # needed for the bankDirectory text = "This test checks firm.get_parameters_from_file \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 firm__get_parameters_from_file in run: %s', environment_directory + identifier + ".xml") # Construct firm filename environment = Environment(environment_directory, identifier) # get the firm_directory from the environment firm_directory = environment.firm_directory # and loop over all firms in the directory listing = os.listdir(firm_directory) firmFilename = firm_directory + listing[0] # generate a household household = Household() household.identifier = "test_household" environment.households.append(household) # generate a bank bank = Bank() bank.identifier = "test_bank" environment.banks.append(bank) # generate a firm firm = Firm() environment.firms.append(firm) helper = Helper() helper.initialize_standard_firm(firm, environment) firm.get_parameters_from_file(firmFilename, environment) # # TESTING # # test whether the parameters are read properly text = "Identifier has been read as follows: \n" text = text + "Identifier: " text = text + firm.identifier text = text + "\n" text = text + "Productivity: " text = text + str(firm.parameters["productivity"]) self.print_info(text)
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)
def consume_rationed(self, environment, time): # We want the consumption to be done in random pairs # We use rationing from market clearing class to do that # Price is static for this example, otherwise we can't use rationing # and need some other market clearing price = 10.0 environment.variable_parameters["price_of_goods"] = price # We need a list of agents and their demand or supply # Supply is denoted with positive float, demand with negative float for_rationing = [] # Firms give us their supply, we assume that since the goods are # perishable their supply is all they have in stock from src.helper import Helper helper = Helper() for firm in environment.firms: # amount = round(helper.leontief([firm.get_account("labour")], [1/firm.productivity]), 0) amount = helper.cobb_douglas( firm.get_account("labour"), firm.get_account("capital"), firm.total_factor_productivity, firm.labour_elasticity, firm.capital_elasticity) * price for_rationing.append([firm, amount]) # Households give use their demand, we assume that they want to # consume the part of their wealth (cash and deposits) that they # do not want to save (determined through propensity to save) # We denote demand in units of the goods, so we divide the cash # households want to spend by price to get the demand for household in environment.households: demand = 0.0 # demand = -round(((household.get_account("deposits") * (1 - household.propensity_to_save)) / price), 0) demand = -((household.get_account("deposits") * (1 - household.propensity_to_save)) / price) # demand = -household.get_account("deposits")/price for_rationing.append([household, demand]) # We import the market clearing class from market import Market # Put the appropriate settings, i.e. # tolerance of error, resolution of search # and amplification for exponential search # This does not matter for rationing # But in principle we need to initialize # with these values market = Market("market") # And we find the rationing, ie the amounts # of goods sold between pairs of agents # TESTING THE ABSTRACT RATIONING # The matching function means that all pairs will have the same priority def matching_agents_basic(agent_one, agent_two): return 1.0 # The below function means that all pairs are allowed def allow_match_basic(agent_one, agent_two): return True # We find the actual trades rationed = market.rationing_abstract(for_rationing, matching_agents_basic, allow_match_basic) # Then we go through the rationing # and move the goods and cash appropriately for ration in rationed: # # A (from) L (to) # bank loan deposit # household goods loan # firm deposit goods # environment.new_transaction("goods", "", ration[1].identifier, ration[0].identifier, ration[2], 0, 0, -1) random_bank = random.choice(environment.banks) environment.new_transaction("deposits", "", ration[0].identifier, random_bank.identifier, ration[2] * price, random_bank.interest_rate_deposits, 0, -1) environment.new_transaction("loans", "", random_bank.identifier, ration[1].identifier, ration[2] * price, random_bank.interest_rate_loans, 0, -1) # We print the action of selling to the screen print("%s sold %d units of goods at a price %f to %s at time %d." ) % (ration[0].identifier, ration[2], price, ration[1].identifier, time) logging.info(" goods consumed on step: %s", time)
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())
def test_valid_json_load(self): valid_parsed_task = json.dumps(valid_mock_task) result = Helper().load_json(valid_parsed_task) self.assertEqual(dict, type(result))