trackoptimizer / optimizer_pulp.py
smugalamunga's picture
updated for JBC Classic varied race distances
f070327
Raw History Blame Contribute Delete
15.3 kB
import json
import os
from collections import defaultdict
import re
import pulp
GRADE_SCORES = {
"G1": 100,
"G2": 50,
"G3": 25,
"OP": 10,
"Pre-OP": 5
}
APTITUDE_VALUES = {
'S': 7, 'A': 6, 'B': 5, 'C': 4, 'D': 3, 'E': 2, 'F': 1, 'G': 0
}
YEAR_MAP = {"Junior": 0, "Classic": 1, "Senior": 2}
HALF_MAP = {"Early": 0, "Late": 1}
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
# Slots for months 7 (July) and 8 (August) are blocked in all three years
SUMMER_MONTHS = {7, 8}
def get_slot_id(year, month, half):
return (YEAR_MAP[year] * 24) + ((month - 1) * 2) + HALF_MAP[half]
def is_summer_slot(slot):
year_idx = slot // 24 # 0=Junior, 1=Classic, 2=Senior
month = ((slot % 24) // 2) + 1
# Junior year has no summer training restriction
return year_idx > 0 and month in SUMMER_MONTHS
def get_slot_desc(slot_id):
y_idx = slot_id // 24
year = ["Junior", "Classic", "Senior"][y_idx]
m_idx = (slot_id % 24) // 2
month = m_idx + 1
h_idx = slot_id % 2
half = ["Early", "Late"][h_idx]
return f"{year} {MONTHS[month - 1]} {half}"
class UMARaceOptimizerPuLP:
def __init__(self, race_data_path, epithet_data_path):
with open(race_data_path, 'r', encoding='utf-8') as f:
self.races = json.load(f)
with open(epithet_data_path, 'r', encoding='utf-8') as f:
self.epithets = json.load(f)
self.races_by_slot = defaultdict(list)
for r in self.races:
slot = get_slot_id(r['year'], r['month'], r['half'])
self.races_by_slot[slot].append(r)
def optimize(self, aptitudes, cutoff_aptitude='B', locked_slots=None, preferred_distance=None):
"""
locked_slots: dict mapping slot_id (int or str) -> race_name (str) or None
str β†’ this slot must race this specific race (forced, even if ineligible)
None β†’ this slot must be a rest (no race)
preferred_distance: optional "Sprint"|"Mile"|"Medium"|"Long" β€” when equal, prefer races of this type
"""
locked_slots = {int(k): v for k, v in (locked_slots or {}).items()}
cutoff = APTITUDE_VALUES.get(cutoff_aptitude, 5)
def is_apt_ok(race):
surface = race['surface']
dist_type = race['distanceType']
if surface == 'Varies':
return True
s_apt = aptitudes.get(surface, 'G')
s_val = APTITUDE_VALUES.get(s_apt, 0)
d_val = -1
for dt in dist_type.split('/'):
dt_apt = aptitudes.get(dt, 'G')
d_val = max(d_val, APTITUDE_VALUES.get(dt_apt, 0))
return s_val >= cutoff and d_val >= cutoff
prob = pulp.LpProblem("Uma_Race_Optimization", pulp.LpMaximize)
# Decision variables
# β€’ skip Classic/Senior summer slots
# β€’ skip locked-rest slots entirely (no variable = no race possible)
# β€’ always include the locked race even if ineligible
x = {}
eligible_races_in_slot = defaultdict(list)
for slot in range(72):
if is_summer_slot(slot):
continue
if slot in locked_slots and locked_slots[slot] is None:
continue # forced rest β€” skip variable creation
locked_race_name = locked_slots.get(slot)
added_names = set()
for race in self.races_by_slot[slot]:
rname = race['name']
if rname in added_names:
continue
if is_apt_ok(race) or rname == locked_race_name:
safe = rname.replace(' ', '_').replace('(', '').replace(')', '')
x[slot, rname] = pulp.LpVariable(f"run_{slot}_{safe}", cat=pulp.LpBinary)
eligible_races_in_slot[slot].append(race)
added_names.add(rname)
# Edge case: locked race not listed in races_by_slot for this slot
if locked_race_name and locked_race_name not in added_names:
# Find the race in the entire list (slow but correct for edge cases)
race_obj = next((r for r in self.races if r['name'] == locked_race_name), None)
if race_obj:
safe = locked_race_name.replace(' ', '_').replace('(', '').replace(')', '')
x[slot, locked_race_name] = pulp.LpVariable(
f"run_{slot}_{safe}", cat=pulp.LpBinary
)
eligible_races_in_slot[slot].append(race_obj)
y = {}
for ep in self.epithets:
var_name = f"ep_{ep['name'].replace(' ', '_')}_{ep['id']}"
y[ep['id']] = pulp.LpVariable(var_name, cat=pulp.LpBinary)
# Objective: epithets > grade (+ preferred distance worth at most one grade step) > race count
epithet_base_weight = 10000
race_bonus = 1
# Calculate reward-based tie-breaker weights for each epithet
epithet_weights = {}
for ep in self.epithets:
bonus = 0
for reward in ep.get("rewards", []):
# 1. Stat points bonus: 1 point per total stat gain
sm = re.match(r"(\d+) Random Stats \+(\d+)", reward)
if sm:
bonus += int(sm.group(1)) * int(sm.group(2))
# 2. Skill Hint bonuses
# Always desired: Homestretch Haste
if "Homestretch Haste" in reward:
bonus += 50
# Mile specific: if preferred distance is Mile
if preferred_distance == "Mile" and "Mile" in reward:
bonus += 40
# Dirt specific: if Dirt aptitude is A or higher
if "Top Pick" in reward:
dirt_apt = aptitudes.get("Dirt", "G")
if dirt_apt in ["A", "S"]:
bonus += 40
# Ensure bonus doesn't override the primary goal of "more epithets"
# (Bonus is kept small relative to the base weight gap)
epithet_weights[ep['id']] = epithet_base_weight + min(bonus, 500)
# Preferred distance bonus logic for individual races
pref_bonus_map = {
"G1": 1, "G2": 51, "G3": 26, "OP": 1, "Pre-OP": 1
}
objective_terms = [y[ep_id] * epithet_weights[ep_id] for ep_id in y]
for (slot, race_name), var in x.items():
# Find the specific race object for this name in this slot
race = next(r for r in self.races_by_slot[slot] if r['name'] == race_name)
grade = race['grade']
grade_score = GRADE_SCORES.get(grade, 0)
dist_type = race.get('distanceType', '')
# Apply dynamic bonus based on grade
extra = 0
if preferred_distance and preferred_distance in dist_type.split('/'):
extra = pref_bonus_map.get(grade, 1)
# Aptitude tie-breaker: prioritize races where the racer has a higher aptitude.
# This bonus is small enough not to change the priority of grades, but large
# enough to act as a significant tie-breaker for races of the same grade.
s_apt = aptitudes.get(race['surface'], 'G')
d_val = max((APTITUDE_VALUES.get(aptitudes.get(dt, 'G'), 0) for dt in race.get('distanceType', '').split('/')), default=0)
aptitude_bonus = 2 * (APTITUDE_VALUES.get(s_apt, 0) + d_val)
objective_terms.append(var * (grade_score + race_bonus + extra + aptitude_bonus))
prob += pulp.lpSum(objective_terms)
# C1: at most one race per slot
for slot in range(72):
slot_vars = [x[slot, r['name']] for r in eligible_races_in_slot[slot]
if (slot, r['name']) in x]
if slot_vars:
prob += pulp.lpSum(slot_vars) <= 1
# C2: locked slot equality constraints
for slot, race_name in locked_slots.items():
if race_name is None:
continue # forced rest already handled by not creating variables
if (slot, race_name) in x:
prob += x[slot, race_name] == 1
for race in eligible_races_in_slot.get(slot, []):
if race['name'] != race_name and (slot, race['name']) in x:
prob += x[slot, race['name']] == 0
# C2a: no 3 consecutive races (scheduler never schedules 3 in a row; locked races count).
# Exception: allow 3 in a row when the third slot is Late December (end of year)β€”no next
# race means no failure risk, and it enables Japan Cup β†’ Stayer's Stakes β†’ Arima Kinen.
for i in range(70):
if (i + 2) % 24 == 23: # third slot is Late Dec: allow 3 consecutive
continue
triple_vars = []
for s in (i, i + 1, i + 2):
triple_vars.extend(
x[s, r["name"]] for r in eligible_races_in_slot[s]
if (s, r["name"]) in x
)
if triple_vars:
prob += pulp.lpSum(triple_vars) <= 2
# C2b: avoid Early Dec + Late Dec + Early Jan (failure risk)
# Late Dec doesn't count toward the 3-consecutive-race rule but is still a race;
# running all three in a row risks failure in Early January.
for boundary in [0, 1]: # Junior->Classic, Classic->Senior
early_dec = 22 + boundary * 24
late_dec = 23 + boundary * 24
early_jan = 24 + boundary * 24
dec_jan_vars = []
for s in [early_dec, late_dec, early_jan]:
dec_jan_vars.extend(
x[s, r["name"]] for r in eligible_races_in_slot[s]
if (s, r["name"]) in x
)
if dec_jan_vars:
prob += pulp.lpSum(dec_jan_vars) <= 2
# C3: epithet requirement constraints
for ep in self.epithets:
ep_var = y[ep['id']]
for idx, sreq in enumerate(ep.get('structured_requirements', [])):
req_var = pulp.LpVariable(f"req_{ep['id']}_{idx}", cat=pulp.LpBinary)
prob += ep_var <= req_var
self._add_req(prob, req_var, sreq, x, y, eligible_races_in_slot, ep['id'], idx)
prob.solve(pulp.PULP_CBC_CMD(msg=0, timeLimit=60))
schedule = {}
achieved = []
solver_status = pulp.LpStatus[prob.status]
if solver_status in ['Optimal', 'Integer Feasible']:
for (slot, race_name), var in x.items():
if pulp.value(var) and pulp.value(var) > 0.5:
race = next(r for r in self.races_by_slot[slot] if r['name'] == race_name)
schedule[slot] = {"race": race}
for ep in self.epithets:
if pulp.value(y[ep['id']]) and pulp.value(y[ep['id']]) > 0.5:
achieved.append(ep['name'])
else:
print(f"Solver status: {solver_status}")
return schedule, achieved, solver_status
def _add_req(self, prob, req_var, sreq, x_vars, y_vars, eligible_by_slot, ep_id, req_idx):
"""Add ILP constraints modelling one structured requirement."""
t = sreq['type']
if t == 'race':
race_name = sreq['name']
occ = [x_vars[s, race_name] for s in range(72) if (s, race_name) in x_vars]
if occ:
prob += req_var <= pulp.lpSum(occ)
else:
prob += req_var == 0
elif t == 'race_count':
race_name = sreq['name']
count = sreq.get('count', 1)
occ = [x_vars[s, race_name] for s in range(72) if (s, race_name) in x_vars]
if len(occ) >= count:
prob += count * req_var <= pulp.lpSum(occ)
else:
prob += req_var == 0
elif t == 'any':
count = sreq.get('count', 1)
nested = []
for i, cond in enumerate(sreq['conditions']):
nv = pulp.LpVariable(f"nreq_{ep_id}_{req_idx}_{i}", cat=pulp.LpBinary)
nested.append(nv)
self._add_req(prob, nv, cond, x_vars, y_vars, eligible_by_slot, ep_id, f"{req_idx}_{i}")
if nested:
prob += count * req_var <= pulp.lpSum(nested)
else:
prob += req_var == 0
elif t == 'all':
nested = []
for i, cond in enumerate(sreq['conditions']):
nv = pulp.LpVariable(f"nreq_{ep_id}_{req_idx}_{i}", cat=pulp.LpBinary)
nested.append(nv)
self._add_req(prob, nv, cond, x_vars, y_vars, eligible_by_slot, ep_id, f"{req_idx}_{i}")
if nested:
prob += pulp.lpSum(nested) >= len(nested) * req_var
else:
prob += req_var == 0
elif t == 'filter':
count = sreq.get('count', 1)
params = sreq.get('params', {})
matching = []
for slot in range(72):
for race in eligible_by_slot[slot]:
if not self._race_matches_filter(race, params):
continue
if (slot, race['name']) in x_vars:
matching.append(x_vars[slot, race['name']])
if len(matching) >= count:
prob += count * req_var <= pulp.lpSum(matching)
else:
prob += req_var == 0
elif t == 'epithet':
target_id = sreq.get('id')
if target_id in y_vars:
prob += req_var <= y_vars[target_id]
else:
prob += req_var == 0
elif t == 'text':
# 'text' type: Treated as unsatisfiable to avoid false positives.
prob += req_var == 0
else:
# Fallback for unknown types
prob += req_var == 0
@staticmethod
def _race_matches_filter(race, params):
if params.get('surface') and race.get('surface') != params['surface']:
return False
if params.get('grade') and race.get('grade') != params['grade']:
return False
if params.get('min_grade') == 'OP' and race.get('grade') not in ['G1', 'G2', 'G3', 'OP']:
return False
if params.get('min_grade') == 'G3' and race.get('grade') not in ['G1', 'G2', 'G3']:
return False
if params.get('distance_type'):
dist_type = params['distance_type']
if dist_type in ['core', 'non-core']:
dist = race.get('length', 0)
is_core = (dist % 400 == 0)
if dist_type == 'core' and not is_core:
return False
if dist_type == 'non-core' and is_core:
return False
elif dist_type not in race.get('distanceType', '').split('/'):
return False
if params.get('name_contains') and params['name_contains'] not in race.get('name', ''):
return False
if params.get('has_country_name'):
countries = ["Japan", "Dubai", "French", "British", "Saudi"]
if not any(c in race.get('name', '') for c in countries):
return False
if params.get('locations') and race.get('location') not in params['locations']:
return False
return True
def main():
base_path = r"c:\Users\smuga\Code\uma_race_schedule_optimizer"
optimizer = UMARaceOptimizerPuLP(
os.path.join(base_path, "data", "raceData.json"),
os.path.join(base_path, "data", "epithetsData.json")
)
user_aptitudes = {
"Turf": "A",
"Dirt": "G",
"Sprint": "G",
"Mile": "F",
"Medium": "A",
"Long": "A"
}
cutoff = 'C'
print("Running optimization (up to 60s)...")
schedule, achieved, status = optimizer.optimize(user_aptitudes, cutoff)
total_races = len(schedule)
print(f"\nOptimization complete β€” {total_races} races scheduled, {len(achieved)} epithets achieved.")
if achieved:
print(f"Epithets: {', '.join(achieved)}")
for year_name in ["Junior", "Classic", "Senior"]:
year_idx = YEAR_MAP[year_name]
year_slots = {s: v for s, v in schedule.items() if s // 24 == year_idx}
print(f"\n{'─' * 60}")
print(f" {year_name.upper()} YEAR")
print(f"{'─' * 60}")
print(f" {'Month':<10} {'Half':<8} {'Race':<32} {'Grade'}")
print(f" {'─'*10} {'─'*8} {'─'*32} {'─'*6}")
for slot in range(year_idx * 24, (year_idx + 1) * 24):
m_idx = (slot % 24) // 2
month = m_idx + 1
half = "Early" if slot % 2 == 0 else "Late"
if is_summer_slot(slot):
print(f" {MONTHS[month-1]:<10} {half:<8} {'β€” Summer Break β€”':<32}")
elif slot in year_slots:
race = year_slots[slot]['race']
print(f" {MONTHS[month-1]:<10} {half:<8} {race['name']:<32} {race['grade']}")
if __name__ == "__main__":
main()