def __init__(self): self.server = None log_folder = program.get_base_dir('logs') if not os.path.exists(log_folder): os.mkdir(log_folder) log_file = os.path.join(log_folder, 'cot_plot.log') LOG_CONF['handlers']['logfile']['filename'] = log_file logging.config.dictConfig(LOG_CONF) self.logger = logging.getLogger(__name__) self.logger.debug( "==============================================================") self.logger.debug("CoT Plot web werver started") self.pyramid_settings = { 'reload_all': False, 'debug_all': True, 'pyramid.debug_all': True, 'pyramid.debug_routematch': True, 'pyramid.reload_all': False, 'cotplot.secret': '$nif2-EERG1$£03mf£AF$&^-' } self.config = Configurator(settings=self.pyramid_settings, root_factory='src.cot_plot.resources.Root') self.settings = settings.Settings() self.updater = Updater()
def initialize(self, environment): self.identifier = environment.identifier self.updater = Updater(environment) self.current_step = 0 self.num_sweeps = int(environment.static_parameters['num_sweeps']) #For measurement self.sweep_result_list = []
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"))
def updater__set_model_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 from src.transaction import Transaction from src.market import Market from src.updater import Updater text = "This test checks updater.set_model_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 updater__set_model_parameters 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) model.model_parameters = {"test": "model parameters"} print("Model's parameters:") print(model.get_model_parameters()) print("Changing model's parameters:...") model.model_parameters = {"new": "model parameters"} print("Model's parameters:") print(model.get_model_parameters())
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)
class Runner(object): # from environment import Environment # # VARIABLES # # # METHODS # #------------------------------------------------------------------------- # __init__ #------------------------------------------------------------------------- def __init__(self): pass #------------------------------------------------------------------------- #------------------------------------------------------------------------- # initialize() #------------------------------------------------------------------------- def initialize(self, environment): self.environment = environment self.updater = Updater(self.environment) self.shocker = Shock() #------------------------------------------------------------------------- #------------------------------------------------------------------------- # do_run #------------------------------------------------------------------------- def do_run(self, measurement, debug): # loop over all time steps and do the updating for i in range(self.environment.parameters.numSweeps): # the update step self.updater.do_update(self.environment, i, debug) # check if there is a shock at the current time step if (int(self.environment.get_state(i).shockType) != 0): self.shocker.do_shock(self.environment, int(i)) self.environment.get_state(i).shockType = 0 # do the measurement measurement.do_measurement(self.environment.banks)
def updater__remove_perishable(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.remove_perishable \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__remove_perishable in run: %s', environment_directory + identifier + ".xml") # Construct household filename environment = Environment(environment_directory, identifier) # # TESTING # model = Updater(environment) model.sell_labour(environment, 0) model.consume_rationed(environment, 0) model.net_loans_deposits(environment, 0) print(environment.households[0]) print("Removing perishable") model.remove_perishable(environment, 0) print(environment.households[0])
def test_updater(self) -> None: ori = parseQuery("""PREFIX dc: <http://purl.org/dc/elements/1.1/> PREFIX ns: <http://example.org/ns#> SELECT ?title (?p*(1-?discount) AS ?price) { ?x ns:price ?p . ?x dc:title ?title . ?x ns:discount ?discount }""") frame = { '@context': { 'price': { '@id': 'http://example.org/ns#price' }, 'title': { '@id': 'http://purl.org/dc/elements/1.1/title' } }, 'price': {}, 'title': {} } u = Updater() res = u.update(ori, frame).dump().split('\n')[0].replace('\n', '') expect = """[[PrefixDecl_{'prefix': 'dc', 'iri': rdflib.term.URIRef('http://purl.org/dc/elements/1.1/')}, \ PrefixDecl_{'prefix': 'ns', 'iri': rdflib.term.URIRef('http://example.org/ns#')}], ConstructQuery_{'template': \ [([rdflib.term.Variable('title'), rdflib.term.URIRef('http://example.org/ns#price'), rdflib.term.Variable\ ('var1')], {}), ([rdflib.term.Variable('title'), pname_{'prefix': 'dc', 'localname': 'title'}, rdflib.term.\ Variable('var2')], {})], 'where': GroupGraphPatternSub_{'part': [TriplesBlock_{'triples': [([rdflib.term.\ Variable('x'), PathAlternative_{'part': [PathSequence_{'part': [PathElt_{'part': pname_{'prefix': 'ns', \ 'localname': 'price'}}]}]}, rdflib.term.Variable('p')], {}), ([rdflib.term.Variable('x'), PathAlternative_\ {'part': [PathSequence_{'part': [PathElt_{'part': pname_{'prefix': 'dc', 'localname': 'title'}}]}]}, rdflib.\ term.Variable('title')], {}), ([rdflib.term.Variable('x'), PathAlternative_{'part': [PathSequence_{'part': \ [PathElt_{'part': pname_{'prefix': 'ns', 'localname': 'discount'}}]}]}, rdflib.term.Variable('discount')], \ {})]}, OptionalGraphPattern_{'graph': TriplesBlock_{'triples': [([rdflib.term.Variable('title'), rdflib.term.\ URIRef('http://example.org/ns#price'), rdflib.term.Variable('var1')], {})]}}, OptionalGraphPattern_{'graph': \ TriplesBlock_{'triples': [([rdflib.term.Variable('title'), pname_{'prefix': 'dc', 'localname': 'title'}, \ rdflib.term.Variable('var2')], {})]}}]}}]""" self.assertEqual(res.strip(), expect)
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])
class Runner(BaseRunner): # # # VARIABLES # # identifier = "" num_simulations = 0 current_step = 0 # # # METHODS # # # ------------------------------------------------------------------------- # __init__ # ------------------------------------------------------------------------- def __init__(self, environment): self.initialize(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_identifier # ------------------------------------------------------------------------- def get_identifier(self): return self.identifier # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_identifier # ------------------------------------------------------------------------- def set_identifier(self, _value): super(Runner, self).set_identifier(_value) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_num_simulations # ------------------------------------------------------------------------- def get_num_simulations(self): return self.num_simulations # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_num_simulations # ------------------------------------------------------------------------- def set_num_simulations(self, _value): super(Runner, self).set_num_simulaitons(_value) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # initialize() # ------------------------------------------------------------------------- def initialize(self, environment): self.identifier = environment.identifier self.num_sweeps = int(environment.num_sweeps) self.updater = Updater(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # do_run # ------------------------------------------------------------------------- def do_run(self, environment): # loop over all time steps and do the updating # We initialise the measurement class for writing outputs to csv # measurement = Measurement("Measurement", environment, self, {1: ["Step", "static", "self.runner.current_step"], # 2: ["Deposits", "dynamic", "self.environment.households[0].get_account", ["deposits"]]}, "TestMeasurement.csv") measurement = Measurement(environment, self) # And open the output file measurement.open_file() # For each update step for i in range(self.num_sweeps): print(environment.measurement_config) # the update step # append current step, this is mostly for measurements self.current_step = i # do the actual update self.updater.do_update(environment, i) # write the state of the system measurement.write_to_file() # HELPER, to be removed in production print(environment.households[0]) print(environment.firms[0]) # Close the output file at the end of the simulation measurement.close_file()
def initialize(self, environment): self.identifier = environment.identifier self.num_sweeps = int(environment.num_sweeps) self.updater = Updater(environment)
class Runner(BaseRunner): # # # VARIABLES # # identifier = "" num_simulations = 0 # # # METHODS # # # ------------------------------------------------------------------------- # __init__ # ------------------------------------------------------------------------- def __init__(self, environment): self.initialize(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_identifier # ------------------------------------------------------------------------- def get_identifier(self): return self.identifier # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_identifier # ------------------------------------------------------------------------- def set_identifier(self, _value): super(Runner, self).set_identifier(_value) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_num_simulations # ------------------------------------------------------------------------- def get_num_simulations(self): return self.num_simulations # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_num_simulations # ------------------------------------------------------------------------- def set_num_simulations(self, _value): super(Runner, self).set_num_simulaitons(_value) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # initialize() # ------------------------------------------------------------------------- def initialize(self, environment): self.identifier = environment.identifier self.num_sweeps = int(environment.num_sweeps) self.updater = Updater(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # do_run # ------------------------------------------------------------------------- def do_run(self, environment): # loop over all time steps and do the updating for i in range(self.num_sweeps): # the update step self.updater.do_update(environment, i) print(environment.firms[0]) print(environment.households[0])
def initialize(self, environment): self.identifier = environment.identifier self.num_sweeps = int(environment.static_parameters['num_sweeps']) self.updater = Updater(environment)
class Runner(BaseRunner): # # # VARIABLES # # identifier = "" num_sweeps = 0 # # # METHODS # # # ------------------------------------------------------------------------- # __init__ # ------------------------------------------------------------------------- def __init__(self, environment): self.initialize(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # initialize() # ------------------------------------------------------------------------- def initialize(self, environment): self.identifier = environment.identifier self.num_sweeps = int(environment.static_parameters['num_sweeps']) self.updater = Updater(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_identifier # ------------------------------------------------------------------------- def get_identifier(self): return self.identifier # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_identifier # ------------------------------------------------------------------------- def set_identifier(self, value): return super(Runner, self).set_identifier(value) # ------------------------------------------------------------------------- # get_num_sweeps # ------------------------------------------------------------------------- def get_num_sweeps(self): return self.num_sweeps # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_num_simulations # ------------------------------------------------------------------------- def set_num_sweeps(self, value): super(Runner, self).set_num_sweeps(value) # ------------------------------------------------------------------------- # do_run # ------------------------------------------------------------------------- def do_run(self, environment): # loop over all time steps and do the updating # For each update step measurement = Measurement(environment, self) measurement.open_file() for i in range(self.num_sweeps): self.current_step = i self.updater.do_update(environment) measurement.write_to_file() print("***\nThis run had %s sweeps and %s simulations") % ( self.num_sweeps, environment.static_parameters['num_simulations']) print( "Check the output file that was written as csv in the measurements folder\n***" ) # environment.print_parameters() # agent = Agent() # print(self.get_identifier()) # print(self.get_num_sweeps()) # print(environment.agents[0]) # print(environment.agents[1]) # parameters={'deposit_rate':-0.02} # agent.append_parameters(parameters) # print(agent.get_parameters()) measurement.close_file()
class Runner(BaseRunner): # # # VARIABLES # # identifier = "" num_sweeps = 0 current_step = 0 # # # METHODS # # # ------------------------------------------------------------------------- # __init__ # ------------------------------------------------------------------------- def __init__(self, environment): self.initialize(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_identifier # ------------------------------------------------------------------------- def get_identifier(self): return self.identifier # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_identifier # ------------------------------------------------------------------------- def set_identifier(self, _value): super(Runner, self).set_identifier(_value) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_num_sweeps # ------------------------------------------------------------------------- def get_num_sweeps(self): return self.num_sweeps # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_num_sweeps # ------------------------------------------------------------------------- def set_num_sweeps(self, _value): super(Runner, self).set_num_sweeps(_value) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # initialize() # ------------------------------------------------------------------------- def initialize(self, environment): self.identifier = environment.identifier self.num_sweeps = int(environment.num_sweeps) self.updater = Updater(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # do_run # ------------------------------------------------------------------------- def do_run(self, environment): # loop over all time steps and do the updating # We initialise the measurement class for writing outputs to csv # measurement = Measurement("Measurement", environment, self, {1: ["Step", "static", "self.runner.current_step"], # 2: ["Deposits", "dynamic", "self.environment.households[0].get_account", ["deposits"]]}, "TestMeasurement.csv") measurement = Measurement(environment, self) # And open the output file measurement.open_file() # We start the shock class as well shock_class = Shock() # For each update step for i in range(self.num_sweeps): # Do the shock: # First we check if the shock occurs at the current sweep # Then we run the shock procedure at the start of the update for shock in environment.shocks: if int(shock[0]) <= i+1 and int(shock[1]) >= i+1: shock_class.do_shock(environment, i, shock[2], "start") # the update step # append current step, this is mostly for measurements self.current_step = i # do the actual update self.updater.do_update(environment, i) # write the state of the system measurement.write_to_file() # Do the shock (revert the shock if necessary): # First we check if the shock occurs at the current sweep # Then we run the shock procedure at the end of the update for shock in environment.shocks: if int(shock[0]) <= i+1 and int(shock[1]) >= i+1: shock_class.do_shock(environment, i, shock[2], "end") # HELPER, to be removed in production # for firm in environment.households: # print(firm) # print(environment.households[0]) # print(environment.firms[0]) # capital = 0.0 # for tranx in environment.firms[0].accounts: # if tranx.type_ == "capital" and tranx.from_ == environment.firms[0]: # capital = capital + tranx.amount # if tranx.type_ == "capital" and tranx.to == environment.firms[0]: # capital = capital - tranx.amount # print(environment.firms[0].get_account("deposits")+capital-environment.firms[0].get_account("loans")) # capital = 0.0 # for tranx in environment.firms[1].accounts: # if tranx.type_ == "capital" and tranx.from_ == environment.firms[1]: # capital = capital + tranx.amount # if tranx.type_ == "capital" and tranx.to == environment.firms[1]: # capital = capital - tranx.amount # print(environment.firms[1].get_account("deposits")+capital-environment.firms[1].get_account("loans")) # capital = 0.0 # for tranx in environment.firms[2].accounts: # if tranx.type_ == "capital" and tranx.from_ == environment.firms[2]: # capital = capital + tranx.amount # if tranx.type_ == "capital" and tranx.to == environment.firms[2]: # capital = capital - tranx.amount # print(environment.firms[2].get_account("deposits")+capital-environment.firms[2].get_account("loans")) print(environment.banks[0]) # print(environment.firms[0]) # Close the output file at the end of the simulation measurement.close_file()
def initialize(self, environment): self.identifier = environment.identifier self.updater = Updater(environment) self.num_sweeps = int(environment.static_parameters['num_sweeps']) self.m = int(environment.static_parameters['m'])
class Runner(BaseRunner): # # # VARIABLES # # identifier = "" num_sweeps = 0 # # # METHODS # # # ------------------------------------------------------------------------- # __init__ # ------------------------------------------------------------------------- def __init__(self, environment): self.initialize(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # initialize() # ------------------------------------------------------------------------- def initialize(self, environment): self.identifier = environment.identifier self.updater = Updater(environment) self.num_sweeps = int(environment.static_parameters['num_sweeps']) self.m = int(environment.static_parameters['m']) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_identifier # ------------------------------------------------------------------------- def get_identifier(self): return self.identifier # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_identifier # ------------------------------------------------------------------------- def set_identifier(self, value): return super(Runner, self).set_identifier(value) # ------------------------------------------------------------------------- # get_num_sweeps # ------------------------------------------------------------------------- def get_num_sweeps(self): return self.num_sweeps # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_num_simulations # ------------------------------------------------------------------------- def set_num_sweeps(self, value): super(Runner, self).set_num_sweeps(value) # ------------------------------------------------------------------------- # do_run # ------------------------------------------------------------------------- def do_run(self, environment): # loop over all time steps and do the updating # For each update step measurement = Measurement(environment, self) measurement.open_file() for i in range(self.num_sweeps): self.current_step = i self.updater.do_update(environment, i) measurement.write_to_file() print("***\nThis run had %s sweeps and %s simulations" ) % (self.num_sweeps, environment.static_parameters['num_simulations']) print("Check the output file that was written as csv in the measurements folder\n***") agent = Agent() for each_agent in environment.agents: print(agent.identifier) # agent = Agent() # print(agent.private_belief) # print(agent.calc_social_belief) # print(agent.investment_decision(environment)) # for keys, values in agent.parameters.items(): # print keys, '-->', values # agent = Agent() # print(self.get_identifier()) # print(self.get_num_sweeps()) # print(environment.agents[0]) # parameters={'deposit_rate':-0.02} # agent.append_parameters(parameters) # print(agent.get_parameters()) measurement.close_file()
class Runner(BaseRunner): # # # VARIABLES # # identifier = "" num_sweeps = 0 # # METHODS # # # ------------------------------------------------------------------------- # __init__ # ------------------------------------------------------------------------- def __init__(self, environment): self.initialize(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # initialize() # ------------------------------------------------------------------------- def initialize(self, environment): self.identifier = environment.identifier self.updater = Updater(environment) self.current_step = 0 self.num_sweeps = int(environment.static_parameters['num_sweeps']) #For measurement self.sweep_result_list = [] # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_identifier # ------------------------------------------------------------------------- def get_identifier(self): return self.identifier # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_identifier # ------------------------------------------------------------------------- def set_identifier(self, value): return super(Runner, self).set_identifier(value) # ------------------------------------------------------------------------- # get_num_sweeps # ------------------------------------------------------------------------- def get_num_sweeps(self): return self.num_sweeps # ------------------------------------------------------------------------- def traverse(self, item): try: for i in iter(item): for j in self.traverse(i): yield j except TypeError: yield item # ------------------------------------------------------------------------- # set_num_simulations # ------------------------------------------------------------------------- def set_num_sweeps(self, value): super(Runner, self).set_num_sweeps(value) # ------------------------------------------------------------------------- # do_run # ------------------------------------------------------------------------- def do_run(self, environment): # loop over all time steps and do the updating # For each update step for i in range(self.num_sweeps): self.current_step = i #DEFAULT IS DO RUN! I added leverage experiment #self.updater.do_update(environment, i) self.updater.do_update_leverage(environment, i, environment.static_parameters['leverage_increase']) self.sweep_result_list.append(self.updater.env_var_par_df) self.updater.write_sweep_list_of_results_to_csv(environment, self.current_step) print("Check the simulation specific output file that was written as csv in the output folder\n***")
class Runner(BaseRunner): # # # VARIABLES # # identifier = "" num_simulations = 0 # # # METHODS # # # ------------------------------------------------------------------------- # __init__ # ------------------------------------------------------------------------- def __init__(self, environment): self.initialize(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_identifier # ------------------------------------------------------------------------- def get_identifier(self): return self.identifier # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_identifier # ------------------------------------------------------------------------- def set_identifier(self, _value): super(Runner, self).set_identifier(_value) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_num_simulations # ------------------------------------------------------------------------- def get_num_simulations(self): return self.num_simulations # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_num_simulations # ------------------------------------------------------------------------- def set_num_simulations(self, _value): super(Runner, self).set_num_simulaitons(_value) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # initialize() # ------------------------------------------------------------------------- def initialize(self, environment): self.identifier = environment.identifier self.num_sweeps = int(environment.num_sweeps) self.updater = Updater(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # do_run # ------------------------------------------------------------------------- def do_run(self, environment): # loop over all time steps and do the updating for i in range(self.num_sweeps): # the update step self.updater.do_update(environment, i) # TESTING IN SIMPLE EXAMPLES # REMOVE FOR PRODUCTION # OR MOVE TO LOGGING print(environment.firms[0]) print(environment.households[0])
def initialize(self, environment): self.environment = environment self.updater = Updater(self.environment) self.shocker = Shock()
class Runner(BaseRunner): # # # VARIABLES # # identifier = "" num_simulations = 0 # # # METHODS # # # ------------------------------------------------------------------------- # __init__ # ------------------------------------------------------------------------- def __init__(self, environment): self.initialize(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_identifier # ------------------------------------------------------------------------- def get_identifier(self): return self.identifier # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_identifier # ------------------------------------------------------------------------- def set_identifier(self, _value): super(Runner, self).set_identifier(_value) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_num_simulations # ------------------------------------------------------------------------- def get_num_simulations(self): return self.num_simulations # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_num_simulations # ------------------------------------------------------------------------- def set_num_simulations(self, _value): super(Runner, self).set_num_simulaitons(_value) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # initialize() # ------------------------------------------------------------------------- def initialize(self, environment): self.identifier = environment.identifier self.num_sweeps = int(environment.num_sweeps) self.updater = Updater(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # do_run # ------------------------------------------------------------------------- def do_run(self, environment): # loop over all time steps and do the updating for i in range(self.num_sweeps): # the update step self.updater.do_update(environment, i) print("Sweep number %s" % str(i+1)) for bank in environment.banks: print(bank) print("Bank objects:") print(environment.banks) print("Firm objects:") print(environment.firms) print("Household objects:") print(environment.households)
class Runner(BaseRunner): # # # VARIABLES # # identifier = "" num_sweeps = 0 # # # METHODS # # # ------------------------------------------------------------------------- # __init__ # ------------------------------------------------------------------------- def __init__(self, environment): self.initialize(environment) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # initialize() # ------------------------------------------------------------------------- def initialize(self, environment): self.identifier = environment.identifier self.updater = Updater(environment) self.num_sweeps = int(environment.static_parameters['num_sweeps']) # self.m = int(environment.static_parameters['m']) # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # get_identifier # ------------------------------------------------------------------------- def get_identifier(self): return self.identifier # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_identifier # ------------------------------------------------------------------------- def set_identifier(self, value): return super(Runner, self).set_identifier(value) # ------------------------------------------------------------------------- # get_num_sweeps # ------------------------------------------------------------------------- def get_num_sweeps(self): return self.num_sweeps # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # set_num_simulations # ------------------------------------------------------------------------- def set_num_sweeps(self, value): super(Runner, self).set_num_sweeps(value) # ------------------------------------------------------------------------- # do_run # ------------------------------------------------------------------------- def do_run(self, environment): # loop over all time steps and do the updating # For each update step measurement = Measurement(environment, self) measurement.open_file() for i in range(self.num_sweeps): self.current_step = i self.updater.do_update(environment, i) measurement.write_to_file() print("***\nThis run had %s sweeps and %s simulations" ) % (self.num_sweeps, environment.static_parameters['num_simulations']) print("Check the output file that was written as csv in the measurements folder\n***") measurement.close_file()
with open('./gitignored/info.txt', 'r') as file: token = file.readline().strip('\n') host = file.readline().strip('\n') username = file.readline().strip('\n') password = file.readline().strip('\n') loop = asyncio.get_event_loop() lock = asyncio.Lock() bot = Bot( command_prefix='!', description='A bot that sends messages to individual people and channels' ' about news.') db_context = DbContext(host, username, password) notifier = Notifier(bot) updater = Updater() feed_reader = FeedReader() @bot.event async def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') loop.create_task(updater.loop(loop, bot, feed_reader, notifier, db_context)) @bot.command(name='sub', pass_context=True) async def subscribe(ctx):
class Runner(BaseRunner): # from environment import Environment # # VARIABLES # identifier = "" num_simulations = 0 # # METHODS # # ------------------------------------------------------------------------- # __init__ # ------------------------------------------------------------------------- def __init__(self): pass # ------------------------------------------------------------------------- def get_identifier(self): return self.identifier def set_identifier(self, _value): """ Class variables: identifier Local variables: _identifier """ super(Runner, self).set_identifier(_value) def get_num_simulations(self): return self.num_simulations def set_num_simulations(self, _value): """ Class variables: num_simulations Local variables: _num_simulations """ super(Runner, self).set_num_simulaitons(_value) # ------------------------------------------------------------------------- # initialize() # ------------------------------------------------------------------------- def initialize(self, environment): self.identifier = environment.identifier self.num_simulations = environment.static_parameters["numSweeps"] self.environment = environment self.updater = Updater(self.environment) self.shocker = Shock() # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # do_run # ------------------------------------------------------------------------- def do_run(self, measurement, debug): # loop over all time steps and do the updating for i in range(self.num_simulations): # the update step self.updater.do_update(self.environment, i, debug) # check if there is a shock at the current time step if (int(self.environment.get_state(i).static_parameters["shockType"]) != 0): self.shocker.do_shock(self.environment, int(i)) self.environment.get_state(i).static_parameters["shockType"] = 0 # do the measurement measurement.do_measurement(self.environment.banks)
def initialize(self, environment): self.identifier = environment.identifier self.num_simulations = environment.static_parameters["numSweeps"] self.environment = environment self.updater = Updater(self.environment) self.shocker = Shock()
class WebServer(object): def __init__(self): self.server = None log_folder = program.get_base_dir('logs') if not os.path.exists(log_folder): os.mkdir(log_folder) log_file = os.path.join(log_folder, 'cot_plot.log') LOG_CONF['handlers']['logfile']['filename'] = log_file logging.config.dictConfig(LOG_CONF) self.logger = logging.getLogger(__name__) self.logger.debug( "==============================================================") self.logger.debug("CoT Plot web werver started") self.pyramid_settings = { 'reload_all': False, 'debug_all': True, 'pyramid.debug_all': True, 'pyramid.debug_routematch': True, 'pyramid.reload_all': False, 'cotplot.secret': '$nif2-EERG1$£03mf£AF$&^-' } self.config = Configurator(settings=self.pyramid_settings, root_factory='src.cot_plot.resources.Root') self.settings = settings.Settings() self.updater = Updater() def startup(self): status = False try: self.logger.info("initialise pyramid...") self.config.include('pyramid_mako') #config.include('pyramid_debugtoolbar') # Security policies authn_policy = AuthTktAuthenticationPolicy( self.pyramid_settings['cotplot.secret'], callback=groupfinder, cookie_name="cotplot-authtkt", secure=False, http_only=True, include_ip=True, path='cot_plot', hashalg='sha512') authz_policy = ACLAuthorizationPolicy() self.config.set_authentication_policy(authn_policy) self.config.set_authorization_policy(authz_policy) self.config.add_forbidden_view(forbidden) self.logger.info("load settings from file...") self.settings.load(program.get_base_dir('settings.json')) port = self.settings.get_web_port() static_path = program.get_bin_dir('cot_plot/static') self.logger.info("static path: %s", static_path) self.config.add_static_view(name='/cot_plot/static', path=static_path, cache_max_age=3600) template_path = program.get_bin_dir('cot_plot//templates') program.set_template_path(template_path) # The default home self.config.add_route('home', '/') self.config.include(include_routes, route_prefix='/') # When this app is frozen config.scan() does not work, so we manually include the views here self.logger.info("include views...") #self.config.scan('web.views') src.cot_plot.views.commodity.include_views(self.config) src.cot_plot.views.financial.include_views(self.config) self.logger.info("setup wsgi...") app = self.config.make_wsgi_app() print("Web serving: http://localhost:%s/cot_plot" % port) self.logger.info("Web serving: http://localhost:%s/cot_plot", port) # Mount the application (or *app*) cherrypy.tree.graft(app, "/cot_plot") # Unsubscribe the default server cherrypy.server.unsubscribe() cherrypy.config.update({ 'environment': 'production', 'log.error_file': 'cp_error.log', }) # Instantiate a new server object self.server = cherrypy._cpserver.Server() # Configure the server object self.server.socket_host = "127.0.0.1" self.server.socket_port = int(port) self.server.thread_pool = 3 #self.server.ssl_certificate = src.common.program.get_base_dir('cert.pem') #self.server.ssl_private_key = src.common.program.get_base_dir('key.pem') #self.server.ssl_module = 'builtin' # Subscribe this server self.server.subscribe() # Start the server engine (Option 1 *and* 2) cherrypy.engine.start() status = True except Exception as e: self.logger.error("Exception starting web service!") self.logger.exception(e) return status def run(self): self.logger.info('Start updater') self.updater.initialise() self.logger.info("Server Running") try: cherrypy.engine.block() except Exception as e: self.logger.exception(e) self.logger.info("Server exit") def shutdown(self): try: self.logger.info("Exit cherrypy engine") cherrypy.engine.exit() self.logger.info("Exit updater") self.updater.shutdown() self.logger.info("Shutdown complete") except Exception as e: self.logger.exception(e)