Skip to content

Commit

Permalink
success rate measure added to resilience metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
aadeshnpn committed Mar 28, 2022
1 parent 1e38017 commit 2c6bdbc
Show file tree
Hide file tree
Showing 8 changed files with 109 additions and 70 deletions.
1 change: 1 addition & 0 deletions examples/coevolution/experiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ def single_evo(args):
parser.add_argument('--stoplen', default=0, type=int)
parser.add_argument('--iprob', default=0.85, type=float)
parser.add_argument('--stop_interval', default=1000, type=int)
parser.add_argument('--no_debris', default=10, type=int)
args = parser.parse_args()
args.stoplen = args.time + args.stop_interval
print(args)
Expand Down
41 changes: 21 additions & 20 deletions examples/coevolution/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def __init__(
str(N), str(iter), str(threshold), str(gstep), str(expp),
str(args.addobject), str(args.removeobject),
str(args.no_objects), str(args.radius),
str(args.time), str(args.iprob),
str(args.time), str(args.iprob), str(args.no_debris),
str(self.runid) + name
)
Path(self.pname).mkdir(parents=True, exist_ok=True)
Expand Down Expand Up @@ -156,20 +156,20 @@ def build_environment_from_json(self):
self.site = self.render.objects['sites'][0]
self.sites = []
self.sites += [self.site]
for i in range(self.num_agents * 1):
# Add food to the site
f = Food(
i, location=self.site.location, radius=self.site.radius)
f.agent_name = None
self.grid.add_object_to_grid(f.location, f)
self.total_food_units += f.weight
f.phenotype = dict()
self.foods.append(f)

for j in range(self.num_agents//4):
# for i in range(self.num_agents //99):
# # Add food to the site
# f = Food(
# i, location=self.site.location, radius=self.site.radius)
# f.agent_name = None
# self.grid.add_object_to_grid(f.location, f)
# self.total_food_units += f.weight
# f.phenotype = dict()
# self.foods.append(f)

for j in range(self.args.no_debris):
# Add debris around the hub
d = Debris(
j, location=self.hub.location, radius=10, weight=2)
j, location=self.hub.location, radius=10, weight=5)
d.agent_name = None
self.grid.add_object_to_grid(d.location, d)
self.total_debris_units += d.weight
Expand Down Expand Up @@ -291,13 +291,14 @@ def foraging_percent(self):
# _, food_grid = grid.find_grid(food.location)
# if food_grid == hub_grid:
# food_objects += [food]
food_objects = list(set(self.hub.dropped_objects))
food_objects = [
food for food in food_objects if type(food).__name__ == 'Food']
# food_objects = set(food_objects)
total_food_weights = sum([food.weight for food in food_objects])
return np.round(
((total_food_weights * 1.0) / self.total_food_units) * 100, 2)
# food_objects = list(set(self.hub.dropped_objects))
# food_objects = [
# food for food in food_objects if type(food).__name__ == 'Food']
# # food_objects = set(food_objects)
# total_food_weights = sum([food.weight for food in food_objects])
# return np.round(
# ((total_food_weights * 1.0) / self.total_food_units) * 100, 2)
return 0

def maintenance_percent(self):
"""Find amount of debris cleaned."""
Expand Down
10 changes: 7 additions & 3 deletions examples/coevolution/resilience_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,12 +270,13 @@ def addition_efficiency_power(fname="EvoCoevolutionPPA"):
timings = range(1000, 11001, 1000)
allpower = {}
allefficiency = {}
hitrate = []
for t in timings:
data = np.squeeze(read_data_n_agent_perturbations_all(
n=100, iter=12000, threshold=7, time=t, iprob=0.85,
addobject='Obstacles', no_objects=2,
radius=10, idx=[2], fname=fname))

# print(data.shape)
powerdata100 = data[:, -1]
allpower[t] = powerdata100

