File size: 13,901 Bytes
b0e3fb9
 
 
 
 
 
 
 
4e7c9ed
 
 
b0e3fb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Maximum flow: exact algorithm against cut enumeration, the LP route, and the flow family."""

import random
from fractions import Fraction as F
from itertools import combinations

import pytest

from lingologos_math import corpus, families, flow, lp, parse_a, parse_b, pipeline, smt
from lingologos_math import fam_flow as ff
from lingologos_math.tree import MathError, fmt_q, from_json, to_json, to_math

SENTENCES = [
    "maxflow [[0, 5, 4, 0], [0, 0, 3, 0], [0, 0, 0, 6], [0, 0, 0, 0]] from 1 to 4",
    "maxflow [[0, 3/2, 0], [0, 0, 5/4], [0, 0, 0]] from 1 to 3",
    "maxflow [[0, 4], [4, 0]] from 1 to 2",
    "maxflow [[0, 2 + 3, 0], [0, 0, 4], [0, 0, 0]] from 1 to 3",
    "maxflow [[0, 6, 0], [0, 0, 2 + 1], [0, 0, 0]] from 1 to 1 + 2",
    "maxflow [[0, 0, 0], [0, 0, 5], [0, 0, 0]] from 1 to 3",
    "maxflow [[0, 3, 0, 2, 0], [0, 0, 3, 0, 0], [0, 0, 0, 2, 0], [0, 0, 0, 0, 4], [0, 0, 0, 0, 0]] from 1 to 5",
]

# Sparse networks without an arc from the sink back to the source: the LP route is slow on
# dense instances, so it is only exercised on these fixed small cases.
SPARSE = [
    ([[0, 5, 4, 0], [0, 0, 3, 0], [0, 0, 0, 6], [0, 0, 0, 0]], 1, 4),
    ([[0, 3, 0, 0], [0, 0, 3, 0], [0, 0, 0, 2], [0, 0, 0, 0]], 1, 4),
    ([[0, 2, 2, 0], [0, 0, 0, 2], [0, 0, 0, 2], [0, 0, 0, 0]], 1, 4),
    ([[0, 4, 0, 0, 0], [0, 0, 3, 0, 0], [0, 0, 0, 3, 0], [0, 0, 0, 0, 2], [0, 0, 0, 0, 0]], 1, 5),
    ([[0, 1, 0], [7, 0, 5], [0, 0, 0]], 1, 3),
]


def _matrix(rows):
    return [[F(value) for value in row] for row in rows]


def _equivalence(query):
    return smt.check(query[0], query[1])[0]


def _random_network(rng, n):
    capacity = [[F(0)] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if i != j and rng.random() < 0.5:
                capacity[i][j] = F(rng.randint(0, 9))
    return capacity


# ---------------------------------------------------------------------------
# Language: both parsers agree, the printer round trips, the family is registered
# ---------------------------------------------------------------------------
def test_both_parsers_agree_on_flow_sentences_and_the_printer_round_trips():
    for text in SENTENCES:
        first = parse_a.parse_problem(text)
        second = parse_b.parse_problem(text)
        assert first == second, text
        assert first[0] == "maxflow"
        assert parse_a.parse_problem(to_math(first)) == first, text
        assert parse_b.parse_problem(to_math(first)) == first, text
        assert from_json(to_json(first)) == first, text


def test_the_flow_family_is_registered_for_the_new_kind():
    family = families.family_of("maxflow")
    assert family is not None and family.name == "maximum flow"
    assert "maxflow" in families.all_kinds()


def test_the_family_rejects_inputs_outside_the_fragment():
    family = families.family_of("maxflow")
    bad = [
        "maxflow [[0, 1], [1, 0]] from 1 to 3",                      # node number out of range
        "maxflow [[0, -1], [0, 0]] from 1 to 2",                     # negative capacity
        "maxflow [[1, 1], [0, 0]] from 1 to 2",                      # arc from a node to itself
        "maxflow [[0, 2], [0, 0]] from 2 to 2",                      # source and sink are equal
        "maxflow [[0, 2], [3, 0]] from x to 2",                      # terminal is not a number
        "maxflow [[0, 2]] from 1 to 2",                              # not a square matrix
        "maxflow [[0, 1, 0, 0, 0, 0, 0, 3], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], "
        "[0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], "
        "[0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0]] from 1 to 8",   # too many nodes
    ]
    for text in bad:
        tree = parse_a.parse_problem(text)
        with pytest.raises(MathError):
            family.check_fragment(tree)
    for text in ("maximize x subject to x <= 1", "det [[1, 2], [3, 4]]"):
        assert parse_a.parse_problem(text)[0] != "maxflow"


# ---------------------------------------------------------------------------
# The exact algorithm against a second, independent algorithm
# ---------------------------------------------------------------------------
def test_max_flow_matches_cut_enumeration_on_random_networks():
    rng = random.Random(20241116)
    for _ in range(120):
        n = rng.randint(2, 5)
        capacity = _random_network(rng, n)
        source, sink = 1, n
        own = flow.max_flow(capacity, source, sink)
        brute = flow.min_cut_by_enumeration(capacity, source, sink)
        assert own["status"] == "flow" and brute["status"] == "cut"
        assert own["value"] == brute["value"], (capacity, own["value"], brute["value"])
        assert flow.check_flow(capacity, source, sink, own["flow"]), capacity
        assert flow.check_cut(capacity, source, sink, own["cut"]), capacity
        assert flow.check_max_flow(capacity, source, sink, own["flow"], own["cut"]), capacity
        assert flow.flow_value(own["flow"], source) == own["value"]


def test_a_certificate_that_breaks_capacity_or_conservation_is_rejected():
    capacity = _matrix([[0, 5, 4, 0], [0, 0, 3, 0], [0, 0, 0, 6], [0, 0, 0, 0]])
    own = flow.max_flow(capacity, 1, 4)
    assert own["value"] == F(6)
    over = [row[:] for row in own["flow"]]
    over[0][1] = over[0][1] + 1                    # more than the capacity of the arc
    assert not flow.check_flow(capacity, 1, 4, over)
    assert not flow.check_max_flow(capacity, 1, 4, over, own["cut"])
    skewed = [row[:] for row in own["flow"]]
    skewed[0][2] = skewed[0][2] - 1                # node 3 loses one unit on the way through
    assert not flow.check_flow(capacity, 1, 4, skewed)
    missing = [node for node in own["cut"] if node != 3]
    assert not flow.check_cut(capacity, 1, 4, missing) or flow.cut_capacity(capacity, missing) != own["value"]


def test_the_cut_side_of_the_certificate_is_a_real_partition():
    capacity = _matrix([[0, 3, 0, 2, 0], [0, 0, 3, 0, 0], [0, 0, 0, 2, 0], [0, 0, 0, 0, 4], [0, 0, 0, 0, 0]])
    own = flow.max_flow(capacity, 1, 5)
    cut = own["cut"]
    assert 1 in cut and 5 not in cut
    assert len(set(cut)) == len(cut)
    across = sum(capacity[i - 1][j - 1] for i in cut for j in range(1, 6) if j not in cut)
    assert across == own["value"] == F(4)


# ---------------------------------------------------------------------------
# The LP route: the dual of the flow LP is the cut, checked with lp.py
# ---------------------------------------------------------------------------
def test_the_lp_route_agrees_and_its_dual_reads_out_the_cut():
    for rows, source, sink in SPARSE:
        capacity = _matrix(rows)
        own = flow.max_flow(capacity, source, sink)
        data = flow.as_lp(capacity, source, sink)
        outcome = lp.solve(data["A"], data["b"], data["c"])
        assert outcome["status"] == "optimal", (rows, outcome["status"])
        assert outcome["value"] == own["value"], (rows, outcome["value"], own["value"])
        assert lp.check_optimal(data["A"], data["b"], data["c"], outcome["point"], outcome["dual"], outcome["value"])
        rebuilt = flow.flow_of_lp(capacity, source, sink, data, outcome["point"])
        cut = flow.cut_of_dual(capacity, source, sink, data, outcome["dual"])
        assert flow.check_max_flow(capacity, source, sink, rebuilt, cut), rows
    with pytest.raises(flow.UnsupportedError):
        flow.as_lp(_matrix([[0, 1, 0], [0, 0, 1], [5, 0, 0]]), 1, 3)      # arc from the sink back


# ---------------------------------------------------------------------------
# The family through the seven node topology
# ---------------------------------------------------------------------------
def test_flow_solvers_agree_through_the_topology():
    family = families.family_of("maxflow")
    for text in SENTENCES:
        tree = parse_a.parse_problem(text)
        view_a, view_b = family.view_a(tree), family.view_b(tree)
        assert view_a["vars"] == view_b["vars"] and view_a["meta"] == view_b["meta"]
        assert view_a["terms"] and len(view_a["terms"]) == len(view_b["terms"])
        first = family.solve_z3(tree, view_a, text)[0]
        second = family.solve_exact(tree, view_b, text)[0]
        assert family.same(first, second), text
        final = pipeline.run(text)["final"]
        assert final["status"] == "VERIFIED", text
        assert final["answer"]["value"] == second["value"], text
        assert final["answer"]["flow"] == second["flow"] and final["answer"]["cut"] == second["cut"]


def test_the_two_views_of_the_same_network_are_equivalent_and_a_changed_one_is_not():
    family = families.family_of("maxflow")
    left = parse_a.parse_problem("maxflow [[0, 5, 4, 0], [0, 0, 3, 0], [0, 0, 0, 6], [0, 0, 0, 0]] from 1 to 4")
    right = parse_b.parse_problem("maxflow [[0, 5, 4, 0], [0, 0, 3, 0], [0, 0, 0, 6], [0, 0, 0, 0]] from 1 to 4")
    query = families.equiv_query(family.view_a(left), family.view_b(right))
    assert query is not None and _equivalence(query) == "unsat"
    other = parse_a.parse_problem("maxflow [[0, 5, 4, 0], [0, 0, 3, 0], [0, 0, 0, 7], [0, 0, 0, 0]] from 1 to 4")
    second = families.equiv_query(family.view_a(left), family.view_a(other))
    assert second is not None and _equivalence(second) == "sat"


def test_answer_and_certificates_are_checked_by_both_engines():
    family = ff.FlowFamily()
    text = "maxflow [[0, 5, 4, 0], [0, 0, 3, 0], [0, 0, 0, 6], [0, 0, 0, 0]] from 1 to 4"
    tree = parse_a.parse_problem(text)
    view = family.view_a(tree)
    answer = family.solve_exact(tree, view, text)[0]
    for config in ("default", "nlsat"):
        assert family.z3_confirm(tree, view, answer, config)[0] is True, config
    assert family.exact_confirm(tree, view, answer, text)[0] is True
    wrong = dict(answer, value=fmt_q(F(answer["value"]) + 1))
    assert family.z3_confirm(tree, view, wrong, "default")[0] is False
    assert family.exact_confirm(tree, view, wrong, text)[0] is False
    no_cut = dict(answer, cut=[])
    assert family.exact_confirm(tree, view, no_cut, text)[0] is False
    for config in ("default", "nlsat"):
        assert family.z3_confirm(tree, view, no_cut, config)[0] is False, config
    for side in ([2], [1, 4], [1, 9], ["a"], [1, 1]):
        claim = dict(answer, cut=side)
        assert family.z3_confirm(tree, view, claim, "default")[0] is False, side
        assert family.exact_confirm(tree, view, claim, text)[0] is False, side
    corrupt = [row[:] for row in answer["flow"]]
    corrupt[0][1] = fmt_q(F(corrupt[0][1]) + 1)
    broken = dict(answer, flow=corrupt)
    assert family.z3_confirm(tree, view, broken, "default")[0] is False
    assert family.exact_confirm(tree, view, broken, text)[0] is False
    other = dict(answer, status="infeasible")
    assert family.z3_confirm(tree, view, other, "default")[0] is False
    assert family.exact_confirm(tree, view, other, text)[0] is False


def test_every_side_of_the_network_is_judged_by_the_capacity_it_has():
    """A side that separates the terminals certifies the value only when its capacity is the value."""
    family = ff.FlowFamily()
    for text in SENTENCES[:3]:
        tree = parse_a.parse_problem(text)
        view = family.view_a(tree)
        answer = family.solve_exact(tree, view, text)[0]
        net = ff.network_of(tree)
        capacity, source, sink, n = net["capacity"], net["source"], net["sink"], net["n"]
        others = [node for node in range(1, n + 1) if node != sink]
        for size in range(1, n):
            for extra in combinations(others, size):
                if source not in extra:
                    continue
                claim = dict(answer, cut=sorted(extra))
                expected = flow.cut_capacity(capacity, extra) == F(answer["value"])
                for config in ("default", "nlsat"):
                    got = family.z3_confirm(tree, view, claim, config)[0]
                    assert got == expected, (text, extra, config, got)
                assert family.exact_confirm(tree, view, claim, text)[0] == expected, (text, extra)


def test_perturbations_and_the_gold_comparison_use_the_answer_shape():
    family = ff.FlowFamily()
    text = "maxflow [[0, 5, 4, 0], [0, 0, 3, 0], [0, 0, 0, 6], [0, 0, 0, 0]] from 1 to 4"
    tree = parse_a.parse_problem(text)
    answer = family.solve_exact(tree, family.view_a(tree), text)[0]
    bumped, changed = family.perturb(answer, "off_by_one")
    assert changed and F(bumped["value"]) == F(answer["value"]) + 1
    moved, changed = family.perturb(answer, "extra_solution")
    assert changed and moved["flow"] != answer["flow"]
    emptied, changed = family.perturb(answer, "drop_solution")
    assert changed and emptied["cut"] == []
    view = family.view_a(tree)
    widened, changed = family.perturb(answer, "closed_open")
    assert changed and widened["cut"] == [1, 2, 3, 4]
    assert family.z3_confirm(tree, view, widened, "default")[0] is False
    assert family.exact_confirm(tree, view, widened, text)[0] is False
    same, changed = family.perturb(answer, "flip_verdict")
    assert not changed and same == answer
    assert family.gold_equal(answer, {"status": "flow", "value": "6"})
    assert not family.gold_equal(answer, {"status": "flow", "value": "7"})
    assert family.gold_equal(answer, {"value": "6", "cut": [1, 2, 3]})
    assert "max flow 6" in family.render(answer)


def test_corpus_flow_rows_have_gold_from_the_exact_engine():
    rows = [item for item in corpus.load() if item["kind"] == "maxflow"]
    assert rows, "the corpus has no flow rows"
    for item in rows:
        tree = parse_a.parse_problem(item["text"])
        network = ff.network_of(tree)
        own = flow.max_flow(network["capacity"], network["source"], network["sink"])
        assert item["gold"]["status"] == "flow"
        assert item["gold"]["value"] == fmt_q(own["value"]), item["id"]