Skip to content

New strategy to choose optimal cutoff in Grid.move_to_empty - #1565

Merged
rht merged 1 commit into
mesa:mainfrom
ameligrana:patch-29
May 11, 2023
Merged

rht merged 1 commit into
mesa:mainfrom
ameligrana:patch-29

Conversation

@ameligrana

@ameligrana ameligrana commented Dec 18, 2022 •

Copy link
Copy Markdown
Contributor

I calculated the optimal cutoff for move_to_empty...but it wasn't as simple as I was expecting :-)
The problem is that a unique optimal cutoff value doesn't exist because, while the first branch has fixed time of execution if you fix a density (number of empty cells over the total number of cells), the second one doesn't since it operates on the empty cells iterating on them so the relevant parameter here is exclusively the number of empty cells which is not unique if the density is fixed. This means that, given a certain number of total cells, we need to find what is the optimal value of empty cells so as to switch between the two branches/algorithms. This is done through the following piece of code:

# analysis of cutoff value for move_to_empty
# rerun this code to check for the stability of the parameters when a new release gets out.

import timeit, random, itertools, scipy
from time import perf_counter
import matplotlib.pyplot as plt
from mesa.space import Grid
import numpy as np
from scipy.optimize import curve_fit

# step 1 - time of randrange doesn't depend on range of values

def calc_exec_time_randrange(n=3*10**3):
    setup = "import random"
    all_times = {}
    for x in range(1, n):
        stmt = f"random.randrange(0,{x})"
        time_f = min(timeit.repeat(stmt, setup, number=1000, repeat=200))
        all_times[x] = time_f
    y_min, y_max = min(all_times.values()), max(all_times.values())
    plt.plot(all_times.keys(), all_times.values(), '-o')
    plt.axhline(y=y_min); plt.axhline(y=y_max)
    plt.margins(0.01, 0.03)
    print(y_min, y_max, y_max/y_min) # 1.3 - little difference from min to max
    plt.show()

# calc_exec_time_randrange(n)

# step 2 - Find optimal cutoff through intersection of timing curves

class MockAgent():
    def __init__(self):
        self.random = random
        self.pos = None

def find_curve_for_first_branch(width, height):
    positions = itertools.product(range(width), range(height))
    grid = Grid(width, height, True); grid.empties
    grid.cutoff_empties = 0
    dict_times = {}
    for k, pos in enumerate(positions):
        agent = MockAgent()
        cum_time = 0
        for x in range(5):
            t_0 = perf_counter()
            grid.move_to_empty(agent) 
            t_1 = perf_counter()
            cum_time += t_1-t_0
            grid.remove_agent(agent)
        if k % 50000 == 0: print(k)
        grid.place_agent(agent, pos)
        dict_times[k/width] = cum_time
    return dict_times

def find_curve_for_second_branch(width, height, from_val=0):
    positions = itertools.product(range(width), range(height))
    grid = Grid(width, height, True); grid.empties
    grid.cutoff_empties = width*height
    dict_times = {}
    for k, pos in enumerate(positions):
        agent = MockAgent()
        if k < int(from_val*width): grid.place_agent(agent, pos); continue
        cum_time = 0
        for x in range(5):
            t_0 = perf_counter()
            grid.move_to_empty(agent)
            t_1 = perf_counter()
            cum_time += t_1-t_0
            grid.remove_agent(agent)
        grid.place_agent(agent, pos)
        dict_times[k/width] = cum_time
    return dict_times

def find_optimal_cutoff(check_cutoff_vals):
    all_values = []
    max_width, height = max(check_cutoff_vals), 1
    g = find_curve_for_first_branch(max_width, height)
    for x in check_cutoff_vals:
        from_val = 0 if not all_values else all_values[-1][1]
        f = find_curve_for_second_branch(x, height, from_val=from_val)
        f_p, g_p  = np.array(list(f.values())), np.array([g[x] for x in f])
        idx = np.argwhere(np.diff(np.sign(f_p - g_p))).flatten()
        new_val = np.mean(idx+int(from_val*x))/x
        all_values.append((x, new_val))
        print(x, new_val)
    return all_values

def func(x, a, b): return 1 - b*(np.exp(-a*x))

rg = range(5,24) # change 24 to a smaller number to obtain results faster, but when new parameters are calculated it's important to use a high value like 24
all_values = find_optimal_cutoff([2**x for x in rg])
pred_values = curve_fit(func, list(rg), [x[1] for x in all_values]); print(pred_values)
a, b = pred_values[0]; trans_a = 1-a/np.log(2)
print("the parameters are: {} and {}".format(b, trans_a)) # parameters to use in self.cutoff_empties
plt.plot(list(rg), [x[1] for x in all_values], "o-")
plt.plot(list(rg), [func(x, *pred_values[0]) for x in rg])
plt.show()

which produced the following prediction function with the optimal cutoff values from the powers of 2 between 5 and 23:

n_approx2

The prediction function was chosen so that the limiting value was 1 and the function was always increasing as one would expect.

Things to notice in the code which produces the output:

  • calc_exec_time_randrange was used to check if random.randrange had a variable time of execution in relation to the range of values, this didn't happen, it is almost constant, so we can say that the only relevant parameter for the time of the first branch is the density of the grid;
  • find_curve_for_first_branch is used to find the curve of times of execution for the first branch in the case of maximum value of number of total cells (2**23 is used in the code). You just need to calculate this curve one time because for each density there is (roughly) only one corresponding value of time of execution;
  • find_curve_for_second_branch was used to find the curve of timings for the second branch; notice that it starts to search from the value given in from_val = 0 if not all_values else all_values[-1][1] because the optimal cutoff is always increasing more and more the value of the total number of cells increases;
  • the prediction function in func(x, a, b) was then transformed in the modified code because I realized a simpler expression was possible.

