Skip to content

Commit

Permalink
Improve performance of sample! function (#765)
Browse files Browse the repository at this point in the history
* Improve performance of sample! function

* use model[id]

Co-authored-by: George Datseris <datseris.george@gmail.com>

* comment about counter

* Update CHANGELOG.md

---------

Co-authored-by: George Datseris <datseris.george@gmail.com>
  • Loading branch information
Tortar and Datseris authored Mar 8, 2023
1 parent 788e1f7 commit a67924b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# main
- `sample!` is now much faster than before when the size of the sample is big, with a size of 1 million agents the function is now 1000x faster.
- A memory bug about offsets calculation has been solved; besides, the `calculate_offsets` function has been sped-up by a significant amount.

# v5.8
Expand Down
17 changes: 10 additions & 7 deletions src/simulations/sample.jl
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ function sample!(
weight = nothing;
replace = true,
)
nagents(model) > 0 || return
nagents(model) == 0 && return nothing
org_ids = collect(allids(model))
if weight !== nothing
weights = Weights([get_data(a, weight, identity) for a in values(model.agents)])
Expand All @@ -35,16 +35,19 @@ function sample!(
add_newids!(model, org_ids, newids)
end

"Used in sample!"
#Used in sample!
function add_newids!(model, org_ids, newids)
# `counter` counts the number of occurencies for each item, it comes from DataStructure.jl
count_newids = counter(newids)
n = nextid(model)
for id in org_ids
if !in(id, newids)
kill_agent!(model.agents[id], model)
noccurances = count_newids[id]
agent = model[id]
if noccurances == 0
kill_agent!(agent, model)
else
noccurances = count(x -> x == id, newids)
for t in 2:noccurances
newagent = deepcopy(model.agents[id])
for _ in 2:noccurances
newagent = deepcopy(agent)
newagent.id = n
add_agent_pos!(newagent, model)
n += 1
Expand Down

0 comments on commit a67924b

Please sign in to comment.