Expand All @@ -284,10 +285,11 @@ def addition_efficiency_power(fname="EvoCoevolutionPPA"):
effdata = [np.array(
[effdata[i][0] if effdata[i].shape[
0] > 1 else 12000 for i in range(len(effdata))])]
hitrate.append(np.sum(effdata[0]!=12000)/effdata[0].shape[0])
effdata = [(
((12000-effdata[i])/12000)*100) for i in range(len(effdata))]
allefficiency[t] = np.round(effdata[0], 2)

print('Success Rate', np.round(np.median(np.array(hitrate)), 2))
X = np.concatenate(
np.array([[i] * len(v[1]) for (i, v) in enumerate(allpower.items())]))
Y = np.concatenate(np.array([v for _, v in allpower.items()]))
Expand Down Expand Up @@ -497,8 +499,10 @@ def main():
# distortion_efficiency_power(fname="EvoNestMNewPPA1")
# shift_efficiency_power(fname="EvoNestMNewPPA1")
# shift_efficiency_power()
plot_power_efficiency_subplots()
# plot_power_efficiency_subplots()
# addition_efficiency_power(fname="EvoNestMNewPPA1")
addition_efficiency_power(fname="EvoCoevolutionPPA")
# addition_efficiency_power(fname="EvoCoevolutionPPAAd")


if __name__ == "__main__":
Expand Down
8 changes: 4 additions & 4 deletions examples/coevolution/world.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@

