Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Testing custom agents and bootstrapping #6

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 6 additions & 24 deletions Agent_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,42 +12,24 @@
from dask.distributed import Client
import Personality_permutations as Pp

class Create_agents():
class Create_random_agent():

def __init__(self, number):
self.initial_number = 1
self.initial_agents = []

personality = Pp.Create_personas()
personality_mix = personality.Get_personas()

general_atributes_A = { 'uuid': uuid.uuid4(),
general_attributes_A = { 'uuid': uuid.uuid4(),
'type': 'A',
'name': number,
'token_wallet': {"reputation": 0},
'activity': 0,
'own_PATs': 0}
general_attributes_A.update(personality_mix)
self.agent = general_attributes_A

general_atributes_A.update(personality_mix)

#general_atributes_B = {'uuid': uuid.uuid4(),
# 'type': 'B',
# 'money': 20,
# 'own_PATs': 0,
# 'token_wallet': {"reputation": 0}}

#general_atributes_B.update(personality_mix)

permutation = [general_atributes_A]

for atribute in permutation:
for i in range(self.initial_number):
agent = atribute
self.initial_agents.append(agent)


def Get_initial_agents(self):
return self.initial_agents
def get_random_agent(self):
return self.agent

class Create_custom_agents():

Expand Down
63 changes: 15 additions & 48 deletions Fin4_ABM.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ def create_agents_with_attributes(last_nr, set, claim_intent, claim_compliance,
creation = Af.Create_custom_agents(i, claim_intent, claim_compliance, voter_drive, creator_intent, creator_design)
individual_agent = creation.getCustomAgent()
initial_agents.append(individual_agent)
return initial_agents

def claim(agent, PAT_list, policy, s):
gains = {}
Expand Down Expand Up @@ -81,25 +80,20 @@ def add_activity_to_coresponding_PAT(pat_id, s):
initial_PAT_ag = []

# Human agents

last_id = 0
if config['human agents']['agents_with_random_attributes'] == 'True':
#print("------------RANDOM agent attributes --------------- ")
for i in range(0, int(config['human agents']['number'])):
creation = Af.Create_agents(i)
individual_agent = creation.Get_initial_agents()
initial_agents_prep.append(individual_agent)

initial_agents = sum([ag for ag in initial_agents_prep], [])

creation = Af.Create_random_agent(i)
individual_agent = creation.get_random_agent()
initial_agents.append(individual_agent)
last_id = i + 1


if config['human agents']['custom_agents'] == 'True':
#print("------------CUSTOM agent attributes --------------- ")


number_of_sets = int(config['human agents']['number_of_custom_agent_sets'])
last_id = 0

for s in range(1, number_of_sets + 1):

#name of variables to be read frpm the init file: extract this into a separate method
Expand Down Expand Up @@ -129,7 +123,7 @@ def add_activity_to_coresponding_PAT(pat_id, s):

creation_frequency = int(config['PAT agents']['frequency_PAT_creation']) # in time-steps

if config['PAT agents']['initial_PAT_agents'] == 'True':
if config['PAT agents']['human_agent_PAT_creation'] == 'True':
PAT_agents = Af.Initial_PAT_agents(int(config['PAT agents']['number_initial_pats']))
initial_PAT_ag = PAT_agents.Get_initial_PAT_agents()

Expand Down Expand Up @@ -162,7 +156,6 @@ def add_activity_to_coresponding_PAT(pat_id, s):


"""### Initial conditions and parameters"""

initial_conditions = {
'agents': initial_agents,
'PATs': initial_PAT_ag,
Expand Down Expand Up @@ -220,7 +213,7 @@ def random_claim_of_tokens(params, step, sL, s):
claim(ch, pats, 'no_activity', s)
to_update.append(ch)

return {'update_agents': {'update': to_update}}
return {'updated_agents': {'update': to_update}}

def create_pat(params, step, sL, s):
agents = s['agents']
Expand All @@ -231,16 +224,7 @@ def create_pat(params, step, sL, s):

if s['timestep'] > 0 and s['timestep'] % creation_frequency == 0:
creator_name = random.randrange(len(agents))
#print ("creator_name: ", creator_name)
for ag in agents:
try:
if ag['name'] == creator_name:
creator = ag
except:
if ag[0]['name'] == creator_name:
creator = ag[0]

#print("creator: ", creator)
creator = next(ag for ag in agents if ag['name'] == creator_name)
intention = creator['creator_intention']
creator_ID = creator['name']
design = creator['creator_design']
Expand Down Expand Up @@ -290,31 +274,14 @@ def update_PATs(params, step, sL, s, _input):
def update_agents(params, step, sL, s, _input):
y = 'agents'
x = copy.copy(s['agents'])

data = _input.get("update_agents", {})
removed_agents = data.get("remove", [])
removed_uuids = [agent['uuid'] for agent in removed_agents]
data = _input.get("updated_agents", {})
updated_agents = data.get("update", [])

updated_uuids = [agent["uuid"] for agent in updated_agents]
added_agents = data.get("add", [])

for agent in x:
try:
uuid = agent["uuid"]
except:
uuid = agent[0]["uuid"]

if uuid in removed_uuids:
x.remove(agent)
if uuid in updated_uuids:
updated_agent = [agent for agent in updated_agents if agent["uuid"] == uuid]
x.remove(agent)
x.append(updated_agent)

for agent in added_agents:
x.append(agent)

for newag in updated_agents:
x.remove(
next((ag for ag in x if newag["uuid"]==ag["uuid"]),
None))
x.append(newag)
#print([type(l) for l in x])
return (y, x)


Expand Down
91 changes: 61 additions & 30 deletions Fin4_ABM_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,7 @@

class MyTestCase(unittest.TestCase):

def reconstruct_agent_database(self, data):
reconstruction = []
for i in range(0, len(data)):
if isinstance(data[i], dict):
reconstruction.append(data[i])
if isinstance(data[i], list):
reconstruction.append(data[i][0])
return reconstruction
#---------------------- Helper functions---------------------------

def number_of_tokens_per_person(self, agent):
distribution = 0
Expand All @@ -27,43 +20,81 @@ def number_of_tokens_per_person(self, agent):
pass
return distribution

def calculate_total_agents_from_config_file(self):
nr_agen_sets = int(config['human agents']['number_of_custom_agent_sets'])
total_agents = 0
if config['human agents']['custom_agents'] == "True":
for set in range(1, nr_agen_sets + 1):
set_name = "set" + str(set) +"_number_of_agents"
total_agents += int(config['human agents'][set_name])
if config['human agents']['agents_with_random_attributes'] == "True":
total_agents += int(config['human agents']['number'])
return total_agents

def info_PATs_from_config_file(self):
nr_agen_sets = int(config['PAT agents']['number_of_custom_PAT_sets'])
total_agents = 0
purpose = []
design = []
for set in range(1, nr_agen_sets + 1):
set_name = "set" + str(set) + "_number_of_PATs"
purpose_name = "set" + str(set) + "_token_purpose"
design_name = "set" + str(set) + "_token_design"
agents_per_set = int(config['PAT agents'][set_name])
for i in range(0, agents_per_set):
purpose.append(config['PAT agents'][purpose_name])
design.append(config['PAT agents'][design_name])
total_agents += agents_per_set
return total_agents, purpose, design

#------------------------ Unittests -------------------------------

def test_number_of_agents_created(self):
print("Running test: number of agents created")
rec_data = self.reconstruct_agent_database(model.raw_result[-1]['agents'])
self.assertEqual(len(rec_data), int(config['human agents']['number']))
self.assertEqual(
len(model.raw_result[-1]['agents']),
self.calculate_total_agents_from_config_file()
)

def test_PAT_creator_creation(self):
print("Running test: PAT creator - creation")
initial_PAT_number = int(config['PAT agents']['number_initial_pats'])
nr_new_PATs = len(model.raw_result[-1]["PATs"]) - initial_PAT_number
print("nr new PATs", nr_new_PATs)
for i in range(0, nr_new_PATs):
creator_ID = model.raw_result[-1]["PATs"][initial_PAT_number + i]['creator_ID']
PAT_purpose = model.raw_result[-1]["PATs"][initial_PAT_number + i]['purpose']
PAT_design = model.raw_result[-1]["PATs"][initial_PAT_number + i]['design']
for ag in model.raw_result[-1]['agents']:
try:
if ag['name']==creator_ID:
self.assertEqual(ag['creator_intention'], PAT_purpose)
self.assertEqual(ag['creator_design'], PAT_design)
except:
if ag[0]['name'] == creator_ID:
self.assertEqual(ag[0]['creator_intention'], PAT_purpose)
self.assertEqual(ag[0]['creator_design'], PAT_design)
if config["PAT agents"]["human_agent_PAT_creation"] == "True":
initial_PAT_number = int(config['PAT agents']['number_initial_pats'])
nr_new_PATs = len(model.raw_result[-1]["PATs"]) - initial_PAT_number
#print("nr new PATs", nr_new_PATs)
for i in range(0, nr_new_PATs):
creator_ID = model.raw_result[-1]["PATs"][initial_PAT_number + i]['creator_ID']
PAT_purpose = model.raw_result[-1]["PATs"][initial_PAT_number + i]['purpose']
PAT_design = model.raw_result[-1]["PATs"][initial_PAT_number + i]['design']
for ag in model.raw_result[-1]['agents']:
try:
if ag['name']==creator_ID:
self.assertEqual(ag['creator_intention'], PAT_purpose)
self.assertEqual(ag['creator_design'], PAT_design)
except:
if ag[0]['name'] == creator_ID:
self.assertEqual(ag[0]['creator_intention'], PAT_purpose)
self.assertEqual(ag[0]['creator_design'], PAT_design)

if config["PAT agents"]["custom_bootstrapping"] == "True":
total_PATs_config, purpose_config, design_config = self.info_PATs_from_config_file()
self.assertEqual(len(model.raw_result[-1]["PATs"]), total_PATs_config)
for i in range(0, total_PATs_config):
self.assertEqual(model.raw_result[-1]["PATs"][i]['purpose'], purpose_config[i])
self.assertEqual(model.raw_result[-1]["PATs"][i]['design'], design_config[i])

def test_AT_ratio(self):
print ("Running test: AT ratio")
rec_data = self.reconstruct_agent_database(model.raw_result[-1]['agents'])
for agent in rec_data:
for agent in model.raw_result[-1]['agents']:
nr_tokens = self.number_of_tokens_per_person(agent)
activity = agent['activity']
if nr_tokens:
if agent['claimer'] == "follower":
self.assertEqual(activity/nr_tokens, 1)
if agent['claimer'] == "opportunistic":
self.assertLessEqual(activity / nr_tokens, 1)
self.assertLessEqual(activity/nr_tokens, 1)
if agent['claimer'] == "cheater":
self.assertEqual(activity / nr_tokens, 0)
self.assertEqual(activity/nr_tokens, 0)
else:
self.assertEqual(activity, 0)

Expand Down
7 changes: 4 additions & 3 deletions config.ini
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ number_of_custom_agent_sets = 3
; the above number has to match the sets defined below:

; set 1
set1_number_of_agents = 1
set1_number_of_agents = 5
set1_claim_intent = noble
set1_claim_compliance = opportunistic
set1_voter_drive = assessment
Expand All @@ -41,12 +41,13 @@ set3_creator_design = careless

[PAT agents]
#---------------------------------------OPTION 1 ---------------------------
initial_PAT_agents = False
human_agent_PAT_creation = True
;always noble and carefully designed
number_initial_pats = 2
;in times steps
frequency_PAT_creation = 3
#---------------------------------------OPTION 2 ---------------------------
custom_bootstrapping = True
custom_bootstrapping = False
number_of_custom_PAT_sets = 2
; the above number has to match the sets defined below:

Expand Down