Skip to content

Commit

Permalink
Faster resorvoir_sampling_single function (#788)
Browse files Browse the repository at this point in the history
* Faster resorvoir_sampling_single function

* Update space_interaction_API.jl

* Update CHANGELOG.md

* Update Project.toml
  • Loading branch information
Tortar authored Mar 30, 2023
1 parent 9d4c958 commit ac73524
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 14 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# main

# v5.13

- `random_nearby_position`, `random_nearby_ids` and `random_nearby_agent` are up to 2 times faster thanks to a faster sampling function.

# v5.12

- The `random_nearby_position` function is now much faster for GridSpaces.
Expand Down
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "Agents"
uuid = "46ada45e-f475-11e8-01d0-f70cc89e6671"
authors = ["George Datseris", "Tim DuBois", "Aayush Sabharwal", "Ali Vahdati"]
version = "5.12.0"
version = "5.13.0"

[deps]
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
Expand Down
22 changes: 9 additions & 13 deletions src/core/space_interaction_API.jl
Original file line number Diff line number Diff line change
Expand Up @@ -367,23 +367,19 @@ end
function resorvoir_sampling_single(iter, model)
res = iterate(iter)
isnothing(res) && return nothing # `iterate` returns `nothing` when it ends

rng = abmrng(model)
choice, state = res # random position to return, and the state of the iterator
w = max(rand(rng), eps()) # rand returns in range [0,1)

skip_counter = 0 # skip entries in the iterator
while !isnothing(state) && !isnothing(iter)
if skip_counter == 0
choice, state = res
skip_counter = floor(log(rand(rng)) / log(1 - w))
w *= max(rand(rng), eps())
else
_, state = res
while true
choice, state = res # random position to return, and the state of the iterator
skip_counter = floor(log(rand(rng)) / log(1 - w)) # skip entries in the iterator
while skip_counter != 0
skip_res = iterate(iter, state)
isnothing(skip_res) && return choice
state = skip_res[2]
skip_counter -= 1
end
res = iterate(iter, state)
isnothing(res) && break
isnothing(res) && return choice
w *= max(rand(rng), eps())
end
return choice
end

0 comments on commit ac73524

Please sign in to comment.