File size: 15,286 Bytes
17cc850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f070327
17cc850
 
f070327
 
 
 
 
 
 
 
17cc850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd102bd
 
17cc850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd102bd
 
17cc850
 
 
 
 
 
f070327
17cc850
 
 
 
 
 
f070327
 
17cc850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd102bd
 
17cc850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f070327
17cc850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
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()