69 """Use a staged targeted scheduler with caller-defined rewrite strategies and checks.
71 :param context: Original context. Bind the question and answer specification
72 to the editor and validator callbacks.
73 :param edits: Ordered nonempty labels for the edit axis.
74 :param support: Ordered nonempty labels for the support axis. The first
75 label is the default bootstrap target.
76 :param inherit_support: Edit labels that require a parent in the target
77 support level. The default uses insertion and reordering labels.
78 :param bootstrap: Ordered cells to attempt from the original context.
79 :param target_attempts: Maximum attempts to fill each cell during coverage.
80 :param coverage_patience: End coverage after this many attempts with no new cell.
81 :param seed: Seed for ties in target selection.
84 def __init__(self, context, *, edits=(
"distractor",
"reorder",
"style"),
85 support=(
"direct",
"paraphrastic",
"discourse",
"multi-sentence"),
86 inherit_support=
None, bootstrap=
None, target_attempts=2, coverage_patience=5, seed=0):
87 if not isinstance(context, str)
or not context.strip():
88 raise ValueError(
"Supply a nonempty original context.")
89 edits, support = tuple(edits), tuple(support)
90 for axis
in (edits, support):
91 if not axis
or any(
not isinstance(label, str)
or not label
for label
in axis)
or len(set(axis)) != len(axis):
92 raise ValueError(
"Each axis needs distinct, nonempty labels.")
94 self.
cells = tuple(product(edits, support))
95 self.
_bootstrap = (tuple((edit, support[0])
for edit
in edits)
if bootstrap
is None
96 else tuple(map(tuple, bootstrap)))
97 self.
_inherit = (set(edits) & {
"distractor",
"reorder"}
if inherit_support
is None
98 else set(inherit_support))
100 raise ValueError(
"Bootstrap and inherited labels must belong to the configured axes.")
101 self.
_attempt_limit = _positive_int(target_attempts,
"target_attempts")
102 self.
_patience = _positive_int(coverage_patience,
"coverage_patience")
103 self.
_rng = np.random.default_rng(seed)
110 """Return one immutable elite per occupied cell in axis order."""
115 """Return cumulative construction and answer call counts."""
118 def _attempt(self, source, target, edit, assess):
120 text = edit(source, target, self.
_rng)
121 if (
not isinstance(text, str)
or not text.strip()
122 or text.strip()
in {self.
context, source, *(entry.text
for entry
in self.
entries)}):
123 self.
_counts[
"rejections"] += 1
126 self.
_counts[
"assessments"] += 1
127 measured = assess(source, text, target)
129 self.
_counts[
"rejections"] += 1
131 cell, quality = measured
132 cell, quality = tuple(cell), float(quality)
133 if cell
not in self.
cells or cell[0] != target[0]
or not isfinite(quality):
134 raise ValueError(
"Return a realized cell of the requested edit type and a finite quality.")
136 if old
is None or quality > old.quality:
138 self.
_counts[
"admissions"] += 1
141 def run(self, edit, assess, *, budget, refinement_reserve=0):
142 """Spend up to budget editor calls. Leave unused work if no action is possible.
144 :param edit: Callback (parent_context, target_cell, rng) returning text or None.
145 :param assess: Callback (parent_context, rewrite, target_cell) returning
146 (realized_cell, quality), or None when answer preservation or edit
147 verification fails. Use the same original answer specification throughout.
148 :param budget: Maximum additional editor calls, including rejected edits.
149 :param refinement_reserve: Portion of budget reserved for occupied cells.
151 budget = _positive_int(budget,
"budget")
152 reserve = index(refinement_reserve)
153 if not (0 <= reserve <= budget
and callable(edit)
and callable(assess)):
154 raise ValueError(
"Supply callable operators and a refinement reserve within the budget.")
155 stop = self.
stats.edits + budget
161 while self.
stats.edits < stop - reserve
and stalled < self.
_patience:
162 parents = sorted(self.
entries, key=
lambda entry: -entry.quality)
164 cell: parent
for cell
in self.
cells
166 and (parent := next((row
for row
in parents
if cell[0]
not in self.
_inherit
167 or row.cell[1] == cell[1]),
None))
is not None
171 fewest = min(self.
_targeted[cell]
for cell
in options)
172 tied = [cell
for cell
in options
if self.
_targeted[cell] == fewest]
173 target = tied[int(self.
_rng.integers(len(tied)))]
176 self.
_attempt(options[target].text, target, edit, assess)
177 stalled = 0
if len(self.
_entries) > before
else stalled + 1
179 parent = min(self.
entries, key=
lambda row: (self.
_refined[row.cell], row.quality))
181 self.
_attempt(parent.text, parent.cell, edit, assess)
185 def probe(self, predict, *, group=None, limit=None):
186 """Call predict once per selected text and group answers by a hashable key.
188 The default groups exact answer strings. Pass a normalizer or a semantic
189 class callback for equivalent answers. When limited, query the
190 highest-quality elites first. Empty neighborhoods have undefined entropy.
192 if not callable(predict)
or group
is not None and not callable(group):
193 raise ValueError(
"Supply prediction and optional grouping callbacks.")
194 rows = sorted(self.
entries, key=
lambda row: -row.quality)
195 if limit
is not None:
196 rows = rows[:_positive_int(limit,
"limit")]
199 self.
_counts[
"answer_calls"] += 1
200 answer = predict(row.text)
201 if not isinstance(answer, str):
202 raise ValueError(
"The predictor must return an answer string.")
203 answers.append(answer)
run(self, edit, assess, *, budget, refinement_reserve=0)
Bootstrap from the source, fill empty cells, then improve occupied cells.
One assessed rewrite and its realized location.