Gopal Sarda
Gopal Sarda

Reputation: 31

Netlogo : Optimize calculation of turtle neighbor within a patch

I need to calculate nearest neighbor turtle in the same patch for all the turtles constrained by some properties. The code which I have written takes a lot of time and am wondering if there is any other way to optimize it. I have defined a property neighbor in turtle to store the nearest neighbor.

to set_neighbor  
  ask patches [
    ask turtles-here with [ life_stage = "STAGE1" ] [
      set neighbor min-one-of other turtles-here with [ life_stage != "STAGE2" ] [ (distance myself) ]
    ]
  ]  
end

I tried to optimize the code by making the following changes but it ended up taking more time. I assumed if I stored the results of a query in a variable and used the variable later multiple times it would be quicker than executing the query itself multiple times.

to set_neighbor  
  ask patches [
    let turt_temp turtles-here with [ life_stage != "STAGE2" ]
    ask turtles-here with [ life_stage = "STAGE1" ] [
      set neighbor min-one-of other turt_temp [ (distance myself) ]
    ]
  ]  
end

I would really appreciate any pointers for this. Thanks in advance.

Upvotes: 2

Views: 135

Answers (2)

JenB
JenB

Reputation: 17678

Another option (and I can't tell which would be faster) is to restrict the number of asks by only doing it where there are both stage1 and not(stage2) turtles on the same patch. I have also used with-min instead of min-one-of but again I don't know which is quicker.

to set_neighbor
  ask patches with [ any? turtles with [ life_stage = "STAGE1" ] and any? turtles with [ life_stage != "STAGE2" ] ]
  [ ask turtles-here with [ life_stage = "STAGE1" ]
    [ set neighbor other turtles-here with [ life_stage != "STAGE2" ] with-min [ distance myself ]
    ]
  ]
end

Upvotes: 0

Bryan Head
Bryan Head

Reputation: 12580

Why have the patches ask the turtles at all? This should do exactly the same thing, but a good bit faster, especially if you have a lot of patches with no turtles at STAGE1:

to set_neighbor  
  ask turtles with [ life_stage = "STAGE1" ] [
    set neighbor min-one-of other turtles-here with [ life_stage != "STAGE2" ] [ (distance myself) ]
  ]
end

I'm not sure just looking why your second implementation was slower. I could see it being slower if you have a lot of patches without any turtles at STAGE1 (especially if there a lot of other turtles on them).

Upvotes: 2

Related Questions