diff --git a/README.md b/README.md index 22c0ff6..784150d 100644 --- a/README.md +++ b/README.md @@ -406,7 +406,10 @@ and CQ11 choice-stage objections. pairs *uncertain*. Pairs over A × A are partitioned into `attacks`, `ignorance`, and `non_attacks`; reasoning is by enumerating *completions*. The module also provides three merge aggregations (`sum_merge_frameworks`, -`max_merge_frameworks`, `leximax_merge_frameworks`) and `consensual_expand`. +`max_merge_frameworks`, `leximax_merge_frameworks`) and +`consensual_expand(framework, profile)`. Expansion preserves the source's +commitments and imports uncontested attack and non-attack relations from the +profile; conflicting outside pairs remain uncertain. `argumentation.dynamics.af_revision` adds arguments and attacks to an existing framework, or revises an extension state by a formula or by a target diff --git a/agent-notes/fix-paper-code-corrections.md b/agent-notes/fix-paper-code-corrections.md new file mode 100644 index 0000000..da84705 --- /dev/null +++ b/agent-notes/fix-paper-code-corrections.md @@ -0,0 +1,31 @@ +# Paper-derived code corrections + +## Goal +Correct the five confirmed implementation mismatches identified after the visual paper-note audit. Make each correction its own commit, then publish the complete series as one PR. Q authorized this on 2026-10-19; the earlier "make it so" remains in the session. Leave the PR open for review; do not merge it under the earlier notes-only integration instruction. + +## State +Branch `fix/paper-code-corrections` starts at origin/main `1e1029e5539c3783dcabca95b0e958761867814a` in `C:/Users/Q/code/argumentation-paper-code-corrections`. All five scoped corrections are implemented and checked against the original paper page images. Four separate commits already exist: `6a2a33a` (impact), `d308240` (distance), `152277f` (expansion), and `4682283` (classification). The fifth commit contains transposition closure and this record update. No local tests, typecheck, build, or other CI steps have run. Publication and hosted CI are next. Preserve the primary checkout's uncommitted audit record and all unrelated artifacts. The failed old temporary-directory cleanup is outside this task. + +## Decisions and why +- Smallest change: fix the existing functions and the existing assertions/generators that encode their incorrect contracts. Roughly 100-180 production lines and comparable or fewer test/doc lines across five commits; no new public framework, flags, compatibility facade, solver optimization, or new guards. +- Commit 1: revised impact removes external attacks entering X, and target-preserving node deletion removes edges touching all of X. Correct existing self-attack expectations. About 20-35 production lines. +- Commit 2: PAF edit distance charges 0/0.5/1 per Definition 18; update objective annotations and existing expectations. About 10-20 production lines. +- Commit 3: consensual expansion receives the profile, imports uncontested outside relations, and is used by the existing merge operators. Update all current callers/docs and assertions. About 35-65 production lines. +- Commit 4: classify Cayrol extension-family changes using the paper's cardinalities, quantifiers, and decisive precedence. Correct existing mistaken tests. About 15-30 production lines. +- Commit 5: transposition closure retains all seed strict rules and generated transpositions; remove unsupported pruning and revise existing generator restrictions. About 10-25 production lines removed/changed. +- Paper evidence is exclusively original page images in the primary checkout. No extraction, OCR, or extracted-paper-text navigation. No local CI steps; use hosted PR CI. No new tests/guards; correct existing tests where they encode a wrong contract. +- Workers own disjoint source/test/doc paths and do not commit. The primary stages only each correction's owned paths and commits them separately. PAF distance and expansion share files and therefore run sequentially. +- Consensual expansion now takes the full profile as its second argument; all repository callers and API documentation were updated. Passing only a universe cannot determine the paper's consensual relations. +- The closure correction removes unsupported pruning rather than adding machinery. Its existing nontrivial-argument property now excludes a rule whose consequent is already an antecedent, matching the argument builder's existing restriction to non-repeating conclusion paths. Changing argument enumeration is outside these five corrections. + +## Source evidence +- AlAnaissy 2024 original images 001,003-004: external incoming attacks, node/edge deletion, self-attack example. +- Coste-Marquis 2007 original images 006-010: generic versus consensual expansion, Example 14, edit distance. +- Cayrol (local 2014 directory, actual 2010 publication) original images 006,008-011,016: structural classifications and examples. +- Prakken 2010 original image 012: Definitions 5.1-5.3, extensive closure under every transposition. + +## Surprises +The existing tests asserted positive self-impact and whole-unit ignorance distance, accepted expansive classification with unequal family counts, and excluded valid transpositions. Those expectations and generator restrictions are corrected alongside the implementation. The argument builder still restricts repeated conclusions; this series does not claim to settle broader argument-enumeration completeness. + +## Next step +Commit closure as the fifth correction, then push and open one combined PR for hosted validation on its exact head. Leave the PR open. Stop and report any execution/check failure under the standing instructions. diff --git a/docs/af-revision.md b/docs/af-revision.md index 76caeca..546db00 100644 --- a/docs/af-revision.md +++ b/docs/af-revision.md @@ -22,6 +22,9 @@ minimal faithful candidates. classifies the effect of adding an argument under grounded semantics using the WS-B taxonomy values in `AFChangeKind`: decisive, restrictive, questioning, destructive, expansive, conservative, and altering. +The classifier uses the paper's extension-family counts: an empty grounded +extension becoming nonempty is decisive. Expansive change requires equal +counts and every new extension strictly containing an old extension. ## Gates diff --git a/docs/argumentation-package-boundary.md b/docs/argumentation-package-boundary.md index a8cf1be..7df7b84 100644 --- a/docs/argumentation-package-boundary.md +++ b/docs/argumentation-package-boundary.md @@ -115,7 +115,9 @@ wrappers live in `argumentation.solver`; CEL authoring, `ConditionIR`, and mapping-like claim metadata. `argumentation.partial_af` owns partial-framework completion enumeration, -completion queries, exact edit-distance merge operators, and `consensual_expand`. +completion queries, exact edit-distance merge operators, and +`consensual_expand(framework, profile)`, which preserves source commitments and +imports uncontested profile relations, leaving conflicting outside pairs ignorant. `argumentation.af_revision` owns AF-level revision and accepts formula-like extension constraints through an argumentation-owned protocol. Propstore diff --git a/docs/structured-argumentation.md b/docs/structured-argumentation.md index 60cdb87..b7526a6 100644 --- a/docs/structured-argumentation.md +++ b/docs/structured-argumentation.md @@ -170,11 +170,11 @@ Compare both `Prem_p` (ordinary premises) and `DefRules` (all defeasible rules) Transposition closure (Def 12, p.13; Prakken 2010 Def 5.1) ensures that strict rules interact correctly with contrariness. For each strict rule `A1, ..., An -> C` and each antecedent index `i`, a transposed rule is generated: `A1, ..., ~C, ..., An -> ~Ai`. This process repeats until a fixpoint is reached. -**Degenerate rule filtering**: transposed rules with contradictory antecedent pairs are discarded (they reference Thm 14, direct consistency). After the fixpoint, an axiom consistency check verifies that no literal's strict closure contains its own contrary. +Prakken 2010 Definition 5.2 requires the closure to contain every input rule and every transposition. Rules with contradictory antecedents, and rules whose consequent also occurs among their antecedents, are retained. Consistency requirements for a particular knowledge base are separate from this rule-set closure. Transposition closure is required for the rationality postulates (Thms 12-15) to hold. Without it, the framework can produce inconsistent extensions — arguments that are jointly accepted but whose conclusions contradict each other under strict rules. -`argumentation/src/argumentation/aspic.py:247` — `transposition_closure()` +`src/argumentation/structured/aspic/aspic.py` — `transposition_closure()` ## Rationality Postulates diff --git a/src/argumentation/dynamics/af_revision.py b/src/argumentation/dynamics/af_revision.py index bd3e0ee..6e9caae 100644 --- a/src/argumentation/dynamics/af_revision.py +++ b/src/argumentation/dynamics/af_revision.py @@ -383,9 +383,11 @@ def _classify_extension_change( ) -> AFChangeKind: """Classify structural extension change after an AF update. - Cayrol, de Saint-Cyr, and Lagasquie-Schiex 2010, JAIR 38, Table 3 - distinguishes seven extension-family changes by content relations between - the old and new extension families, not by cardinality alone. + Cayrol, de Saint-Cyr, and Lagasquie-Schiex 2010, JAIR 38, Definitions + 8-14 and Table 2 distinguish changes in the number of extensions first. + Expansive change preserves that number, and every new extension must + strictly contain an old one. A transition from the empty grounded + extension to one nonempty extension is decisive. """ before_set = frozenset(frozenset(extension) for extension in before) after_set = frozenset(frozenset(extension) for extension in after) @@ -394,24 +396,16 @@ def _classify_extension_change( return AFChangeKind.CONSERVATIVE if not after_set or after_set == empty_family: return AFChangeKind.DESTRUCTIVE - if ( - before_set - and after_set - and all(any(old < new for new in after_set) for old in before_set) + if len(after_set) == 1 and ( + len(before_set) >= 2 or before_set in {frozenset(), empty_family} ): - return AFChangeKind.EXPANSIVE - if len(after_set) == 1: - survivor = next(iter(after_set)) - if survivor in before_set or before_set in {frozenset(), empty_family}: - return AFChangeKind.DECISIVE + return AFChangeKind.DECISIVE if len(before_set) < len(after_set): return AFChangeKind.QUESTIONING - if ( - before_set - and after_set - and all(any(new <= old for old in before_set) for new in after_set) - ): + if len(after_set) < len(before_set): return AFChangeKind.RESTRICTIVE + if all(any(old < new for old in before_set) for new in after_set): + return AFChangeKind.EXPANSIVE return AFChangeKind.ALTERING diff --git a/src/argumentation/frameworks/af_merging.py b/src/argumentation/frameworks/af_merging.py index 901e56e..8f62fda 100644 --- a/src/argumentation/frameworks/af_merging.py +++ b/src/argumentation/frameworks/af_merging.py @@ -48,10 +48,9 @@ def _candidate_frameworks( def _expanded_profile( profile: dict[str, ArgumentationFramework], - universe: frozenset[str], ) -> dict[str, PartialArgumentationFramework]: return { - source: consensual_expand(framework, universe) + source: consensual_expand(framework, profile) for source, framework in profile.items() } @@ -112,7 +111,7 @@ def sum_merge_frameworks( ) -> list[ArgumentationFramework] | EnumerationExceeded: """Return exact Sum-minimizing AFs over the shared argument universe.""" universe = _shared_universe(profile) - expanded = _expanded_profile(profile, universe) + expanded = _expanded_profile(profile) strict_bipartition_winners = _strict_bipartition_sum_merge(universe, expanded) if strict_bipartition_winners is not None: return strict_bipartition_winners @@ -121,7 +120,7 @@ def sum_merge_frameworks( if isinstance(candidates, EnumerationExceeded): return candidates - best_score: int | None = None + best_score: float | None = None winners: list[ArgumentationFramework] = [] for candidate in candidates: score = sum( @@ -143,12 +142,12 @@ def max_merge_frameworks( ) -> list[ArgumentationFramework] | EnumerationExceeded: """Return exact Max-minimizing AFs over the shared argument universe.""" universe = _shared_universe(profile) - expanded = _expanded_profile(profile, universe) + expanded = _expanded_profile(profile) candidates = _candidate_frameworks(universe, max_candidates=max_candidates) if isinstance(candidates, EnumerationExceeded): return candidates - best_score: int | None = None + best_score: float | None = None winners: list[ArgumentationFramework] = [] for candidate in candidates: score = max( @@ -170,12 +169,12 @@ def leximax_merge_frameworks( ) -> list[ArgumentationFramework] | EnumerationExceeded: """Return exact Leximax-minimizing AFs over the shared argument universe.""" universe = _shared_universe(profile) - expanded = _expanded_profile(profile, universe) + expanded = _expanded_profile(profile) max_winners = max_merge_frameworks(profile, max_candidates=max_candidates) if isinstance(max_winners, EnumerationExceeded): return max_winners - best_vector: tuple[int, ...] | None = None + best_vector: tuple[float, ...] | None = None winners: list[ArgumentationFramework] = [] for candidate in max_winners: vector = tuple( diff --git a/src/argumentation/frameworks/partial_af.py b/src/argumentation/frameworks/partial_af.py index 2647a7c..7ed7751 100644 --- a/src/argumentation/frameworks/partial_af.py +++ b/src/argumentation/frameworks/partial_af.py @@ -1,8 +1,9 @@ """Partial argumentation frameworks and completion-based queries.""" -from __future__ import annotations - -from dataclasses import dataclass +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass from enum import StrEnum from itertools import combinations, product from typing import TypeAlias, cast @@ -140,22 +141,31 @@ def _coerce_partial_framework( raise TypeError(f"Unsupported framework type: {type(framework)!r}") -def merge_framework_edit_distance( - left: FrameworkLike, - right: FrameworkLike, -) -> int: - """Hamming distance over pair labels on a shared argument universe.""" +def merge_framework_edit_distance( + left: FrameworkLike, + right: FrameworkLike, +) -> float: + """Coste-Marquis et al. 2007, Definition 18 edit distance over pair labels. + + Equal labels cost zero, ignorance versus a definite label costs 0.5, + and attack versus non-attack costs one on the shared argument universe. + """ left_framework = _coerce_partial_framework(left) right_framework = _coerce_partial_framework(right) if left_framework.arguments != right_framework.arguments: raise ValueError("merge_framework_edit_distance requires identical arguments") - return sum( - 1 - for pair in left_framework.ordered_pairs - if left_framework.state_of(pair) != right_framework.state_of(pair) - ) + return sum( + ( + 0.5 + if pair in left_framework.ignorance or pair in right_framework.ignorance + else 1.0 + for pair in left_framework.ordered_pairs + if left_framework.state_of(pair) != right_framework.state_of(pair) + ), + 0.0, + ) _COMPLETION_SEMANTICS: frozenset[str] = frozenset({"grounded", "preferred", "stable"}) @@ -207,38 +217,40 @@ def _attack_relation(framework: ArgumentationFramework) -> frozenset[AttackPair] return framework.attacks if framework.attacks is not None else framework.defeats -def consensual_expand( - framework: ArgumentationFramework, - universe: frozenset[str], -) -> PartialArgumentationFramework: - """Expand an AF to a shared universe using ignorance outside source scope. - - Coste-Marquis et al. 2007, Def. 11 takes the universe as the union of the - profile's argument sets, so it must contain the source arguments. - """ - source_arguments = frozenset(framework.arguments) - missing = source_arguments - universe - if missing: - raise ValueError( - f"universe must contain every source argument; missing {sorted(missing)!r}" - ) - attack_relation = _attack_relation(framework) - attacks: set[AttackPair] = set() - ignorance: set[AttackPair] = set() - non_attacks: set[AttackPair] = set() - - for pair in product(universe, universe): - attacker, target = pair - if attacker in source_arguments and target in source_arguments: - if pair in attack_relation: - attacks.add(pair) - else: - non_attacks.add(pair) - else: - ignorance.add(pair) - - return PartialArgumentationFramework( - arguments=universe, +def consensual_expand( + framework: ArgumentationFramework, + profile: Mapping[str, ArgumentationFramework], +) -> PartialArgumentationFramework: + """Expand an AF using the profile's uncontested attack commitments. + + Coste-Marquis et al. 2007, Definition 12 preserves the source's attacks + and non-attacks, imports uncontested relations outside its scope, and + leaves only conflicting outside pairs ignorant. Pairs known to no source + become non-attacks. The universe includes the source and every profile AF. + """ + source_arguments = frozenset(framework.arguments) + universe = set(source_arguments) + profile_attacks: set[AttackPair] = set() + profile_non_attacks: set[AttackPair] = set() + for source in profile.values(): + universe.update(source.arguments) + relation = _attack_relation(source) + profile_attacks.update(relation) + profile_non_attacks.update( + set(product(source.arguments, source.arguments)) - relation + ) + + source_attacks = _attack_relation(framework) + source_non_attacks = ( + set(product(source_arguments, source_arguments)) - source_attacks + ) + conflicts = profile_attacks & profile_non_attacks + attacks = source_attacks | ((profile_attacks - conflicts) - source_non_attacks) + ignorance = conflicts - (source_attacks | source_non_attacks) + non_attacks = set(product(universe, universe)) - (attacks | ignorance) + + return PartialArgumentationFramework( + arguments=frozenset(universe), attacks=frozenset(attacks), ignorance=frozenset(ignorance), non_attacks=frozenset(non_attacks), diff --git a/src/argumentation/gradual/gradual.py b/src/argumentation/gradual/gradual.py index 52603cd..76d4b58 100644 --- a/src/argumentation/gradual/gradual.py +++ b/src/argumentation/gradual/gradual.py @@ -294,10 +294,10 @@ def revised_direct_impact( ) -> RevisedImpactResult: """Compute the revised removal-based impact of ``influencers`` on ``target``. - Al Anaissy et al. 2024, Definition 12: remove direct attacks from the - influencer set to the target, and compare against target-preserving argument - deletion. The latter keeps ``target`` when it is also in ``influencers``, - which makes self-attack attribution defined. + Al Anaissy et al. 2024, Definitions 10 and 12: first remove external + attacks entering the influencer set, then compare against deletion of that + set. Argument deletion retains ``target`` but removes relations incident + on any influencer, isolating the target when it is an influencer itself. """ normalized_influencers = frozenset(str(argument) for argument in influencers) target = str(target) @@ -315,7 +315,7 @@ def revised_direct_impact( removed_attacks = frozenset( (source, attacked) for source, attacked in graph.attacks - if source in normalized_influencers and attacked == target + if source not in normalized_influencers and attacked in normalized_influencers ) attack_removed = _without_attacks(graph, removed_attacks) after_attack_removal = quadratic_energy_strengths( @@ -330,7 +330,7 @@ def revised_direct_impact( ) removed_arguments = normalized_influencers - {target} - argument_removed = _without_arguments(graph, removed_arguments) + argument_removed = _without_arguments(graph, normalized_influencers, target=target) after_argument_removal = quadratic_energy_strengths( argument_removed, tolerance=tolerance, @@ -458,8 +458,10 @@ def _without_attacks( def _without_arguments( graph: WeightedBipolarGraph, removed_arguments: frozenset[str], + *, + target: str, ) -> WeightedBipolarGraph: - remaining = graph.arguments - removed_arguments + remaining = graph.arguments - (removed_arguments - {target}) return WeightedBipolarGraph( arguments=remaining, initial_weights={ @@ -468,11 +470,11 @@ def _without_arguments( attacks=frozenset( (source, target) for source, target in graph.attacks - if source in remaining and target in remaining + if source not in removed_arguments and target not in removed_arguments ), supports=frozenset( (source, target) for source, target in graph.supports - if source in remaining and target in remaining + if source not in removed_arguments and target not in removed_arguments ), ) diff --git a/src/argumentation/structured/aspic/aspic.py b/src/argumentation/structured/aspic/aspic.py index 0fa49cc..6506396 100644 --- a/src/argumentation/structured/aspic/aspic.py +++ b/src/argumentation/structured/aspic/aspic.py @@ -394,30 +394,6 @@ class ArgumentationSystem: defeasible_rules: frozenset[Rule] -def _is_degenerate_rule(rule: Rule, contrariness: ContrarinessFn) -> bool: - """Check if a strict rule is degenerate and should be excluded. - - A rule is degenerate if it has a contradictory pair among its - antecedents (both φ and ~φ). Such rules can only fire when - contradictory information is already present, and their - transpositions produce ill-formed rules. - - Modgil & Prakken 2018, Def 12 (p.13): transposition closure requires - well-formed rules. Rules with contradictory antecedent pairs cannot - be properly closed under transposition. - - Note: rules where an antecedent is the contrary of the consequent - (e.g., ~r, p -> ~p) are NOT degenerate — they are valid transpositions - needed for the rationality postulates (Thm 14, p.18: direct consistency). - """ - antes = rule.antecedents - for i, left in enumerate(antes): - for right in antes[i + 1 :]: - if contrariness.is_contradictory(left, right): - return True - return False - - def _contradictories_of( literal: Literal, language: frozenset[Literal], @@ -466,11 +442,11 @@ def transposition_closure( (Def 12 applies to R_s only). The fixpoint always terminates because L is finite, bounding the number of possible rules. - Rules with contradictory antecedent pairs (both φ and ~φ) are excluded: - they are degenerate (ex falso quodlibet) and their transpositions - produce rules where the consequent appears in the antecedents, - violating well-formedness. Similarly, any generated transposition - whose consequent appears in its own antecedents is excluded. + Every input rule is retained, including rules with contradictory + antecedents or with their consequent among their antecedents. Every + transposition is added without either restriction: Definition 5.2 + requires the closure to contain the original rules and all their + transpositions. Prakken 2010, Defs. 5.1-5.3 (pp. 141-142; local page image ``papers/Prakken_2010_AbstractFrameworkArgumentationStructured/pngs/page-012.png``) @@ -486,8 +462,8 @@ def transposition_closure( Returns: A pair ``(closed_rules, post_closure_language)`` where - ``closed_rules`` is the smallest frozenset of well-formed Rules - closed under transposition, containing all well-formed input rules, + ``closed_rules`` is the smallest frozenset of Rules + closed under transposition, containing all input rules, and ``post_closure_language`` contains the input language plus every literal appearing in the closed rules. @@ -495,8 +471,7 @@ def transposition_closure( ValueError: if a strict-rule literal has no contradictory partner in the supplied contrariness relation. """ - # Filter out degenerate seed rules with contradictory antecedent pairs. - closed: set[Rule] = {r for r in rules if not _is_degenerate_rule(r, contrariness)} + closed: set[Rule] = set(rules) changed = True while changed: changed = False @@ -520,16 +495,12 @@ def transposition_closure( continue if any(a not in language for a in transposed_antes): continue - if transposed_consequent in transposed_antes: - continue new_rule = Rule( antecedents=tuple(transposed_antes), consequent=transposed_consequent, kind="strict", name=None, ) - if _is_degenerate_rule(new_rule, contrariness): - continue if new_rule not in closed: new_rules.add(new_rule) changed = True diff --git a/tests/dynamics/test_af_revision.py b/tests/dynamics/test_af_revision.py index 26ea2b7..88c6be7 100644 --- a/tests/dynamics/test_af_revision.py +++ b/tests/dynamics/test_af_revision.py @@ -257,20 +257,24 @@ def test_cayrol_2010_questioning_classification_for_more_extensions() -> None: assert _classify_extension_change(before, after) == AFChangeKind.QUESTIONING -def test_ws_o_arg_cayrol_2010_decisive_uses_surviving_extension_content() -> None: - """Bug 4: a two-extension family collapsing to one old extension is decisive.""" - before = (frozenset({"a"}), frozenset({"b"})) - after = (frozenset({"a"}),) - - assert _classify_extension_change(before, after) == AFChangeKind.DECISIVE - - -def test_ws_o_arg_cayrol_2010_expansive_does_not_require_equal_cardinality() -> None: - """Bug 4: expansive is content-based, not equal-cardinality-based.""" +def test_cayrol_2010_grounded_addition_is_decisive_from_empty() -> None: + """Example 2.1 (p.55): adding Z->A to the cycle yields {Z,B}.""" + framework = ArgumentationFramework( + arguments=frozenset({"a", "b", "c"}), + defeats=frozenset({("a", "b"), ("b", "c"), ("c", "a")}), + ) + + assert cayrol_2014_classify_grounded_argument_addition( + framework, "z", frozenset({("z", "a")}) + ) == AFChangeKind.DECISIVE + + +def test_cayrol_2010_increasing_extension_count_is_questioning() -> None: + """Definition 12 requires equal counts for expansive change.""" before = (frozenset({"a"}),) after = (frozenset({"a", "b"}), frozenset({"a", "c"})) - assert _classify_extension_change(before, after) == AFChangeKind.EXPANSIVE + assert _classify_extension_change(before, after) == AFChangeKind.QUESTIONING def test_ws_o_arg_extension_revision_state_accepts_lazy_ranking() -> None: diff --git a/tests/frameworks/test_partial_af.py b/tests/frameworks/test_partial_af.py index 4420741..06f6a52 100644 --- a/tests/frameworks/test_partial_af.py +++ b/tests/frameworks/test_partial_af.py @@ -107,8 +107,8 @@ def test_merge_framework_edit_distance_is_identity_and_symmetric(): ) assert merge_framework_edit_distance(left, left) == 0 - assert merge_framework_edit_distance(left, right) == 1 - assert merge_framework_edit_distance(right, left) == 1 + assert merge_framework_edit_distance(left, right) == 0.5 + assert merge_framework_edit_distance(right, left) == 0.5 def test_merge_framework_edit_distance_satisfies_triangle_inequality(): diff --git a/tests/frameworks/test_partial_af_merge.py b/tests/frameworks/test_partial_af_merge.py index 3b30db3..3932afd 100644 --- a/tests/frameworks/test_partial_af_merge.py +++ b/tests/frameworks/test_partial_af_merge.py @@ -4,8 +4,7 @@ from itertools import product -import pytest -from hypothesis import HealthCheck, given, settings +from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st from argumentation.core.dung import ArgumentationFramework @@ -37,35 +36,52 @@ def _af(arguments: set[str], attacks: set[tuple[str, str]]) -> ArgumentationFram ) -def test_consensual_expand_preserves_in_scope_pairs_and_marks_out_of_scope_as_ignorance(): - af = _af({"A"}, {("A", "A")}) - - expanded = consensual_expand(af, frozenset({"A", "B"})) - - assert ("A", "A") in expanded.attacks - assert ("A", "B") in expanded.ignorance - assert ("B", "A") in expanded.ignorance - assert ("B", "B") in expanded.ignorance - - -def test_consensual_expand_rejects_universe_missing_source_arguments(): - """Coste-Marquis et al. 2007, Def. 11 (p.6-7): the expansion universe is - ``A = union A_i``, so every source argument set ``A_i`` is contained in it. - A smaller universe must not silently drop ``B`` and its attack.""" - af = _af({"A", "B"}, {("A", "B")}) - - with pytest.raises(ValueError, match="universe"): - consensual_expand(af, frozenset({"A"})) - - -def test_consensual_expand_to_superset_universe_keeps_source_arguments(): - """Control: a universe containing ``A_i`` keeps every source argument.""" - af = _af({"A", "B"}, {("A", "B")}) - - expanded = consensual_expand(af, frozenset({"A", "B", "C"})) - - assert af.arguments <= expanded.arguments - assert expanded.attacks == frozenset({("A", "B")}) +def test_consensual_expand_matches_example_14_first_source(): + """Coste-Marquis et al. 2007, pp. 737–738: AF1 imports b->c and c->d.""" + profile = { + "AF1": _af({"a", "b"}, {("a", "b"), ("b", "a")}), + "AF2": _af({"b", "c", "d"}, {("b", "c"), ("c", "d")}), + "AF3": _af({"a", "b", "d"}, {("a", "b"), ("a", "d")}), + "AF4": _af({"a", "b", "d"}, {("b", "d"), ("b", "a")}), + } + + expanded = consensual_expand(profile["AF1"], profile) + + assert expanded.arguments == frozenset({"a", "b", "c", "d"}) + assert expanded.attacks == frozenset( + {("a", "b"), ("b", "a"), ("b", "c"), ("c", "d")} + ) + assert expanded.ignorance == frozenset({("a", "d"), ("b", "d")}) + assert ("a", "c") in expanded.non_attacks # No agent knows both endpoints. + + +def test_consensual_expand_retains_source_scope_outside_profile(): + """Definition 12 uses A union union(A_i), preserving a source outside P.""" + af = _af({"A", "B"}, {("A", "B")}) + profile = {"other": _af({"C"}, {("C", "C")})} + + expanded = consensual_expand(af, profile) + + assert expanded.arguments == frozenset({"A", "B", "C"}) + assert expanded.attacks == frozenset({("A", "B"), ("C", "C")}) + assert expanded.ignorance == frozenset() + assert {("A", "A"), ("B", "A"), ("B", "B"), ("A", "C")} <= expanded.non_attacks + + +def test_consensual_expand_keeps_conflicting_outside_pairs_ignorant(): + """Example 14's AF2 retains b->c/c->d and is ignorant about a->b/b->a/a->d.""" + profile = { + "AF1": _af({"a", "b"}, {("a", "b"), ("b", "a")}), + "AF2": _af({"b", "c", "d"}, {("b", "c"), ("c", "d")}), + "AF3": _af({"a", "b", "d"}, {("a", "b"), ("a", "d")}), + "AF4": _af({"a", "b", "d"}, {("b", "d"), ("b", "a")}), + } + + expanded = consensual_expand(profile["AF2"], profile) + + assert expanded.attacks == frozenset({("b", "c"), ("c", "d")}) + assert expanded.ignorance == frozenset({("a", "b"), ("b", "a"), ("a", "d")}) + assert ("b", "d") in expanded.non_attacks # AF2's own non-attack is preserved. def test_edit_distance_to_own_expansion_uses_pre_preference_attacks(): @@ -78,7 +94,7 @@ def test_edit_distance_to_own_expansion_uses_pre_preference_attacks(): attacks=frozenset({("A", "B")}), ) - expanded = consensual_expand(af, af.arguments) + expanded = consensual_expand(af, {"source": af}) assert merge_framework_edit_distance(af, expanded) == 0 @@ -89,14 +105,16 @@ def test_edit_distance_counts_attack_versus_non_attack_pairs(): right = _af({"A", "B"}, set()) assert merge_framework_edit_distance(left, right) == 1 - expanded = consensual_expand(left, left.arguments) + expanded = consensual_expand(left, {"source": left}) assert merge_framework_edit_distance(left, expanded) == 0 def test_consensual_expand_on_shared_universe_introduces_no_ignorance(): af = _af({"A", "B"}, {("A", "B")}) - expanded = consensual_expand(af, frozenset({"A", "B"})) + expanded = consensual_expand( + af, {"source": af, "contrary": _af({"A", "B"}, set())} + ) assert expanded.ignorance == frozenset() assert expanded.attacks == frozenset({("A", "B")}) diff --git a/tests/gradual/test_gradual.py b/tests/gradual/test_gradual.py index 1caf429..654c14b 100644 --- a/tests/gradual/test_gradual.py +++ b/tests/gradual/test_gradual.py @@ -96,11 +96,11 @@ def test_revised_direct_impact_handles_self_attack() -> None: impact = revised_direct_impact(graph, influencers=frozenset({"a"}), target="a") - assert impact.removed_attacks == frozenset({("a", "a")}) + assert impact.removed_attacks == frozenset() assert impact.removed_arguments == frozenset() - assert impact.after_argument_removal_strength == pytest.approx(0.4238537989) - assert impact.after_attack_removal_strength == pytest.approx(0.5) - assert impact.impact == pytest.approx(0.0761462011) + assert impact.after_argument_removal_strength == pytest.approx(0.5) + assert impact.after_attack_removal_strength == pytest.approx(0.4238537989) + assert impact.impact == pytest.approx(-0.0761462011) def test_revised_direct_impact_is_zero_for_unrelated_argument() -> None: diff --git a/tests/structured/aspic/test_aspic.py b/tests/structured/aspic/test_aspic.py index 69b0868..6ee3c5a 100644 --- a/tests/structured/aspic/test_aspic.py +++ b/tests/structured/aspic/test_aspic.py @@ -336,10 +336,9 @@ def strict_rules(draw, language, contrariness, max_rules=4): Prakken 2010, Defs 3.4, 5.1-5.2 (pp.47-48, 141-142). 1. Draw 0-max_rules seed rules with 1-2 antecedents from L, consequent from L. - 2. Filter: consequent not in antecedents. - 3. Compute transposition closure (calls transposition_closure which does not - exist yet -- tests will fail with ImportError in red phase). - 4. Return the closed rule set. + 2. Compute transposition closure without excluding contradictory bodies + or rules whose consequent also appears in their antecedents. + 3. Return the closed rule set. """ L_list = sorted(language, key=repr) n_rules = draw(st.integers(min_value=0, max_value=max_rules)) @@ -348,10 +347,7 @@ def strict_rules(draw, language, contrariness, max_rules=4): n_ante = draw(st.integers(min_value=1, max_value=min(2, len(L_list)))) antecedents = _distinct_antecedents(draw, L_list, n_ante) consequent = draw(st.sampled_from(L_list)) - # Filter: consequent must not appear in antecedents - if consequent in antecedents: - continue - seed_rules.append( + seed_rules.append( Rule( antecedents=antecedents, consequent=consequent, @@ -369,7 +365,7 @@ def strict_rules(draw, language, contrariness, max_rules=4): @st.composite def strict_seed_rules(draw, language, contrariness, max_rules=4): - """Generate well-formed strict seed rules before transposition closure.""" + """Generate strict seed rules over L before transposition closure.""" L_list = sorted(language, key=repr) n_rules = draw(st.integers(min_value=0, max_value=max_rules)) seed_rules: list[Rule] = [] @@ -377,15 +373,7 @@ def strict_seed_rules(draw, language, contrariness, max_rules=4): n_ante = draw(st.integers(min_value=1, max_value=min(2, len(L_list)))) antecedents = _distinct_antecedents(draw, L_list, n_ante) consequent = draw(st.sampled_from(L_list)) - if consequent in antecedents: - continue - if any( - contrariness.is_contradictory(left, right) - for index, left in enumerate(antecedents) - for right in antecedents[index + 1 :] - ): - continue - seed_rules.append( + seed_rules.append( Rule( antecedents=antecedents, consequent=consequent, @@ -434,21 +422,13 @@ def _schema_transpositions( ): transposed_antecedents = list(rule.antecedents) transposed_antecedents[index] = contrary_consequent - if contrary_antecedent in transposed_antecedents: - continue - candidate = Rule( + candidate = Rule( antecedents=tuple(transposed_antecedents), consequent=contrary_antecedent, kind="strict", name=None, ) - if any( - contrariness.is_contradictory(left, right) - for left_index, left in enumerate(candidate.antecedents) - for right in candidate.antecedents[left_index + 1 :] - ): - continue - transpositions.add(candidate) + transpositions.add(candidate) return frozenset(transpositions) @@ -577,31 +557,8 @@ def test_rule_antecedents_in_language(self, lc_sr_dr): assert ante in L, f"Antecedent {ante} of rule {r} not in L" assert r.consequent in L, f"Consequent {r.consequent} of rule {r} not in L" - @given( - logical_language().flatmap( - lambda lc: st.tuples( - st.just(lc), - strict_rules(language=lc[0], contrariness=lc[1]), - defeasible_rules(language=lc[0]), - ) - ) - ) - @settings(deadline=None) - def test_consequent_not_in_antecedents(self, lc_sr_dr): - """No rule has its consequent appearing in its antecedents. - - A rule phi_1, ..., phi_n -> psi must have psi not in {phi_1, ..., phi_n}. - This is a well-formedness constraint: a rule cannot trivially conclude - one of its own premises. - """ - (L, _cfn), s_rules, d_rules = lc_sr_dr - for r in s_rules | d_rules: - assert r.consequent not in r.antecedents, ( - f"Rule {r} has consequent {r.consequent} in antecedents" - ) - - -class TestTranspositionClosure: + +class TestTranspositionClosure: """Property tests for transposition closure of strict rules. Modgil & Prakken 2018, Def 12 (p.13): if A1,...,An -> C is a strict @@ -624,9 +581,7 @@ class TestTranspositionClosure: ) ) @settings(deadline=None) - def test_transposition_closure_is_extensive_for_well_formed_seed_rules( - self, lc_rules - ): + def test_transposition_closure_is_extensive_for_seed_rules(self, lc_rules): """Seed strict rules are retained by closure. Grounded in @@ -1279,8 +1234,11 @@ def test_nontriviality(self, data): This is the non-triviality guarantee from the knowledge_base strategy: it forces at least one rule's antecedents into K_p, - ensuring build_arguments produces compound arguments when a - c-consistent rule antecedent set is available. + ensuring build_arguments produces compound arguments when a + c-consistent antecedent set is available for a rule whose conclusion + is not already among its antecedents. This matches the builder's + existing restriction to non-repeating conclusion paths; the rule-set + closure itself also retains tautological rules. See reports/hypothesis-aspic-feasibility.md Section 3, Level 4. """ L, cfn = data.draw(logical_language()) @@ -1293,8 +1251,9 @@ def test_nontriviality(self, data): arguments = build_arguments(system, kb) assume( any( - frozenset(rule.antecedents) <= (kb.axioms | kb.premises) - and is_c_consistent( + rule.consequent not in rule.antecedents + and frozenset(rule.antecedents) <= (kb.axioms | kb.premises) + and is_c_consistent( frozenset(rule.antecedents), system.strict_rules, system.contrariness,