File size: 5,893 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""CLEVR-specific immutable object-attribute interventions."""

from __future__ import annotations

import copy
from dataclasses import dataclass
from typing import Literal

from ..hashing import canonical_json_hash
from ..sources.base import World
from ..sources.world_ops import NODE_VISIBILITY_KEY, world_sha256
from .base import InterventionError

ClevrAttribute = Literal["color", "material", "shape", "size"]
ClevrMutationKind = Literal["CONTROL", "SUBSTITUTE", "MISSING"]

ATTRIBUTE_DOMAINS: dict[ClevrAttribute, tuple[str, ...]] = {
    "color": ("blue", "brown", "cyan", "gray", "green", "purple", "red", "yellow"),
    "material": ("metal", "rubber"),
    "shape": ("cube", "cylinder", "sphere"),
    "size": ("large", "small"),
}


@dataclass(frozen=True)
class ClevrMutation:
    """One deterministic, content-addressed CLEVR attribute edit."""

    world: World
    kind: ClevrMutationKind
    target_node: str
    attribute: ClevrAttribute
    before: str
    after: str | None
    seed: int
    mutation_sha256: str


def substitute_clevr_attribute(
    world: World,
    target_node: str,
    attribute: ClevrAttribute,
    value: str,
    *,
    seed: int,
    kind: Literal["CONTROL", "SUBSTITUTE"] = "SUBSTITUTE",
) -> ClevrMutation:
    """Return a new world with one typed CLEVR attribute changed."""

    before = _current(world, target_node, attribute)
    if value not in ATTRIBUTE_DOMAINS[attribute]:
        raise InterventionError(
            f"CLEVR {attribute} substitute {value!r} is outside the official domain"
        )
    if value == before:
        raise InterventionError(
            f"CLEVR {attribute} substitute for {target_node!r} must change the value"
        )
    new = with_clevr_attribute(world, target_node, attribute, value)
    return _mutation(
        source=world,
        transformed=new,
        kind=kind,
        target_node=target_node,
        attribute=attribute,
        before=before,
        after=value,
        seed=seed,
    )


def redact_clevr_attribute(
    world: World,
    target_node: str,
    attribute: ClevrAttribute,
    *,
    seed: int,
) -> ClevrMutation:
    """Remove one observed attribute and hide the object's rendered pixels."""

    before = _current(world, target_node, attribute)
    new = with_clevr_attribute(world, target_node, attribute, None)
    visibility = dict(new.get(NODE_VISIBILITY_KEY, {}) or {})
    visibility[target_node] = "hidden"
    new[NODE_VISIBILITY_KEY] = visibility
    return _mutation(
        source=world,
        transformed=new,
        kind="MISSING",
        target_node=target_node,
        attribute=attribute,
        before=before,
        after=None,
        seed=seed,
    )


def with_clevr_attribute(
    world: World,
    target_node: str,
    attribute: ClevrAttribute,
    value: str | None,
) -> World:
    """Clone ``world`` and set one object attribute, preserving visibility."""

    if attribute not in ATTRIBUTE_DOMAINS:
        raise InterventionError(f"unknown CLEVR attribute {attribute!r}")
    if value is not None and value not in ATTRIBUTE_DOMAINS[attribute]:
        raise InterventionError(f"invalid CLEVR {attribute} value {value!r}")
    new = copy.deepcopy(world)
    objects = new.get("objects")
    if not isinstance(objects, list):
        raise InterventionError("CLEVR world objects is not an array")
    for index, obj in enumerate(objects):
        if isinstance(obj, dict) and obj.get("id") == target_node:
            obj[attribute] = value
            objects[index] = obj
            return new
    raise InterventionError(f"CLEVR target {target_node!r} is not a world object")


def object_ids(world: World) -> tuple[str, ...]:
    objects = world.get("objects")
    if not isinstance(objects, list):
        raise InterventionError("CLEVR world objects is not an array")
    ids = [
        str(obj["id"])
        for obj in objects
        if isinstance(obj, dict) and isinstance(obj.get("id"), str)
    ]
    if len(ids) != len(objects) or len(ids) != len(set(ids)):
        raise InterventionError("CLEVR world has missing or duplicate object ids")
    return tuple(sorted(ids))


def _current(world: World, target_node: str, attribute: ClevrAttribute) -> str:
    objects = world.get("objects")
    if not isinstance(objects, list):
        raise InterventionError("CLEVR world objects is not an array")
    for obj in objects:
        if isinstance(obj, dict) and obj.get("id") == target_node:
            value = obj.get(attribute)
            if not isinstance(value, str) or value not in ATTRIBUTE_DOMAINS[attribute]:
                raise InterventionError(
                    f"CLEVR object {target_node!r} has invalid {attribute} {value!r}"
                )
            return value
    raise InterventionError(f"CLEVR target {target_node!r} is not a world object")


def _mutation(
    *,
    source: World,
    transformed: World,
    kind: ClevrMutationKind,
    target_node: str,
    attribute: ClevrAttribute,
    before: str,
    after: str | None,
    seed: int,
) -> ClevrMutation:
    digest = canonical_json_hash(
        {
            "kind": kind,
            "target_node": target_node,
            "attribute": attribute,
            "before": before,
            "after": after,
            "seed": seed,
            "source_world_sha256": world_sha256(source),
            "transformed_world_sha256": world_sha256(transformed),
        }
    )
    return ClevrMutation(
        world=transformed,
        kind=kind,
        target_node=target_node,
        attribute=attribute,
        before=before,
        after=after,
        seed=seed,
        mutation_sha256=digest,
    )


__all__ = [
    "ATTRIBUTE_DOMAINS",
    "ClevrAttribute",
    "ClevrMutation",
    "ClevrMutationKind",
    "object_ids",
    "redact_clevr_attribute",
    "substitute_clevr_attribute",
    "with_clevr_attribute",
]