Coverage for src/retrospeedlab/docs_site/experiments.py: 97%

74 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-12-02 22:44 +0000

1from collections.abc import Callable 

2from datetime import datetime 

3 

4from retrospeedlab.docs_site.cells import CLEAR, Cell, Table, Tile, bar, number, pill, text 

5from retrospeedlab.docs_site.labels import ( 

6 NOT_YET, 

7 PERCENT, 

8 age_label, 

9 count_label, 

10 fixed, 

11 game_title, 

12 rounded, 

13 share_label, 

14 tenths, 

15) 

16from retrospeedlab.docs_site.lake import source_name 

17from retrospeedlab.docs_site.payloads import ( 

18 EngagementExperiment, 

19 EstimatedMetric, 

20 LabExperiment, 

21 PromotionDimension, 

22 PromotionVariant, 

23) 

24 

25MIN_HOURS = 12 

26P_DIGITS = 3 

27METRICS = { 

28 "frames_saved_per_hour": "Frames saved per searched hour", 

29 "crossing_rate": "Attempts that crossed into a new state", 

30 "record_hour_rate": "Searched hours with a new record", 

31 "verify_failure_rate": "Won runs that did not replay", 

32} 

33RATES = frozenset({"crossing_rate", "record_hour_rate", "verify_failure_rate"}) 

34DIMENSIONS = {"cta": "call to action", "tags": "hashtags"} 

35 

36 

37def metric_name(metric: str) -> str: 

38 return METRICS[metric] if metric in METRICS else metric 

39 

40 

41def shown(metric: str, value: float) -> str: 

42 return f"{fixed(value * PERCENT, 1)}%" if metric in RATES else fixed(value, 1) 

43 

44 

45def signed(metric: str, value: float) -> str: 

46 return f"{'+' if value > 0 else ''}{shown(metric, value)}" 

47 

48 

49def estimate_label(metric: EstimatedMetric) -> str: 

50 if metric.control_estimate is None or metric.treatment_estimate is None: 

51 return NOT_YET 

52 return f"{shown(metric.metric, metric.control_estimate)} → {shown(metric.metric, metric.treatment_estimate)}" 

53 

54 

55def interval_label(metric: EstimatedMetric) -> str: 

56 if metric.ci_lower is None or metric.ci_upper is None or metric.confidence is None: 

57 return NOT_YET 

58 interval = f"{signed(metric.metric, metric.ci_lower)} to {signed(metric.metric, metric.ci_upper)}" 

59 return f"{rounded(metric.confidence * PERCENT)}% interval {interval}" 

60 

61 

62def p_label(value: float | None) -> str: 

63 return NOT_YET if value is None else fixed(value, P_DIGITS) 

64 

65 

66def dimension_name(dimension: str) -> str: 

67 return DIMENSIONS[dimension] if dimension in DIMENSIONS else dimension 

68 

69 

70def experiment_rows(experiment: LabExperiment, titles: dict[str, str], now: datetime) -> list[list[Cell]]: 

71 run: list[Cell] = [game_title(titles, experiment.game), age_label(experiment.changed_at, now)] 

72 if not any(metric.enough for metric in experiment.metrics): 

73 first = experiment.metrics[0] 

74 hours = f"{first.control_n} h before, {first.treatment_n} h after" 

75 return [[*run, NOT_YET, pill("not enough data yet"), hours, f"needs {MIN_HOURS} h each side", NOT_YET]] 

76 return [ 

77 [ 

78 *run, 

79 metric_name(metric.metric), 

80 pill(metric.verdict), 

81 estimate_label(metric), 

82 interval_label(metric), 

83 p_label(metric.holm_p), 

84 ] 

85 for metric in experiment.metrics 

86 ] 

87 

88 

89def change_takeaway(experiments: list[LabExperiment]) -> str: 

90 verdicts = [{metric.verdict for metric in experiment.metrics} for experiment in experiments] 

91 better = sum("better" in found for found in verdicts) 

92 worse = sum("worse" in found for found in verdicts) 

93 clear = sum(bool(found & CLEAR) for found in verdicts) 

94 if not clear: 

95 return f"None of the {len(experiments)} lab changes has a clear effect yet." 

96 moved = f"{clear} of {len(experiments)} lab changes moved a metric clearly" 

97 return f"{moved}: {better} for the better, {worse} for the worse." 

98 

99 

100def lab_experiments_table(experiments: list[LabExperiment], titles: dict[str, str], now: datetime) -> Table: 

101 return Table( 

102 [ 

103 text("Game"), 

104 text("Shipped"), 

105 text("Metric"), 

106 text("Verdict"), 

107 number("Before → after"), 

108 number("Interval"), 

109 number("Adjusted p"), 

110 ], 

111 [row for experiment in experiments for row in experiment_rows(experiment, titles, now)], 

112 "No lab change has been measured yet.", 

113 change_takeaway(experiments) if experiments else None, 

114 None, 

115 ) 

116 

117 

118def bandit_table(comparison: EstimatedMetric | None) -> Table: 

119 rows: list[list[Cell]] = ( 

120 [ 

121 [ 

122 metric_name(comparison.metric), 

123 pill(comparison.verdict), 

124 estimate_label(comparison), 

125 interval_label(comparison), 

126 p_label(comparison.p_value), 

127 ] 

128 ] 

129 if comparison is not None and comparison.enough 

130 else [] 

131 ) 

132 takeaway = ( 

133 None 

134 if comparison is None 

135 else f"{count_label(comparison.treatment_n)} bandit turns against {count_label(comparison.control_n)}" 

136 f" held out: {comparison.verdict}." 

137 ) 

138 return Table( 

139 [text("Metric"), text("Verdict"), number("Held out → bandit"), number("Interval"), number("p")], 

140 rows, 

141 "The search bandit has not gathered enough turns yet.", 

142 takeaway, 

143 None, 

144 ) 

145 

146 

147def value_range(lower: float, upper: float, label: Callable[[float], str]) -> str: 

148 return f"{label(lower)}–{label(upper)}" 

149 

150 

151def whole(value: float) -> str: 

152 return count_label(rounded(value)) 

153 

154 

155def per_dollar(value: float | None, lower: float | None, upper: float | None) -> str: 

156 if value is None: 

157 return NOT_YET 

158 return whole(value) if lower is None or upper is None else f"{whole(value)} ({value_range(lower, upper, whole)})" 

159 

160 

161def promotion_dimensions_table(dimensions: list[PromotionDimension]) -> Table: 

162 rows: list[list[Cell]] = [ 

163 [ 

164 dimension_name(dimension.dimension), 

165 dimension.value, 

166 tenths(dimension.posts), 

167 f"{tenths(dimension.per_post)} ({value_range(dimension.lower, dimension.upper, tenths)})", 

168 bar(share_label(dimension.share), dimension.share, 1), 

169 ] 

170 for dimension in dimensions 

171 ] 

172 strongest = max(dimensions, key=lambda dimension: dimension.share) if dimensions else None 

173 return Table( 

174 [text("Choice"), text("Value"), number("Posts"), number("Engagement per post"), number("Next posts")], 

175 rows, 

176 "No Bluesky post has been scored yet.", 

177 None 

178 if strongest is None 

179 else f'The strongest lean: "{strongest.value}" as {dimension_name(strongest.dimension)},' 

180 f" in {share_label(strongest.share)} of the next posts.", 

181 None, 

182 ) 

183 

184 

185def shorts_variants_table(variants: list[PromotionVariant]) -> Table: 

186 liked = [(variant.likes_per_dollar, variant) for variant in variants if variant.likes_per_dollar is not None] 

187 best = max(liked, key=lambda pair: pair[0])[1] if liked else None 

188 rows: list[list[Cell]] = [ 

189 [ 

190 source_name(variant.channel), 

191 str(variant.variant), 

192 count_label(variant.drafts), 

193 per_dollar(variant.views_per_dollar, variant.views_lower, variant.views_upper), 

194 per_dollar(variant.likes_per_dollar, variant.likes_lower, variant.likes_upper), 

195 ] 

196 for variant in variants 

197 ] 

198 return Table( 

199 [text("Channel"), number("Variant"), number("Drafts"), number("Views per dollar"), number("Likes per dollar")], 

200 rows, 

201 "No promotion has been drafted yet.", 

202 None 

203 if best is None 

204 else f"Variant {best.variant} on {source_name(best.channel)} draws the most likes per dollar.", 

205 None, 

206 ) 

207 

208 

209def experiments_tile(changes: list[LabExperiment], comparisons: list[EngagementExperiment]) -> Tile: 

210 tests = {row.experiment for row in comparisons} 

211 clear_tests = {row.experiment for row in comparisons if row.verdict in CLEAR} 

212 clear_changes = [change for change in changes if any(metric.verdict in CLEAR for metric in change.metrics)] 

213 return Tile( 

214 "Experiments", 

215 count_label(len(changes) + len(tests)), 

216 f"{count_label(len(clear_changes) + len(clear_tests))} with a clear effect", 

217 )