Closed ekiefl closed 2 months ago
Speeds were calculated by running this script with the various provided parameters on both this branch and the main branch (prior to merging):
#! /usr/bin/env python
import numpy as np
import pandas as pd
import pooltool as pt
get_pos = lambda table, ball: ( # noqa E731
(table.w - 2 * ball.params.R) * np.random.rand() + ball.params.R,
(table.l - 2 * ball.params.R) * np.random.rand() + ball.params.R,
ball.params.R,
)
def place_ball(i, balls, table):
ball = pt.Ball(i)
while True:
new_pos = get_pos(table, ball)
ball.state.rvw[0] = new_pos
for other in balls.values():
if pt.ptmath.is_overlapping(
ball.state.rvw, other.state.rvw, ball.params.R, other.params.R
):
break
else:
return ball
def main(args):
pt.simulate(pt.System.example())
data = {
"n": [],
"mu": [],
"sigma": [],
"stddev": [],
}
for n in range(2, args.N, args.s):
times = []
for _ in range(args.M):
table = pt.Table.from_table_specs(pt.objects.PocketTableSpecs(l=2, w=1))
balls = {}
balls["cue"] = place_ball("cue", balls, table)
for i in range(n):
balls[str(i)] = place_ball(str(i), balls, table)
cue = pt.Cue(cue_ball_id="cue")
shot = pt.System(cue=cue, table=table, balls=balls)
shot.strike(V0=10, phi=pt.aim.at_ball(shot, "1"))
with pt.terminal.TimeCode(quiet=True) as timer:
pt.simulate(shot, continuous=False, inplace=True)
times.append(timer.time.total_seconds())
mu = np.mean(times)
sigma = np.std(times)
data["n"].append(n)
data["mu"].append(mu)
data["sigma"].append(sigma)
data["stddev"].append(sigma / np.sqrt(n))
print(f"Ball count: {n}")
print(f"Time: {mu:.3f}s +- {sigma:.4f}s")
print("---")
df = pd.DataFrame(data)
df.to_csv(args.output, sep="\t", index=False)
if __name__ == "__main__":
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-M", type=int, default=200, help="Number of trials")
ap.add_argument("-N", type=int, default=9, help="Max number of balls")
ap.add_argument("-s", type=int, default=3, help="Step size")
ap.add_argument("--output", type=str, required=True, help="Output txt file")
args = ap.parse_args()
main(args)
And visualized with this script:
import pandas as pd
import plotly.graph_objects as go
# Load the data
time_dev = pd.read_csv('speed_dev.txt', sep='\t')
time_main = pd.read_csv('speed_main.txt', sep='\t')
time_granular_dev = pd.read_csv('speed_granular_dev.txt', sep='\t')
time_granular_main = pd.read_csv('speed_granular_main.txt', sep='\t')
# Create the first plot
fig = go.Figure()
# Time Dev (dark red)
fig.add_trace(go.Scatter(
x=time_dev['n'],
y=time_dev['mu'],
error_y=dict(type='data', array=time_dev['sigma']),
mode='lines+markers',
name='Time (cache)',
line=dict(color='darkred')
))
# Time Main (dark grey)
fig.add_trace(go.Scatter(
x=time_main['n'],
y=time_main['mu'],
error_y=dict(type='data', array=time_main['sigma']),
mode='lines+markers',
name='Time (no cache)',
line=dict(color='darkgrey')
))
# Update layout for the first plot
fig.update_layout(
title='Time Comparison (Caching versus no caching)',
xaxis_title='Number of balls in simulation',
yaxis_title='Mean Time (s)',
legend=dict(x=0.1, y=0.9),
margin=dict(l=50, r=50, t=50, b=50),
width=600,
height=600,
)
# Create the second plot
fig2 = go.Figure()
# Time Granular Dev (dark red)
fig2.add_trace(go.Scatter(
x=time_granular_dev['n'],
y=time_granular_dev['mu'],
error_y=dict(type='data', array=time_granular_dev['sigma']),
mode='lines+markers',
name='Time (cache)',
line=dict(color='darkred')
))
# Time Granular Main (dark grey)
fig2.add_trace(go.Scatter(
x=time_granular_main['n'],
y=time_granular_main['mu'],
error_y=dict(type='data', array=time_granular_main['sigma']),
mode='lines+markers',
name='Time (no cache)',
line=dict(color='darkgrey')
))
# Update layout for the second plot
fig2.update_layout(
title='Time Comparison (Caching versus no caching)',
xaxis_title='Number of balls in simulation',
yaxis_title='Mean Time (s)',
legend=dict(x=0.1, y=0.9),
margin=dict(l=50, r=50, t=50, b=50),
width=600,
height=600,
)
# Show figures
fig.show()
fig2.show()
Based on reviewer feedback (https://github.com/pyOpenSci/software-submission/issues/173), an idea sprouted to cache event times to avoid recalculation at every step of the shot evolution algorithm. This PR implements that.
The results yield improvements in simulation time for random simulations, using ball number as a parameter for simulation complexity:
The improvement is more dramatic when the number of balls is dramatically increased: