Skip to content

Commit cd44299

Browse files
committed
Cleanup: cleaned up python code
1 parent 5a34888 commit cd44299

9 files changed

Lines changed: 37 additions & 55 deletions

File tree

15.1 KB
Loading

src/benchmarking/python/scripts/image.py renamed to src/benchmarking/python/image_editing/image.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,18 +21,22 @@ def __init__(self, image_1: Path, image_2: Path):
2121
if self.image_2.size != self.image_1.size:
2222
self.image_2 = self.image_2.resize(image_1.size)
2323

24+
"""
25+
CURRENTLY WIP
26+
- DOES NOT ACHIEVE DESIRED RESULT
27+
"""
2428
def diff(self, output_name: str = "diff.png"):
2529
copy_1 = self.image_1
2630
copy_2 = self.image_2
2731

2832
diff = ImageChops.difference(copy_1, copy_2)
2933

30-
overlay = Image.alpha_composite(copy_1, copy_2)
34+
# overlay = Image.alpha_composite(copy_1, copy_2)
3135

3236
script_dir = Path(__file__).resolve().parent
3337
output_path = script_dir / output_name
3438

35-
overlay.save(output_path)
39+
diff.save(output_path)
3640

3741
print(f"Saved diff to: {output_path}")
3842

File renamed without changes.

src/benchmarking/python/pixi.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,4 @@ pillow = "*"
1313

1414
[tasks]
1515
main = "python -m scripts.main"
16-
picture = "python -m scripts.image"
16+
image = "python -m image_editing.image"

src/benchmarking/python/plotting/ExchangePlot.py

Lines changed: 9 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -42,21 +42,9 @@ def iter_rows(self):
4242
}
4343

4444
# 2D array of processed data frame into [["Open", "Close", "High", "Low", "Volume"], ...]
45+
# aggregates trades into candlesticks over 'cycles' instead of timestamp
46+
# last value in array is the trade price
4547
def _process_csv(self, cycles: int = 10, cycle_range: tuple[int, int] | None = None, source: str = "expected") -> list[list[float]]:
46-
"""
47-
agg trades into candlesticks over `cycles` rows.
48-
49-
Uses the last value of prices in a row as the trade price; volume is
50-
the sum of quantities for that row. Empty rows (no trades) advance the
51-
cycle window but do not change OHLCV unless a trade occurs in the window.
52-
Returns a list of [Open, Close, High, Low, Volume].
53-
54-
Args:
55-
cycles: Number of rows per candlestick window.
56-
cycle_range: Optional (min, max) tuple to filter rows by cycle number.
57-
source: Either "expected" (exp_prices/exp_qtities) or "actual" (acc_prices/acc_qtities).
58-
"""
59-
6048
candles: list[list[float]] = []
6149

6250
open_price = None
@@ -112,11 +100,10 @@ def _process_csv(self, cycles: int = 10, cycle_range: tuple[int, int] | None = N
112100

113101
return candles
114102

115-
116-
117103
def _split_column(self, col: str):
118104
if col not in self.df:
119105
return
106+
120107
def _to_float_list(value):
121108
if pd.isna(value):
122109
return []
@@ -128,8 +115,10 @@ def _to_float_list(value):
128115
except TypeError:
129116
return [float(value)]
130117

131-
self.df[col] = self.df[col].apply(_to_float_list)
132-
118+
self.df[col] = self.df[col].apply(lambda x: _to_float_list(x))
119+
# self.df[col] = self.df[col].apply(_to_float_list) is equivalent, e.g. x -> f -> f x
120+
121+
# plots the candlestick chart
133122
def plot_candles(self, data, start="2026-01-01", freq="T", title="Stock Price", out: Path | None = None):
134123
df = pd.DataFrame(
135124
data,
@@ -155,19 +144,12 @@ def plot_candles(self, data, start="2026-01-01", freq="T", title="Stock Price",
155144
)
156145

157146
def plot_all(self, out_dir: Path | None = None, cycle_range: tuple[int, int] | None = None):
158-
"""
159-
Generate and save exchange candlestick plots for both expected and actual data.
160-
161-
Args:
162-
out_dir: Output directory. If None, uses default exchange graphs directory.
163-
cycle_range: Optional (min, max) tuple to filter data by cycle range.
164-
"""
165147
if out_dir is None:
166148
out_dir = get_graph_dir("exchange")
167149

168150
base_name = self.csv_path.stem
169151

170-
# Plot expected data
152+
# process csv into useable form
171153
candles_expected = self._process_csv(cycle_range=cycle_range, source="expected")
172154
if candles_expected:
173155
self.plot_candles(
@@ -180,7 +162,7 @@ def plot_all(self, out_dir: Path | None = None, cycle_range: tuple[int, int] | N
180162
else:
181163
print("No expected trades found")
182164

183-
# Plot actual data
165+
# plot actual data
184166
candles_actual = self._process_csv(cycle_range=cycle_range, source="actual")
185167
if candles_actual:
186168
self.plot_candles(

src/benchmarking/python/plotting/LatencyPlot.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ def __init__(self, csv_path: Path):
1414
"dequeue": df["dequeue_latency_ns"].astype(float).values,
1515
}
1616

17-
# Outlier removal (IQR)
17+
# outlier removal (IQR)
1818
def _remove_outliers_iqr(self, data, k=1.5):
1919
q1 = np.percentile(data, 25)
2020
q3 = np.percentile(data, 75)
@@ -96,7 +96,7 @@ def cdf(self, metric="enqueue", title="Latency CDF", out: Path | None = None, re
9696

9797
plt.close()
9898

99-
# Summary
99+
# plot summary of factors
100100
def summary(self, metric="enqueue", remove_outliers=True):
101101
data = self.data[metric]
102102
if remove_outliers:

src/benchmarking/python/plotting/OrderingPlot.py

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22
import pandas as pd
33
import numpy as np
44
import matplotlib.pyplot as plt
5-
from benchmarking.python.plotting.utils import get_graph_dir
5+
from benchmarking.python.plotting.utils import *
6+
7+
"""
8+
Class to plot all the graphs related to order-preservation
9+
"""
610

711
class OrderingPlot:
812
def __init__(self, csv_path: Path):
@@ -14,6 +18,7 @@ def __init__(self, csv_path: Path):
1418
"actual_id": df["actual_id"].astype(float).values,
1519
}
1620

21+
# checks if sequence is identical
1722
def order_preserved(self) -> bool:
1823
return np.array_equal(self.data["expected_id"], self.data["actual_id"])
1924

@@ -65,15 +70,15 @@ def plot_offset(self, title="Actual - Expected", out: Path | None = None, id_ran
6570
exp = self.data["expected_id"]
6671
act = self.data["actual_id"]
6772

68-
# Filter by id_range if provided
73+
# id_range filter
6974
if id_range:
7075
mask = (exp >= id_range[0]) & (exp <= id_range[1])
7176
exp = exp[mask]
7277
act = act[mask]
7378

7479
delta = act - exp
7580

76-
# Only plot points with non-zero offset
81+
# plot points with non-zero offset
7782
offset_mask = delta != 0
7883
exp_offset = exp[offset_mask]
7984
delta_offset = delta[offset_mask]
@@ -97,7 +102,6 @@ def plot_displacement_heatmap(self, title="Displacement Magnitude", out: Path |
97102
exp = self.data["expected_id"]
98103
act = self.data["actual_id"]
99104

100-
# Filter by id_range if provided
101105
if id_range:
102106
mask = (exp >= id_range[0]) & (exp <= id_range[1])
103107
exp = exp[mask]
@@ -125,7 +129,6 @@ def plot_expected_vs_actual_colored(self, title="Expected vs Actual (colored by
125129
exp = self.data["expected_id"]
126130
act = self.data["actual_id"]
127131

128-
# Filter by id_range if provided
129132
if id_range:
130133
mask = (exp >= id_range[0]) & (exp <= id_range[1])
131134
exp = exp[mask]
@@ -150,15 +153,8 @@ def plot_expected_vs_actual_colored(self, title="Expected vs Actual (colored by
150153
plt.show()
151154
plt.close()
152155

153-
# Plot all ordering graphs
156+
# plot all ordering graphs
154157
def plot_all(self, out_dir: Path | None = None, id_range: tuple[int, int] | None = None):
155-
"""
156-
Generate and save all ordering plots to the specified directory.
157-
158-
Args:
159-
out_dir: Output directory. If None, uses default ordering graphs directory.
160-
id_range: Optional tuple (min, max) to filter data by ID range.
161-
"""
162158
if out_dir is None:
163159
out_dir = get_graph_dir("ordering")
164160

src/benchmarking/python/plotting/utils.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from pathlib import Path
2+
23
"""
34
Code that contains all the utility functions for getting most recent graphs,
45
csvs, and directory paths.
@@ -8,22 +9,24 @@
89
def get_root() -> Path:
910
return Path(__file__).resolve().parents[2]
1011

12+
# returns the path for the specific csv directory (exchange, ordering, latencies)
1113
def get_csv_dir(dir: str) -> Path:
1214
return get_root() / "csvs" / dir
1315

16+
# eturns the path for the specific graph directory (exchange, ordering, latencies)
1417
def get_graph_dir(dir: str) -> Path:
1518
path = get_root() / "graphs" / dir
1619
path.mkdir(parents=True, exist_ok=True)
1720
return path
1821

19-
# get the most recent CSV from all directories (exchange, ordering, latencies).
22+
# get the most recent CSV from all directories (exchange, ordering, latencies)
2023
def get_latest_csv(must_match: bool = False) -> dict[str, Path]:
21-
dirs = {"exchange": "exchange", "ordering": "ordering", "latencies": "latencies"}
24+
dirs = ["exchange", "ordering", "latencies"]
2225
latest = {}
2326
timestamps = {}
2427

25-
for key, dir_name in dirs.items():
26-
path = get_csv_dir(dir_name)
28+
for key in dirs:
29+
path = get_csv_dir(key)
2730
csvs = get_csvs_dir(path, reverse=True)
2831
if not csvs:
2932
raise FileNotFoundError(f"No CSVs found in {path}")
@@ -44,9 +47,11 @@ def get_latest_csv(must_match: bool = False) -> dict[str, Path]:
4447

4548
return latest
4649

50+
# returns the most recent csv in the directory specified
4751
def get_latest_csv_dir(dir: str) -> Path:
4852
return get_latest_csv()[dir]
4953

54+
# returns all the csvs in the directory specified
5055
def get_csvs_dir(path: Path, reverse: bool = False):
5156
return sorted(path.glob("*.csv"), reverse=reverse)
5257

@@ -60,13 +65,8 @@ def get_csv_all_dirs(name: str) -> dict[str, bool]:
6065
dirs = ["exchange", "ordering", "latencies"]
6166
return {dir_name: get_csv(name, dir_name) for dir_name in dirs}
6267

68+
# returns a dictionary of directories to Paths if the file name is in any of the directories
6369
def get_csv_all_dirs_name(name: str) -> dict[str, Path]:
64-
"""
65-
Find a CSV by name across all directories and return full paths.
66-
67-
Returns:
68-
Dictionary mapping dir names to full CSV paths where the file exists.
69-
"""
7070
dirs = ["exchange", "ordering", "latencies"]
7171
result = {}
7272
for dir_name in dirs:
-46.4 KB
Binary file not shown.

0 commit comments

Comments
 (0)