"sites": [
{
"x":30,
"y":30,
"x":-30,
"y":-30,
"radius":10,
"q_value":0.9
}
],
"boundary": [
{
"x":-30,
"y":-30,
"x":30,
"y":30,
"radius":10
},
{
Expand Down
3 changes: 2 additions & 1 deletion examples/modularity/computemetrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,8 @@ def compute_DEP(equivalance, succesor):

def main():
gnames = [
'/tmp/coevo.bnf', '/tmp/bt.bnf', '/tmp/swarm.bnf']
'/tmp/coevo.bnf', '/tmp/bt.bnf', '/tmp/swarm.bnf',
'/tmp/coevoAddition.bnf']
for gname in gnames:
size_metrics(gname)
structure_metrics(gname)
Expand Down
4 changes: 2 additions & 2 deletions grammars/coevo.bnf
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
<constraintt> ::=CanMove|IsCarryable_<dobjects>|IsDropable_<sobjects>

<action> ::= MoveTowards_<sobjects>_Normal|Explore_0_Normal|MoveAway_<sobjects>_Normal|CompositeSingleCarry_<dobjects>|CompositeDrop_<dobjects>
<sobjects>::=Boundary|Hub|Sites
<dobjects>::=Debris|Food
<sobjects>::=Boundary|Hub
<dobjects>::=Debris
<objects>::=<sobjects>|<dobjects>
<SuccessNode> ::= [PostCnd]DummyNode[/PostCnd]
97 changes: 61 additions & 36 deletions swarms/behaviors/sbehaviors.py
Original file line number Diff line number Diff line change
Expand Up @@ -814,50 +814,75 @@ def initialise(self):

def update(self):
"""Logic to drop the item."""
try:
# Get the objects from the actuators
objects = list(filter(
lambda x: type(x).__name__ == self.item,
self.agent.attached_objects))[0]
# Grid
grid = self.agent.model.grid
static_grids = grid.get_neighborhood(self.agent.location, 1)
envobjects = self.agent.model.grid.get_objects_from_list_of_grid(
None, static_grids)

envobjects = [
e for e in envobjects if type(e).__name__.find('Agent')== -1]

unique_envobjs_name = set(
[type(
envobj).__name__ for envobj in envobjects])
dropped = False
# print('drop mod', objects, unique_envobjs_name, envobjects)
# try:
# Get the objects from the actuators
objects = list(filter(
lambda x: type(x).__name__ == self.item,
self.agent.attached_objects))[0]
# Grid
grid = self.agent.model.grid
static_grids = grid.get_neighborhood(self.agent.location, 1)
envobjects = self.agent.model.grid.get_objects_from_list_of_grid(
None, static_grids)

envobjects = [
e for e in envobjects if type(e).__name__.find('Agent')== -1]

unique_envobjs_name = set(
[type(
envobj).__name__ for envobj in envobjects])
# dropped = False
# print('drop mod', objects, unique_envobjs_name, envobjects)

## If attached object food, can't drop on boundary or obstacles
## If attached object debri, can't drop on hub
def drop(sobject, aobject):
sobject.dropped_objects.append(aobject)
self.agent.attached_objects.remove(aobject)
sobject.agent_name = self.agent.name
return True

if type(objects).__name__ == 'Food':
if (
('Hub' in unique_envobjs_name) and (
('Boundary' in unique_envobjs_name) or (
'Obstacles' in unique_envobjs_name)):
return common.Status.FAILURE
elif (
('Hub' in unique_envobjs_name) and (
'Debris' in unique_envobjs_name)):
return common.Status.FAILURE
elif (
('Hub' in unique_envobjs_name) and (
'Debris' not in unique_envobjs_name)):
for envobj in envobjects:
if type(envobj).__name__ == 'Hub':
drop(envobj, objects)
return common.Status.SUCCESS
else:
for obj in envobjects:
if (
type(obj).__name__ in ['Hub'] and (
'Debris' not in unique_envobjs_name)) or (
type(obj).__name__ in [
'Boundary', 'Obstacles']):
dropped = True
obj.dropped_objects.append(objects)
self.agent.attached_objects.remove(objects)
objects.agent_name = self.agent.name
break

if not dropped:
self.agent.model.grid.add_object_to_grid(
objects.location, objects)
self.agent.attached_objects.remove(objects)
objects.agent_name = self.agent.name
return common.Status.SUCCESS
except (AttributeError, IndexError):
return common.Status.FAILURE
return common.Status.SUCCESS
else:
if (
('Hub' in unique_envobjs_name) or (
'Obstacles' in unique_envobjs_name)):
return common.Status.FAILURE
elif (
('Boundary' in unique_envobjs_name)):
for envobj in envobjects:
if type(envobj).__name__ == 'Boundary':
drop(envobj, objects)
return common.Status.SUCCESS
else:
self.agent.model.grid.add_object_to_grid(
objects.location, objects)
self.agent.attached_objects.remove(objects)
objects.agent_name = self.agent.name
return common.Status.SUCCESS
# except (AttributeError, IndexError):
# return common.Status.FAILURE


class DropPartial(Behaviour):
Expand Down
15 changes: 11 additions & 4 deletions test/test_swarm_drop_modified.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def __init__(self, N, width, height, grid=10, seed=None):
self.food = Food()
self.grid.add_object_to_grid(self.food.location, self.food)

self.debris = Debris()
self.debris = Debris(location=(40, 40), radius=10, weight=5)
self.grid.add_object_to_grid(self.debris.location, self.debris)

self.boundary = Boundary(location=(30, 30), radius=10)
Expand All @@ -72,17 +72,23 @@ def __init__(self, N, width, height, grid=10, seed=None):
for i in range(1):
a = SwarmAgentDrop(i, self)
self.schedule.add(a)
x = 30
y = 30
x = 0
y = 0
a.location = (x, y)
a.direction = -2.3561944901923448
self.grid.add_object_to_grid((x, y), a)
self.agent = a

self.agent.attached_objects.append(self.food)
self.agent.model.grid.remove_object_from_grid(
self.food.location, self.food)
self.food.agent_name = self.agent.name

# self.agent.attached_objects.append(self.debris)
# self.agent.model.grid.remove_object_from_grid(
# self.debris.location, self.debris)
# self.debris.agent_name = self.agent.name

def step(self):
self.schedule.step()

Expand All @@ -93,7 +99,8 @@ def setUp(self):
self.environment = DropSwarmEnvironmentModel(1, 100, 100, 10, 123)

for i in range(2):
print(self.environment.agent.location)
print(
self.environment.agent.location, self.environment.agent.attached_objects)
self.environment.step()

def test_agent_path(self):
Expand Down

0 comments on commit 2c6bdbc

Please sign in to comment.