Rodrigo Ferreira Rodrigues commited on
Commit
f9e8d8c
·
1 Parent(s): 1e1cba6

add module default template

Browse files
Files changed (5) hide show
  1. README.md +44 -6
  2. app.py +6 -0
  3. path_planning_evaluate.py +225 -0
  4. requirements.txt +1 -0
  5. tests.py +10 -0
README.md CHANGED
@@ -1,12 +1,50 @@
1
  ---
2
- title: Path Planning Evaluate
3
- emoji: 🚀
4
- colorFrom: blue
5
- colorTo: indigo
 
 
 
6
  sdk: gradio
7
- sdk_version: 6.5.1
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Path_Planning_evaluate
3
+ datasets:
4
+ - GeoBenchmark
5
+ tags:
6
+ - evaluate
7
+ - metric
8
+ description: "TODO: add a description here"
9
  sdk: gradio
10
+ sdk_version: 3.19.1
11
  app_file: app.py
12
  pinned: false
13
  ---
14
 
15
+ # Metric Card for Path_Planning_evaluate
16
+
17
+ ***Module Card Instructions:*** *Fill out the following subsections. Feel free to take a look at existing metric cards if you'd like examples.*
18
+
19
+ ## Metric Description
20
+ *Give a brief overview of this metric, including what task(s) it is usually used for, if any.*
21
+
22
+ ## How to Use
23
+ *Give general statement of how to use the metric*
24
+
25
+ *Provide simplest possible example for using the metric*
26
+
27
+ ### Inputs
28
+ *List all input arguments in the format below*
29
+ - **input_field** *(type): Definition of input, with explanation if necessary. State any default value(s).*
30
+
31
+ ### Output Values
32
+
33
+ *Explain what this metric outputs and provide an example of what the metric output looks like. Modules should return a dictionary with one or multiple key-value pairs, e.g. {"bleu" : 6.02}*
34
+
35
+ *State the range of possible values that the metric's output can take, as well as what in that range is considered good. For example: "This metric can take on any value between 0 and 100, inclusive. Higher scores are better."*
36
+
37
+ #### Values from Popular Papers
38
+ *Give examples, preferrably with links to leaderboards or publications, to papers that have reported this metric, along with the values they have reported.*
39
+
40
+ ### Examples
41
+ *Give code examples of the metric being used. Try to include examples that clear up any potential ambiguity left from the metric description above. If possible, provide a range of examples that show both typical and atypical results, as well as examples where a variety of input parameters are passed.*
42
+
43
+ ## Limitations and Bias
44
+ *Note any known limitations or biases that the metric has, with links and references if possible.*
45
+
46
+ ## Citation
47
+ *Cite the source where this metric was introduced.*
48
+
49
+ ## Further References
50
+ *Add any useful further references.*
app.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import evaluate
2
+ from evaluate.utils import launch_gradio_widget
3
+
4
+
5
+ module = evaluate.load("rfr2003/path_planning_evaluate")
6
+ launch_gradio_widget(module)
path_planning_evaluate.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """TODO: Add a description here."""
15
+
16
+ import evaluate
17
+ import datasets
18
+ import ast
19
+ import re
20
+ import heapq
21
+
22
+
23
+ # TODO: Add BibTeX citation
24
+ _CITATION = """\
25
+ @InProceedings{huggingface:module,
26
+ title = {A great new module},
27
+ authors={huggingface, Inc.},
28
+ year={2020}
29
+ }
30
+ """
31
+
32
+ # TODO: Add description of the module here
33
+ _DESCRIPTION = """\
34
+ This metrics aims to evaluate path planning abilities of LMs.
35
+ """
36
+
37
+
38
+ # TODO: Add description of the arguments of the module here
39
+ _KWARGS_DESCRIPTION = """
40
+ Calculates how good the path predicted by the model is.
41
+ Args:
42
+ predictions: list of predictions to score. Each predictions
43
+ should be a string containing coordinates in the format (x, y).
44
+ references: list of reference for each prediction. Each
45
+ reference should be a string with tokens separated by spaces.
46
+ Returns:
47
+ compliance_ratio: 1 if the model is able to produce a well formated python list,
48
+ feasible_ratio: A path is feasible if it doesn'collide with obstacles, get out of the grid and doesn't move diagonally. This metric is the number of feasible paths over the total number of reachable paths.
49
+ success_ratio: A path is successful if it is feasible and goes from the starting point to the end(s) point(s). This metric is the number of successful paths over the total number of reachable paths.
50
+ optimal_ratio: A path is optimal if it is successful and its length is equal or shorter to the golden one. This metric is the number of optimal paths over the total number of reachable paths.
51
+ distance: Sum of the distance from the last position predicted and the objectives for a feasible path not successful.
52
+ unreachable_acc: Number of times the model was able to detect an unreachable path over the total of unreachable paths. -1 if all the goals are reachable.
53
+ Examples:
54
+
55
+ >>> my_new_module = evaluate.load("rfr2003/path_planning_evaluate")
56
+ >>> results = my_new_module.compute(predictions=['[(0,0), (0,1), (1,1)]', '[(0,0), (1,0), (1,1)]', '[(0,0), (1,0), (1,1), (0,1)]', '(0,0'], golds=[[(0,0), (0,1), (1,1)], [(0,0), (0,1), (1,1)], [(0,0), (0,1)], []], obstacles=[[(1,0)], [(1,0)], [], []], ends=[[(1,1)], [(1,1)], [(0,1)], [(0,1)]], n=[2, 2, 2, 2])
57
+ >>> print(results)
58
+ {'compliance_ratio': 0.75, 'success_ratio': 0.6666666666666666,'optimal_ratio': 0.3333333333333333, 'feasible_ratio': 0.6666666666666666, 'distance': 0, 'unreachable_acc': 1.0}
59
+ """
60
+
61
+
62
+ @evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
63
+ class Path_Planning_evaluate(evaluate.Metric):
64
+ """TODO: Short description of my evaluation module."""
65
+
66
+ def _info(self):
67
+ # TODO: Specifies the evaluate.EvaluationModuleInfo object
68
+ return evaluate.MetricInfo(
69
+ # This is the description that will appear on the modules page.
70
+ module_type="metric",
71
+ description=_DESCRIPTION,
72
+ citation=_CITATION,
73
+ inputs_description=_KWARGS_DESCRIPTION,
74
+ # This defines the format of each prediction and reference
75
+ features=datasets.Features({
76
+ 'generations': datasets.Value('string'),
77
+ 'golds': datasets.Sequence(datasets.Sequence(datasets.Value('int64'))),
78
+ 'obstacles': datasets.Sequence(datasets.Sequence(datasets.Value('int64'))),
79
+ 'ends': datasets.Sequence(datasets.Sequence(datasets.Value('int64'))),
80
+ 'n': datasets.Sequence(datasets.Value('int64')),
81
+ }),
82
+ )
83
+
84
+ def _download_and_prepare(self, dl_manager):
85
+ """Optional: download external resources useful to compute the scores"""
86
+ # TODO: Download external resources if needed
87
+ pass
88
+
89
+ def _a_star(self, n, obs, start, end):
90
+ obs = set(obs)
91
+ actions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
92
+
93
+ def heuristic(position):
94
+ return abs(position[0] - end[0]) + abs(position[1] - end[1])
95
+
96
+ visited = set()
97
+ heap = []
98
+ heapq.heappush(heap, (0, start, []))
99
+
100
+ while heap:
101
+ cost, current, path = heapq.heappop(heap)
102
+ if current == end:
103
+ return len(path)
104
+
105
+ if current in visited:
106
+ continue
107
+
108
+ visited.add(current)
109
+
110
+ for action in actions:
111
+ neighbor = (current[0] + action[0], current[1] + action[1])
112
+
113
+ if 0 <= neighbor[0] < n and 0 <= neighbor[1] < n:
114
+ if neighbor not in obs:
115
+ new_cost = cost + 1
116
+ new_path = path + [current]
117
+ heapq.heappush(heap, (new_cost + heuristic(neighbor), neighbor, new_path))
118
+
119
+ return 100
120
+
121
+ def _calculate_path_dist(self, n, obs, start, unvisited):
122
+ dist = 0
123
+
124
+ for end in unvisited:
125
+ dist += self._a_star(n, obs, start, end)
126
+
127
+ return dist
128
+
129
+ def _evaluate_path(self, gen_path, gold_path, ends, obs, n):
130
+ metrics = {'correct': False, 'optimal': False, 'detect_unreachable': False, 'feasible': False, 'is_unreachable': False, 'distance': 0}
131
+ if len(gold_path) == 0:
132
+ metrics['is_unreachable'] = True
133
+ if len(gen_path) == 0:
134
+ metrics['detect_unreachable'] = True
135
+ return metrics
136
+ else:
137
+ if len(gen_path) == 0:
138
+ return metrics
139
+
140
+ start = gold_path[0]
141
+
142
+ obst_set = set(obs)
143
+
144
+ for i, (x, y) in enumerate(gen_path):
145
+ if not (0 <= x < n and 0 <= y < n):
146
+ return metrics #not feasible, correct or optimal
147
+
148
+ if (x, y) in obst_set:
149
+ return metrics #not feasible, correct or optimal
150
+
151
+ if i > 0 and (abs(x-gen_path[i][0]) + abs(y-gen_path[i][1]) > 1):
152
+ return metrics #not feasible, correct or optimal
153
+
154
+ metrics['feasible'] = True
155
+
156
+ unvisited = set()
157
+
158
+ if gen_path[0] == start:
159
+ metrics['correct'] = True
160
+ for e in ends:
161
+ if e not in gen_path:
162
+ metrics['correct'] = False
163
+ unvisited.add(e)
164
+
165
+ if metrics['correct']:
166
+ if len(gen_path) <= len(gold_path):
167
+ metrics['optimal'] = True
168
+ else:
169
+ metrics['distance'] = self._calculate_path_dist(n, obs, gen_path[-1], unvisited)
170
+
171
+ return metrics
172
+
173
+ def _compute(self, generations, golds, obstacles, ends, n):
174
+ assert len(generations) == len(golds) == len(obstacles) == len(ends) == len(n)
175
+ assert isinstance(golds, list)
176
+
177
+ correct, total_reach, total_unreach = 0, 0, 0
178
+
179
+ pattern = r"\(\s*(\d*)\s*,\s*(\d*)\s*\)"
180
+
181
+ metrics = {'compliance': 0, 'correct': 0, 'optimal': 0, 'n_detect_unreachable': 0, 'feasible': 0, 'distance': 0}
182
+
183
+ for gen, gold, _obs, _ends, _n in zip(generations, golds, obstacles, ends, n):
184
+
185
+ try:
186
+ gen_path = ast.literal_eval(gen)
187
+ for i in range(len(gen_path)):
188
+ gen_path[i] = (int(gen_path[i][0]), int(gen_path[i][1]))
189
+ metrics['compliance'] += 1
190
+ except:
191
+ matches = re.findall(pattern, gen)
192
+ gen_path = [(int(x), int(y)) for x, y in matches]
193
+
194
+ gold_path = [(int(p[0]), int(p[1])) for p in gold]
195
+ _obs = [(int(p[0]), int(p[1])) for p in _obs]
196
+ _ends = [(int(p[0]), int(p[1])) for p in _ends]
197
+
198
+ m = self._evaluate_path(gen_path, gold_path, _ends, _obs, _n)
199
+
200
+ if m['is_unreachable']:
201
+ total_unreach += 1
202
+ metrics['n_detect_unreachable'] += m['detect_unreachable']
203
+
204
+ else:
205
+ for k in ['correct', 'optimal', 'feasible']:
206
+ metrics[k] += int(m[k])
207
+
208
+ if m['feasible'] and not m['correct']:
209
+ metrics['distance'] += m['distance']
210
+
211
+ total_reach += 1
212
+
213
+ diff = metrics['feasible']-metrics['correct']
214
+
215
+ r_metrics = {}
216
+ r_metrics.update({
217
+ 'compliance_ratio': metrics['compliance']/(total_reach+total_unreach),
218
+ 'success_ratio': metrics['correct']/total_reach,
219
+ 'optimal_ratio': metrics['optimal']/total_reach,
220
+ 'feasible_ratio': metrics['feasible']/total_reach,
221
+ 'distance': metrics['distance']/diff if diff > 0 else metrics['distance'],
222
+ 'unreachable_acc': metrics['n_detect_unreachable']/total_unreach if total_unreach > 0 else -1,
223
+ })
224
+
225
+ return r_metrics
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ git+https://github.com/huggingface/evaluate@main
tests.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ test_cases = [
2
+ {
3
+ 'predictions': ['[(0,0), (0,1), (1,1)]', '[(0,0), (1,0), (1,1)]', '[(0,0), (1,0), (1,1), (0,1)]', '(0,0'],
4
+ 'golds': [[(0,0), (0,1), (1,1)], [(0,0), (0,1), (1,1)], [(0,0), (0,1)], []],
5
+ 'obstacles': [[(1,0)], [(1,0)], [], []],
6
+ 'ends': [[(1,1)], [(1,1)], [(0,1)], [(0,1)]],
7
+ 'n': [2, 2, 2, 2],
8
+ "result": {'compliance_ratio': 0.75, 'success_ratio': 0.6666666666666666,'optimal_ratio': 0.3333333333333333, 'feasible_ratio': 0.6666666666666666, 'distance': 0, 'unreachable_acc': 1.0}
9
+ }
10
+ ]