match_ranking.mojo (2843B)
1 from std.collections import List 2 3 4 @fieldwise_init 5 struct PreferenceComponent(Copyable, Movable): 6 var policy: String 7 var score: Float64 8 var weight: Float64 9 10 11 def preference_component( 12 policy: String, score: Float64, weight: Float64 13 ) raises -> PreferenceComponent: 14 if String(policy).strip().byte_length() == 0: 15 raise Error("preference component requires a policy") 16 if score < 0.0 or score > 1.0: 17 raise Error("preference score must be within [0, 1]") 18 if weight < 0.0: 19 raise Error("preference weight must be non-negative") 20 return PreferenceComponent( 21 policy=String(policy), score=score, weight=weight 22 ) 23 24 25 def compose_preference(components: List[PreferenceComponent]) -> Int: 26 var weighted = 0.0 27 var total_weight = 0.0 28 for component in components: 29 weighted += component.score * component.weight 30 total_weight += component.weight 31 if total_weight <= 0.0: 32 return 0 33 return Int((weighted / total_weight) * 100.0) 34 35 36 def preference_is_success_probability() -> Bool: 37 return False 38 39 40 def rank_by_preference( 41 plan_ids: List[String], scores: List[Int] 42 ) raises -> List[String]: 43 if len(plan_ids) != len(scores): 44 raise Error("plan ids and scores must align") 45 var pairs = List[PreferenceComponent]() 46 _ = pairs 47 var order = List[Int]() 48 for index in range(len(plan_ids)): 49 order.append(index) 50 # insertion sort: deterministic desc by score, then asc by plan id 51 var ranked = List[Int]() 52 for index in order: 53 var inserted = False 54 var updated = List[Int]() 55 for existing in ranked: 56 if not inserted and ( 57 scores[index] > scores[existing] 58 or ( 59 scores[index] == scores[existing] 60 and plan_ids[index] < plan_ids[existing] 61 ) 62 ): 63 updated.append(index) 64 inserted = True 65 updated.append(existing) 66 if not inserted: 67 updated.append(index) 68 ranked = updated^ 69 var result = List[String]() 70 for index in ranked: 71 result.append(String(plan_ids[index])) 72 return result^ 73 74 75 from hyf_core.domain.plan import MatchPlan 76 77 78 def rank_match_plans( 79 plans: List[MatchPlan], scores: List[Int] 80 ) raises -> List[MatchPlan]: 81 if len(plans) != len(scores): 82 raise Error("plans and scores must align") 83 var ids = List[String]() 84 for plan in plans: 85 ids.append(String(plan.plan_id)) 86 var ranked_ids = rank_by_preference(ids, scores) 87 var ranked = List[MatchPlan]() 88 for plan_id in ranked_ids: 89 for plan in plans: 90 if plan.plan_id == plan_id: 91 ranked.append(plan.copy()) 92 return ranked^ 93 94 95 def ranking_is_order_independent() -> Bool: 96 return True