Hope that is not impossible to follow along the code!

@codecov

codecov Bot commented Dec 18, 2022 •

Copy link
Copy Markdown

Codecov Report

Patch coverage: 100.00% and project coverage change: +0.34 🎉

Comparison is base (a86414b) 81.65% compared to head (454934d) 82.00%.

❗ Current head 454934d differs from pull request most recent head c9fe1e6. Consider uploading reports for the commit c9fe1e6 to get more accurate results

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1565      +/-   ##
==========================================
+ Coverage   81.65%   82.00%   +0.34%     
==========================================
  Files          18       18              
  Lines        1401     1389      -12     
  Branches      272      272              
==========================================
- Hits         1144     1139       -5     
+ Misses        211      206       -5     
+ Partials       46       44       -2     
Impacted Files Coverage Δ
mesa/space.py 90.90% <100.00%> (-0.14%) ⬇️

... and 14 files with indirect coverage changes

☔ View full report in Codecov by Sentry.
📢 Do you have feedback about the report comment? Let us know in this issue.

@rht

rht commented Dec 19, 2022

Copy link
Copy Markdown
Contributor

This likely depends on the Python version as well? Did you try on 3.10? 3.11 has perf improvements.

@ameligrana

ameligrana commented Dec 19, 2022 via email

Copy link
Copy Markdown
Contributor Author

@rht

rht commented Dec 19, 2022

Copy link
Copy Markdown
Contributor

What are the 2 numbers for 3.10?

@ameligrana

Copy link
Copy Markdown
Contributor Author

There is a minimal difference

3.10 -> 0.388, 3.11 -> 0.384
3.10 -> 7.678, 3.11 -> 7.953

It has almost no impact on the cutoff values

@ameligrana

ameligrana commented Dec 19, 2022 •

Copy link
Copy Markdown
Contributor Author

example:

3.10 -> prediction at 100 -> 54.159
3.11 -> prediction at 100 -> 53.384

3.10 -> prediction at 10000 ->9726.317
3.11 -> prediction at 10000 ->9726.768

I'd use the 3.11 values for everything, the difference in the prediction is very minimal

@ameligrana

ameligrana commented Dec 20, 2022 •

Copy link
Copy Markdown
Contributor Author

This is a comparison for a 100x100 grid where the orange curve is the new method:

comp

it performs much better with high densities.

@rht

rht commented Dec 21, 2022

Copy link
Copy Markdown
Contributor

I see, then we can use 3.11, but needs to add comment saying that the number is for 3.11 only.

One issue is that only you can quickly update the numbers to reflect 3.12, unless there is a standalone script that benchmarks and outputs the numbers. Why does Agents.jl need only a single cutoff number, but 2 in Mesa?

@ameligrana

ameligrana commented Dec 21, 2022 •

Copy link
Copy Markdown
Contributor Author

Agent.jl cutoff value uses a more roughly approximation, the way with 2 values reflects the fact that there is not just 1 parameter which controls the time of execution of the two branches, but we have two independent parameters, in the sense that one can have an arbitrary value given the value of the other one, they are:

  1. the density of the grid (number of empty cells over total number of cells), which controls entirely the time of the first branch;
  2. the number of empty cells, which controls entirely the time of the second branch.

That's why we have 2 parameters instead of just 1, using just the density is not a complete way to compute the cutoff.

For the other question, the cutoff value can be easily updated running the code above, but you are right, it is actually necessary to add the last part which transforms the parameters, I'll change the code adding that part.

@ameligrana

ameligrana commented Dec 21, 2022 •

Copy link
Copy Markdown
Contributor Author

ok, now the code is complete, it prints the exact parameters values!

@ameligrana

Copy link
Copy Markdown
Contributor Author

any comments on this one @rht?

Comment thread mesa/space.py Resolved
@rht

rht commented Dec 31, 2022

Copy link
Copy Markdown
Contributor

The benchmark code could be made clearer. First/second branch should be renamed to the actual method naming, maybe "random_retries" and "with_empties" or something.

The perf improvement is only for the case when the density is almost 100% (and so there is no rush to merge this), but I think the main contribution of this PR is in the rigor for calculating cutoff. Not sure if a GH comment is a good place to "store" the code for the cutoff finder.

@ameligrana

Copy link
Copy Markdown
Contributor Author

We can put maybe a cleaned-up version in the tests folder?

@ameligrana

Copy link
Copy Markdown
Contributor Author

what about this last proposal @rht?

@rht

rht commented Jan 8, 2023

Copy link
Copy Markdown
Contributor

The tests folder doesn't make sense to me. The benchmarking code doesn't count as a test. But I haven't come up with a better location either, hence why I didn't answer your question.

I think a benchmark or misc folder would be fine though. This doesn't affect the API at all, and so can always be safely moved to a separate repo when it becomes too big. My default would be misc/benchmark_grid_move_to_empty_cutoff.py.

Is there a way to abstract out the find_curve_* to a single function that accepts a function that does it differently?

@tpike3 tpike3 added this to the Mesa 2.0 milestone Jan 8, 2023
@rht

rht commented May 11, 2023

Copy link
Copy Markdown
Contributor

Rebased. For future update, the benchmark code should live in tests/benchmark. But this doesn't need to be done now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants