File size: 12,908 Bytes
7cec401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import networkx as nx
import copy

MAX_OBJECTS_DEEP = 10

def validate_plan(init_graph, goal_graph, actions, print_results=False):
    #Find nodes changed betwee initial and goal graph.
    important_nodes = find_important_nodes(init_graph, goal_graph, add_assets=False)
    if print_results:
        print("Important nodes:\n",important_nodes)
    #Run actions in graph simulation
    final_graph, errors = simulate_on_graph(init_graph, actions)

    #Classes of important objects
    important_node_names = []
    for node in important_nodes:
        if node[0] not in important_node_names:
            important_node_names.append(node[0])

    correct_obj, total_obj = validate_objects(final_graph, goal_graph, important_node_names, print_results)
    correct_assets, total_asets = validate_assets(final_graph, goal_graph, important_nodes)

    object_success_rate = 1.0 if total_obj == 0 else correct_obj / total_obj
    asset_success_rate = 1.0 if total_asets == 0 else correct_assets / total_asets

    total_count = total_obj + total_asets
    partial_success = 1.0 if total_count == 0 else (correct_obj + correct_assets) / total_count

    if print_results:
        print("Object Success Rate:", object_success_rate)
        print("Asset Success Rate:", asset_success_rate)
        print("Partial Success:", partial_success)
        print(errors)

    if len(errors) == 0 and partial_success == 1.0:
        success = True
    else:
        success = False

    return success, partial_success, errors

def simulate_on_graph(init_graph, actions):
    simulator = ValidatorSceneSimulator(init_graph)
    errors = []
    for action in actions:
        feedback = simulator.action(action[0], action[1])
        if feedback:
            errors.append((action, feedback))
    final_graph = simulator.graph
    return final_graph, errors

def validate_objects(final_graph, goal_graph, important_node_names, print_results=False):
    object_count = 0
    goal_state_counts = {}
    final_state_counts = {}
    # Find all objects with same name as relevant node names. (Objects of same class)
    for node_name in goal_graph:
        goal_node = goal_graph.nodes[node_name]
        final_node = final_graph.nodes[node_name]
        if node_name[0] in important_node_names and goal_node['type'] == 'object':
            object_count += 1
            goal_state = (node_name[0], tuple(goal_node['states']), goal_node['relation'], goal_node['related_to'])
            final_state = (node_name[0], tuple(final_node['states']), final_node['relation'], final_node['related_to'])
            
            goal_state_counts[goal_state] = goal_state_counts.get(goal_state, 0) + 1
            final_state_counts[final_state] = final_state_counts.get(final_state, 0) + 1
    state_difference = 0
    # Count objects in correct states
    for key in goal_state_counts:
        if key in final_state_counts:
            goal_state_counts[key] -= final_state_counts[key]
            if goal_state_counts[key] < 0:
                goal_state_counts[key] = 0
        state_difference += goal_state_counts[key]
    correct_objects = object_count - state_difference
    if print_results:
        print("Goal state count:")
        for goal in goal_state_counts:
            print(goal, goal_state_counts[goal], sep=': ')
        print("Final state count:")
        for goal in final_state_counts:
            print(goal, final_state_counts[goal], sep=': ')

    return correct_objects,  object_count

def validate_assets(final_graph, goal_graph, important_nodes):
    # Check Asset states
    asset_count = 0
    correct_states = 0
    for node_name in important_nodes:
        final_node = final_graph.nodes[node_name]
        goal_node = goal_graph.nodes[node_name]
        if final_node['type'] == 'asset':
            asset_count += 1
            if set(final_node['states']) == set(goal_node['states']):
                correct_states += 1
    return correct_states, asset_count

class ValidatorSceneSimulator():
    def __init__(self, graph: nx.Graph):
        self.graph = copy.deepcopy(graph)
        self._reset_edges()

    def _reset_edges(self):
        self.graph.remove_edges_from(list(self.graph.edges))
        for node_name in self.graph.nodes:
            self._add_edge(node_name)

    def _add_edge(self, node_name):
        node = self.graph.nodes[node_name]
        try:
            match node['type']:
                case 'place':
                    self.graph.add_edge(node_name,('scene',1))
                case 'asset':
                    self.graph.add_edge(node_name,node['place'])
                case 'object':
                    self.graph.add_edge(node_name,node['related_to'])
                case 'unseen_object':
                    self.graph.add_edge(node_name,node['related_to'])
                case 'agent':
                    self.graph.add_edge(node_name,node['location'])
                case 'scene':
                    pass
                case _:
                    print(f"Unknown node type: {node['type']}")
        except:
            raise ValueError(f"Error during edges resetting with {node_name} {node}. Check relations.")

    def is_accessible(self, node):
        if node['type'] != 'object':
            return True, ''
        for _ in range(MAX_OBJECTS_DEEP):
            parent_name = node['related_to']
            parent = self.graph.nodes[parent_name]
            if parent['type'] == 'agent':
                return True, ''
            if 'closed' in parent['states'] and node['relation'] == 'inside_of':
                return False, parent_name
            if parent['type'] != 'object':
                return True, ''
            node = parent
        return True, ''
    
    def find_place(self, node):
        for _ in range(MAX_OBJECTS_DEEP+1):
            if node['type'] == 'asset':
                return node['place']
            if node['type'] == 'agent':
                return node['location']
            parent_name = node['related_to']
            node = self.graph.nodes[parent_name]

    def action(self, action, node_name):
        G = self.graph
        if action in ['done', 'discover_objects']:
            return 0
        if node_name not in G:
            return f"Node {node_name} not found in the graph. Try look on or inside assets."
        if action not in ['put_on', 'put_inside', 'pick_up', 'open', 'close', 'turn_on', 'turn_off', 'discover_objects', 'go_to']:
            return f"Action {action} is wrong. No such action as {action}."
        
        node = G.nodes[node_name]
        agent = G.nodes[('agent',1)]
        sayplan_name = node_name[0] +'-'+ str(node_name[1])

        if action in ['put_on', 'put_inside', 'pick_up', 'open', 'close', 'turn_on', 'turn_off', 'discover_objects'] and node['type'] not in ['asset', 'object']:
            return f"Action {action}({sayplan_name}) is wrong. You can interact only with asset and object nodes."
        
        accesible, parent_name = self.is_accessible(node)
        if not accesible:
            return f"Action {action}({sayplan_name}) is wrong.{sayplan_name} in not accesible because {parent_name} is closed."
        
        if node['type'] in ['asset', 'object'] and action not in node['affordances']:
            return f"Action {action}({sayplan_name}) is wrong. It is not possible to {action} {sayplan_name}"
        
        if action not in ['go_to', 'done'] and agent['location'] != self.find_place(node):
            return f"Action {action}({sayplan_name}) is wrong. Agent not in the same room with node."

        match action:
            case 'go_to':
                if node['type'] != 'place':
                    return f"Action {action}({sayplan_name}) is wrong. {sayplan_name} is not a room to go."
                agent['location'] = node_name

            case 'pick_up':
                if agent['holding'] != '':
                    return f"Action {action}({sayplan_name}) is wrong. Agent can hold only one object. Agent aldeady holding {agent['holding']}"
                if (node['type'] != 'object'):
                    return f"Action {action}({sayplan_name}) is wrong. Agent can pick_up only object nodes."

                agent['holding'] = node_name
                node['relation'] = 'inside_hand'
                node['related_to'] = ('agent',1)
            case 'put_on':
                if agent['holding'] == '':
                    return f"Action {action}({sayplan_name}) is wrong. Agent don't holding something to put"
                if 'put_on' not in node['affordances']:
                    return f"Action {action}({sayplan_name}) is wrong. Agent cant put objects on {sayplan_name}"

                G.nodes[agent['holding']]['relation'] = 'ontop_of'
                G.nodes[agent['holding']]['related_to'] = node_name
                agent['holding'] = ''

            case 'put_inside':
                if agent['holding'] == '':
                    return f"Action {action}({sayplan_name}) is wrong. Agent don't holding something to put"
                if agent['holding'] == node:
                    return f"Action {action}({sayplan_name}) is wrong. An object cannot be placed inside itself."
                if 'closed' in node['states']:
                    return f"Action {action}({sayplan_name}) is wrong. Agent cant put objects inside of closed {sayplan_name}"

                G.nodes[agent['holding']]['relation'] = 'inside_of'
                G.nodes[agent['holding']]['related_to'] = node_name
                agent['holding'] = ''
            case 'open':
                if 'open' in node['states']:
                    return f"Action {action}({sayplan_name}) is wrong. {sayplan_name} already open"

                node['states'].remove('closed')
                node['states'].append('open')
            case 'close':
                if 'closed' in node['states']:
                    return f"Action {action}({sayplan_name}) is wrong. {sayplan_name} already closed"

                node['states'].remove('open')
                node['states'].append('closed')
            case 'turn_on':
                if 'on' in node['states']:
                    return f"Action {action}({sayplan_name}) is wrong. {sayplan_name} already turned on"

                if 'off' in node['states']:
                    node['states'].remove('off')
                node['states'].append('on')

                #Adding states for dynamic tasks from SayPlan
                if node_name[0] in ['microwave'] and 'closed' in node['states']:
                    for obj, attr in G.nodes(data=True):
                        if attr['type'] == 'object' and attr['related_to'] == node_name and attr['relation'] == 'inside_of':
                            attr['states'].append('hot')
                if node_name[0] in ['coffee_machine']:
                    for obj, attr in G.nodes(data=True):
                        if attr['type'] == 'object' and attr['related_to'] == node_name and attr['relation'] == 'inside_of':
                            attr['states'].append('filled_coffee')

            case 'turn_off':
                if 'off' in node['states']:
                    return f"Action {action}({sayplan_name}) is wrong. {sayplan_name} already off"
                
                node['states'].remove('on')
                node['states'].append('off')
                
            case 'discover_objects':
                pass
            case 'done':
                pass
            case _:
              return f"Action {action} is wrong. No such action as {action}."
        self._reset_edges()
        return 0

def find_important_nodes(init_graph, goal_graph, add_assets=False):
    """

    Function that return list of objects and assets changed between initial and goal graph.

    """
    def add_parent_nodes(node_name, graph):
        node = graph.nodes[node_name]
        for _ in range(MAX_OBJECTS_DEEP):
            parent_name = node.get('related_to')
            if not parent_name:
                break
            parent = graph.nodes[parent_name]
            important_nodes.add(parent_name)
            if parent['type'] != 'object':
                break
            node = parent

    important_nodes = set()
    for node_name in init_graph.nodes:
        if init_graph.nodes[node_name] != goal_graph.nodes[node_name]:
            important_nodes.add(node_name)

            if init_graph.nodes[node_name]['type'] == 'object' and add_assets:
                add_parent_nodes(node_name, init_graph)
                add_parent_nodes(node_name, goal_graph)

    return list(important_nodes)