rogermt commited on
Commit
bd3af66
·
verified ·
1 Parent(s): 2ed0296

Upload mxbi-arckit.txt

Browse files
Files changed (1) hide show
  1. mxbi-arckit.txt +1302 -0
mxbi-arckit.txt ADDED
@@ -0,0 +1,1302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Directory structure:
2
+ └── mxbi-arckit/
3
+ ├── README.md
4
+ ├── LICENSE
5
+ ├── pyproject.toml
6
+ ├── arckit/
7
+ │ ├── __init__.py
8
+ │ ├── cli.py
9
+ │ ├── data.py
10
+ │ ├── importtool.py
11
+ │ └── vis.py
12
+ └── .github/
13
+ └── workflows/
14
+ └── pypi.yml
15
+
16
+ ================================================
17
+ FILE: README.md
18
+ ================================================
19
+ # arckit
20
+
21
+ [![PyPI version](https://badge.fury.io/py/arckit.svg)](https://badge.fury.io/py/arckit)
22
+
23
+ ![Example visualisation of ARC grids](./images/allgrids10.svg)
24
+
25
+ Python and command-line tools for easily working with the ARC, ARC-AGI & ARC-AGI-2 datasets.
26
+
27
+ ```bash
28
+ pip install -U arckit
29
+ ```
30
+
31
+ Arckit provides tools for loading the data in a friendly format (without a separate download!), visualizing the data with high-quality vector graphics, and evaluating models on the dataset.
32
+
33
+ ✨ **NEW in v1.0:** Added ARC-AGI-2 & ARC Prize 2025 Data, updated evaluation ruleset.
34
+
35
+ ## 🐍 Python API
36
+
37
+ ### Loading the dataset
38
+
39
+ ```python
40
+ >>> import arckit
41
+ >>> train_set, eval_set = arckit.load_data() # Load ARC-AGI-2 train/eval.
42
+ >>> train_set, eval_set = arckit.load_data("kaggle") # Load ARC Prize 2025
43
+ >>> train_set, eval_set = arckit.load_data("arcagi") # Load latest ARC-AGI-1
44
+
45
+ # TaskSets are iterable and indexable
46
+ >>> train_set
47
+ <TaskSet: 400 tasks>
48
+ >>> train_set[0]
49
+ <Task-train 007bbfb7 | 5 train | 1 test>
50
+
51
+ # Indexing can be done by task ID
52
+ >>> train_set[0] == train_set['007bbfb7']
53
+ True
54
+
55
+ # You can load specific tasks by ID
56
+ >>> task = arckit.load_single('007bbfb7')
57
+ ```
58
+
59
+ ### Interacting with tasks
60
+
61
+ ```python
62
+ >>> task.dataset
63
+ 'train'
64
+ >>> task.id
65
+ '007bbfb7'
66
+
67
+ ## Extracting task Grids
68
+ >>> task.train # o task.test
69
+ => List[Tuple[ndarray, ndarray]] # of input/output pairs
70
+
71
+ >>> task.train[0][0] # input of 1st train example
72
+ array([[0, 7, 7],
73
+ [7, 7, 7],
74
+ [0, 7, 7]])
75
+
76
+ # Tasks can be previewed (with colour!) in Python.
77
+ >>> train_set[15].show()
78
+ <Task-train 0d3d703e | 4 train | 1 test>
79
+ ┏━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┳━━┳━━━━━━━━┓
80
+ ┃ A-in 3x3 ┃ A-out 3x3 ┃ B-in 3x3 ┃ B-out 3x3 ┃ C-in 3x3 ┃ C-out 3x3 ┃ D-in 3x3 ┃ D-out 3x3 ┃ ┃ TA-in ┃
81
+ ┡━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━╇━━╇━━━━━━━━┩
82
+ │ 3 1 2 │ 4 5 6 │ 2 3 8 │ 6 4 9 │ 5 8 6 │ 1 9 2 │ 9 4 2 │ 8 3 6 │ │ 8 1 3 │
83
+ │ 3 1 2 │ 4 5 6 │ 2 3 8 │ 6 4 9 │ 5 8 6 │ 1 9 2 │ 9 4 2 │ 8 3 6 │ │ 8 1 3 │
84
+ │ 3 1 2 │ 4 5 6 │ 2 3 8 │ 6 4 9 │ 5 8 6 │ 1 9 2 │ 9 4 2 │ 8 3 6 │ │ 8 1 3 │
85
+ └──────────┴───────────┴──────────┴───────────┴──────────┴───────────┴──────────┴───────────┴──┴────────┘
86
+
87
+ # Get task in original ARC format following fchollet's repo.
88
+ >>> task.to_dict()
89
+ => {
90
+ "id": str,
91
+ "train": List[{"input": List[List[int]], "output": List[List[int]]}],
92
+ "test": List[{"input": List[List[int]], "output": List[List[int]]}]
93
+ }
94
+ ```
95
+
96
+ ### Scoring a submission file:
97
+
98
+ To evaluate a submission in [Kaggle ARC format](https://www.kaggle.com/competitions/abstraction-and-reasoning-challenge/overview/evaluation):
99
+
100
+ ```python
101
+ >>> eval_set.score_submission(
102
+ 'submission.csv', # Submission with two columns output_id,output in Kaggle fomrat
103
+ topn=2, # How many predictions to consider (default: 2)
104
+ return_correct=False # Whether to return a list of which tasks were solved
105
+ )
106
+ ```
107
+
108
+ > **Note:** the default `topn` was changed from 3 to 2 in v1.0 to match changes in the official evaluation.
109
+
110
+ ### Loading a specific dataset version
111
+
112
+ The ARC-AGI datasets have had [several bugfixes](https://github.com/arcprize/ARC-AGI-2/blob/main/changelog.md) since original release. Additionally, a new ARC-AGI-2 dataset has been released for competitions starting in 2025. By default, the `latest` version of ARC-AGI-2 is loaded, but you can specify a `version` parameter to both `load_data` and `load_single` to load other datasets.
113
+
114
+ **The version options are:**
115
+
116
+ - `latest`, `arcagi2`: The latest version of the ARC-AGI-2 dataset (currently: `f3283f7`)
117
+ - `arcagi`: The latest version of the ARC-AGI dataset (currently: `aa922be`)
118
+ - `kaggle`, `kaggle2025`: The data for the 2025 Kaggle competition based on ARC-AGI-2 (currently: `kaggle250808`)
119
+ - `kaggle2024`: The data for the 2024 Kaggle competition based on ARC-AGI (pinned)
120
+ - `arc`, `kaggle2019`: The original ARC data, as in the 2019 Kaggle competition (pinned)
121
+
122
+ > **Note:** You may wish to pin your data to a specific version number to avoid underlying data changes during research. To do this, use the most specific name available when loading data, or pin the installed version of `arckit` in your environment.
123
+
124
+ ## 🖼️ Creating visualisations
125
+
126
+ The `arckit.vis` submodule provides useful functions for creating vector graphics visualisations of tasks, using the `drawsvg` module. The docstrings for these functions provide more detailed information as well as additional options.
127
+
128
+ ```python
129
+ >>> import arckit.vis as vis
130
+ >>> grid = vis.draw_grid(task.train['2013d3e2'][0], xmax=3, ymax=3, padding=.5, label='Example')
131
+ >>> vis.output_drawing(grid, "images/grid_example.png") # svg/pdf/png
132
+ ```
133
+
134
+ ![Example of arckit visualisation](./images/grid_example.png)
135
+
136
+ When drawing tasks, arckit will intelligently resize all of the grids such that the total size of the illustration does not exceed the chosen width/height.
137
+
138
+ ```python
139
+ >>> task = vis.draw_task(train_set[0], width=10, height=6, label='Example')
140
+ >>> vis.output_drawing(task, "images/arcshow_example.png") # svg/pdf/png
141
+ ```
142
+
143
+ ![Example of arckit output](./images/arcsave_example.png)
144
+
145
+ Alternatively, the `print_grid` function outputs a grid directly to the terminal without creating any files.
146
+
147
+ ```python
148
+ >>> task = train_set[0] # Get the first task
149
+ >>> for i, (input_array, output_array) in enumerate(task.train): # Loop through the training examples
150
+ >>> print(f"Training Example {i+1}")
151
+ >>> print("Input:")
152
+ >>> vis.print_grid(input_array)
153
+ >>> print("Output:")
154
+ >>> vis.print_grid(output_array)
155
+ >>> print()
156
+ ```
157
+
158
+ <img src="./images/arc_terminal_print_grid_example.png" width="200">
159
+
160
+ ## 💻 Command-line tools
161
+
162
+ `arcshow` draws a visualisation of a specific task straight to the console:
163
+
164
+ ![Example of arcshow command output (with colours)](./images/arcshow_example.png)
165
+
166
+ `arcsave` saves a visualisation of a specific task to a file (pdf/svg/png), and is useful for inspecting tasks or producing high quality graphics showing specific tasks (e.g. for a paper). Tasks can be specified by their hex ID or by dataset, e.g. `train0`.
167
+
168
+ ```bash
169
+ usage: arcsave [-h] [--output OUTPUT] task_id width height
170
+
171
+ Save a task to a image file.
172
+
173
+ positional arguments:
174
+ task_id The task id to save. Can either be a task ID or a string e.g. `train0`
175
+ width The width of the output image
176
+ height The height of the output image
177
+
178
+ optional arguments:
179
+ -h, --help show this help message and exit
180
+ --output OUTPUT The output file to save to. Must end in .svg/.pdf/.png. By default, pdf is used.
181
+ ```
182
+
183
+ ![Example of arcsave command output](./images/arcsave_example.png)
184
+
185
+ ## 💡 Contributions
186
+
187
+ Any relevant contributions are very welcome! Please feel free to open an issue or pull request, or drop me an email if you want to discuss any possible changes.
188
+
189
+ ## 📜 Acknowledgements
190
+
191
+ The ARC and ARC-AGI-2 datasets was graciously released by Francois Chollet under [Apache 2.0](https://github.com/fchollet/ARC/blob/master/LICENSE) and can be found in original format in [these](https://github.com/fchollet/ARC) [repositories](https://github.com/arcprize/ARC-AGI-2). The dataset is reproduced within the `arckit` package under the same license.
192
+
193
+
194
+
195
+ ================================================
196
+ FILE: LICENSE
197
+ ================================================
198
+ Apache License
199
+ Version 2.0, January 2004
200
+ http://www.apache.org/licenses/
201
+
202
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
203
+
204
+ 1. Definitions.
205
+
206
+ "License" shall mean the terms and conditions for use, reproduction,
207
+ and distribution as defined by Sections 1 through 9 of this document.
208
+
209
+ "Licensor" shall mean the copyright owner or entity authorized by
210
+ the copyright owner that is granting the License.
211
+
212
+ "Legal Entity" shall mean the union of the acting entity and all
213
+ other entities that control, are controlled by, or are under common
214
+ control with that entity. For the purposes of this definition,
215
+ "control" means (i) the power, direct or indirect, to cause the
216
+ direction or management of such entity, whether by contract or
217
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
218
+ outstanding shares, or (iii) beneficial ownership of such entity.
219
+
220
+ "You" (or "Your") shall mean an individual or Legal Entity
221
+ exercising permissions granted by this License.
222
+
223
+ "Source" form shall mean the preferred form for making modifications,
224
+ including but not limited to software source code, documentation
225
+ source, and configuration files.
226
+
227
+ "Object" form shall mean any form resulting from mechanical
228
+ transformation or translation of a Source form, including but
229
+ not limited to compiled object code, generated documentation,
230
+ and conversions to other media types.
231
+
232
+ "Work" shall mean the work of authorship, whether in Source or
233
+ Object form, made available under the License, as indicated by a
234
+ copyright notice that is included in or attached to the work
235
+ (an example is provided in the Appendix below).
236
+
237
+ "Derivative Works" shall mean any work, whether in Source or Object
238
+ form, that is based on (or derived from) the Work and for which the
239
+ editorial revisions, annotations, elaborations, or other modifications
240
+ represent, as a whole, an original work of authorship. For the purposes
241
+ of this License, Derivative Works shall not include works that remain
242
+ separable from, or merely link (or bind by name) to the interfaces of,
243
+ the Work and Derivative Works thereof.
244
+
245
+ "Contribution" shall mean any work of authorship, including
246
+ the original version of the Work and any modifications or additions
247
+ to that Work or Derivative Works thereof, that is intentionally
248
+ submitted to Licensor for inclusion in the Work by the copyright owner
249
+ or by an individual or Legal Entity authorized to submit on behalf of
250
+ the copyright owner. For the purposes of this definition, "submitted"
251
+ means any form of electronic, verbal, or written communication sent
252
+ to the Licensor or its representatives, including but not limited to
253
+ communication on electronic mailing lists, source code control systems,
254
+ and issue tracking systems that are managed by, or on behalf of, the
255
+ Licensor for the purpose of discussing and improving the Work, but
256
+ excluding communication that is conspicuously marked or otherwise
257
+ designated in writing by the copyright owner as "Not a Contribution."
258
+
259
+ "Contributor" shall mean Licensor and any individual or Legal Entity
260
+ on behalf of whom a Contribution has been received by Licensor and
261
+ subsequently incorporated within the Work.
262
+
263
+ 2. Grant of Copyright License. Subject to the terms and conditions of
264
+ this License, each Contributor hereby grants to You a perpetual,
265
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
266
+ copyright license to reproduce, prepare Derivative Works of,
267
+ publicly display, publicly perform, sublicense, and distribute the
268
+ Work and such Derivative Works in Source or Object form.
269
+
270
+ 3. Grant of Patent License. Subject to the terms and conditions of
271
+ this License, each Contributor hereby grants to You a perpetual,
272
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
273
+ (except as stated in this section) patent license to make, have made,
274
+ use, offer to sell, sell, import, and otherwise transfer the Work,
275
+ where such license applies only to those patent claims licensable
276
+ by such Contributor that are necessarily infringed by their
277
+ Contribution(s) alone or by combination of their Contribution(s)
278
+ with the Work to which such Contribution(s) was submitted. If You
279
+ institute patent litigation against any entity (including a
280
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
281
+ or a Contribution incorporated within the Work constitutes direct
282
+ or contributory patent infringement, then any patent licenses
283
+ granted to You under this License for that Work shall terminate
284
+ as of the date such litigation is filed.
285
+
286
+ 4. Redistribution. You may reproduce and distribute copies of the
287
+ Work or Derivative Works thereof in any medium, with or without
288
+ modifications, and in Source or Object form, provided that You
289
+ meet the following conditions:
290
+
291
+ (a) You must give any other recipients of the Work or
292
+ Derivative Works a copy of this License; and
293
+
294
+ (b) You must cause any modified files to carry prominent notices
295
+ stating that You changed the files; and
296
+
297
+ (c) You must retain, in the Source form of any Derivative Works
298
+ that You distribute, all copyright, patent, trademark, and
299
+ attribution notices from the Source form of the Work,
300
+ excluding those notices that do not pertain to any part of
301
+ the Derivative Works; and
302
+
303
+ (d) If the Work includes a "NOTICE" text file as part of its
304
+ distribution, then any Derivative Works that You distribute must
305
+ include a readable copy of the attribution notices contained
306
+ within such NOTICE file, excluding those notices that do not
307
+ pertain to any part of the Derivative Works, in at least one
308
+ of the following places: within a NOTICE text file distributed
309
+ as part of the Derivative Works; within the Source form or
310
+ documentation, if provided along with the Derivative Works; or,
311
+ within a display generated by the Derivative Works, if and
312
+ wherever such third-party notices normally appear. The contents
313
+ of the NOTICE file are for informational purposes only and
314
+ do not modify the License. You may add Your own attribution
315
+ notices within Derivative Works that You distribute, alongside
316
+ or as an addendum to the NOTICE text from the Work, provided
317
+ that such additional attribution notices cannot be construed
318
+ as modifying the License.
319
+
320
+ You may add Your own copyright statement to Your modifications and
321
+ may provide additional or different license terms and conditions
322
+ for use, reproduction, or distribution of Your modifications, or
323
+ for any such Derivative Works as a whole, provided Your use,
324
+ reproduction, and distribution of the Work otherwise complies with
325
+ the conditions stated in this License.
326
+
327
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
328
+ any Contribution intentionally submitted for inclusion in the Work
329
+ by You to the Licensor shall be under the terms and conditions of
330
+ this License, without any additional terms or conditions.
331
+ Notwithstanding the above, nothing herein shall supersede or modify
332
+ the terms of any separate license agreement you may have executed
333
+ with Licensor regarding such Contributions.
334
+
335
+ 6. Trademarks. This License does not grant permission to use the trade
336
+ names, trademarks, service marks, or product names of the Licensor,
337
+ except as required for reasonable and customary use in describing the
338
+ origin of the Work and reproducing the content of the NOTICE file.
339
+
340
+ 7. Disclaimer of Warranty. Unless required by applicable law or
341
+ agreed to in writing, Licensor provides the Work (and each
342
+ Contributor provides its Contributions) on an "AS IS" BASIS,
343
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
344
+ implied, including, without limitation, any warranties or conditions
345
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
346
+ PARTICULAR PURPOSE. You are solely responsible for determining the
347
+ appropriateness of using or redistributing the Work and assume any
348
+ risks associated with Your exercise of permissions under this License.
349
+
350
+ 8. Limitation of Liability. In no event and under no legal theory,
351
+ whether in tort (including negligence), contract, or otherwise,
352
+ unless required by applicable law (such as deliberate and grossly
353
+ negligent acts) or agreed to in writing, shall any Contributor be
354
+ liable to You for damages, including any direct, indirect, special,
355
+ incidental, or consequential damages of any character arising as a
356
+ result of this License or out of the use or inability to use the
357
+ Work (including but not limited to damages for loss of goodwill,
358
+ work stoppage, computer failure or malfunction, or any and all
359
+ other commercial damages or losses), even if such Contributor
360
+ has been advised of the possibility of such damages.
361
+
362
+ 9. Accepting Warranty or Additional Liability. While redistributing
363
+ the Work or Derivative Works thereof, You may choose to offer,
364
+ and charge a fee for, acceptance of support, warranty, indemnity,
365
+ or other liability obligations and/or rights consistent with this
366
+ License. However, in accepting such obligations, You may act only
367
+ on Your own behalf and on Your sole responsibility, not on behalf
368
+ of any other Contributor, and only if You agree to indemnify,
369
+ defend, and hold each Contributor harmless for any liability
370
+ incurred by, or claims asserted against, such Contributor by reason
371
+ of your accepting any such warranty or additional liability.
372
+
373
+ END OF TERMS AND CONDITIONS
374
+
375
+ APPENDIX: How to apply the Apache License to your work.
376
+
377
+ To apply the Apache License to your work, attach the following
378
+ boilerplate notice, with the fields enclosed by brackets "[]"
379
+ replaced with your own identifying information. (Don't include
380
+ the brackets!) The text should be enclosed in the appropriate
381
+ comment syntax for the file format. We also recommend that a
382
+ file or class name and description of purpose be included on the
383
+ same "printed page" as the copyright notice for easier
384
+ identification within third-party archives.
385
+
386
+ Copyright [yyyy] [name of copyright owner]
387
+
388
+ Licensed under the Apache License, Version 2.0 (the "License");
389
+ you may not use this file except in compliance with the License.
390
+ You may obtain a copy of the License at
391
+
392
+ http://www.apache.org/licenses/LICENSE-2.0
393
+
394
+ Unless required by applicable law or agreed to in writing, software
395
+ distributed under the License is distributed on an "AS IS" BASIS,
396
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
397
+ See the License for the specific language governing permissions and
398
+ limitations under the License.
399
+
400
+
401
+
402
+ ================================================
403
+ FILE: pyproject.toml
404
+ ================================================
405
+ [build-system]
406
+ requires = ["setuptools>=61.0", "wheel"]
407
+ build-backend = "setuptools.build_meta"
408
+
409
+ [project]
410
+ name = "arckit"
411
+ version = "1.0.1" # Remember to change in __init__.py
412
+ description = "Tools for working with the Abstraction & Reasoning Corpus (ARC-AGI)"
413
+ readme = "README.md"
414
+ authors = [
415
+ {name = "Mikel Bober-Irizar", email = "mikel@mxbi.net"}
416
+ ]
417
+ license = "Apache-2.0"
418
+ requires-python = ">=3.8"
419
+ keywords = ["arc", "agi", "reasoning", "abstraction"]
420
+ classifiers = [
421
+ "Development Status :: 5 - Production/Stable",
422
+ "Programming Language :: Python :: 3",
423
+ "Programming Language :: Python :: 3.8",
424
+ "Programming Language :: Python :: 3.9",
425
+ "Programming Language :: Python :: 3.10",
426
+ "Programming Language :: Python :: 3.11",
427
+ "Programming Language :: Python :: 3.12",
428
+ "Programming Language :: Python :: 3.13",
429
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
430
+ ]
431
+ dependencies = [
432
+ "numpy",
433
+ "rich",
434
+ "drawsvg",
435
+ ]
436
+
437
+ [project.urls]
438
+ Homepage = "https://github.com/mxbi/arckit"
439
+ Repository = "https://github.com/mxbi/arckit"
440
+ Issues = "https://github.com/mxbi/arckit/issues"
441
+
442
+ [project.scripts]
443
+ arctask = "arckit.cli:taskprint"
444
+ arcsave = "arckit.cli:tasksave"
445
+
446
+ [tool.setuptools.packages.find]
447
+ include = ["arckit*"]
448
+ exclude = ["arckit.__pycache__*"]
449
+
450
+ [tool.setuptools.package-data]
451
+ arckit = ["data/*.json"]
452
+
453
+ [tool.setuptools.exclude-package-data]
454
+ arckit = ["__pycache__/*", "*.py[co]"]
455
+
456
+
457
+ ================================================
458
+ FILE: arckit/__init__.py
459
+ ================================================
460
+ from .data import Task, load_data, fmt_grid, load_single
461
+ from .vis import draw_grid, draw_task, output_drawing
462
+
463
+ __version__ = "1.0.1"
464
+ __version_info__ = (1, 0, 1)
465
+
466
+
467
+ ================================================
468
+ FILE: arckit/cli.py
469
+ ================================================
470
+ import sys
471
+ import argparse
472
+ from .data import load_single
473
+ from .vis import draw_task, output_drawing
474
+
475
+ def taskprint():
476
+ if len(sys.argv) < 2:
477
+ print("Usage: arctask <task_id>")
478
+ return
479
+
480
+ task = load_single(sys.argv[1])
481
+
482
+ task.show()
483
+
484
+ def tasksave():
485
+ parser = argparse.ArgumentParser(description='Save a task to a image file.')
486
+ parser.add_argument('task_id', type=str, help='The task id to save. Can either be a task ID or a string e.g. `train0`')
487
+ parser.add_argument('width', type=int, help='The width of the output image', default=20)
488
+ parser.add_argument('height', type=int, help='The height of the output image', default=10)
489
+ parser.add_argument('--output', type=str, help='The output file to save to. Must end in .svg/.pdf/.png. By default, pdf is used.', default=False, required=False)
490
+ args = parser.parse_args()
491
+
492
+ task = load_single(args.task_id)
493
+
494
+ drawing = draw_task(task, width=args.width, height=args.height)
495
+ out_fn = args.output or f'{task.id}_{drawing.width}x{drawing.height}.pdf'
496
+ print(f'Drawn task {task.id} ({drawing.width}x{drawing.height}), saving to {out_fn}')
497
+
498
+ output_drawing(drawing, out_fn)
499
+
500
+
501
+ ================================================
502
+ FILE: arckit/data.py
503
+ ================================================
504
+ import json
505
+ import numpy as np
506
+ import os
507
+ import csv
508
+
509
+ from rich import print
510
+ from rich.panel import Panel
511
+ from rich.table import Table
512
+ from rich.text import Text
513
+
514
+ def idx2chr(idx):
515
+ return chr(idx + 65)
516
+
517
+ def fmt_grid(grid, colour=True, spaces=True):
518
+ grid_str = []
519
+ if not colour:
520
+ for row in grid:
521
+ if spaces == 'gpt':
522
+ grid_str.append(''.join([' ' + str(x) for x in row]))
523
+ elif spaces:
524
+ grid_str.append(' '.join([str(x) for x in row]))
525
+ else:
526
+ grid_str.append(''.join([str(x) for x in row]))
527
+
528
+ return "\n".join(grid_str)
529
+ else:
530
+ if spaces:
531
+ cmap = dict({i: (str(i) + ' ', f"color({i})") for i in range(10)}, **{str(i): (str(i) + ' ', f"color({i})") for i in range(10)})
532
+ else:
533
+ cmap = dict({i: (str(i), f"color({i})") for i in range(10)}, **{str(i): (str(i), f"color({i})") for i in range(10)})
534
+
535
+ for row in grid:
536
+ grid_str += [cmap[digit] for digit in row]
537
+ grid_str += ["\n"]
538
+
539
+ return Text.assemble(*grid_str[:-1])
540
+
541
+ class Task:
542
+ def __init__(self, id, train, test, dataset=None, version=None):
543
+ self.dataset = dataset
544
+ self.version = version
545
+ self.id = id
546
+ self.train = [(np.array(example['input']), np.array(example['output'])) for example in train]
547
+ self.test = [(np.array(example['input']), np.array(example['output'])) for example in test]
548
+
549
+ self.color_count = max
550
+
551
+ def __lt__(self, other):
552
+ return self.id < other.id
553
+
554
+ def __hash__(self):
555
+ return hash(self.id)
556
+
557
+ @classmethod
558
+ def from_json(cls, json_file):
559
+ with open(json_file) as f:
560
+ data = json.load(f)
561
+
562
+ # train_examples = [(np.array(example['input']), np.array(example['output'])) for example in data['train']]
563
+ # test_examples = [(np.array(example['input']), np.array(example['output'])) for example in data['test']]
564
+
565
+ return cls(os.path.basename(json_file)[:-5], data['train'], data['test'])
566
+
567
+ def __repr__(self):
568
+ return f"<Task-{self.dataset} {self.id} | {len(self.train)} train | {len(self.test)} test>"
569
+
570
+ def show(self, answer=False):
571
+ table = Table(title=repr(self), show_lines=True)
572
+
573
+ data = []
574
+ for i, (input, output) in enumerate(self.train):
575
+ data += [fmt_grid(input), fmt_grid(output)]
576
+ ix, iy = input.shape
577
+ ox, oy = output.shape
578
+ table.add_column(f"{idx2chr(i)}-in {ix}x{iy}", justify="center", no_wrap=True)
579
+ table.add_column(f"{idx2chr(i)}-out {ox}x{oy}", justify="center", no_wrap=True)
580
+
581
+ data.append('')
582
+ table.add_column("")
583
+ for i, (input, output) in enumerate(self.test):
584
+ table.add_column(f"T{idx2chr(i)}-in", justify="center", header_style="bold", no_wrap=True)
585
+ if answer:
586
+ table.add_column(f"T{idx2chr(i)}-out", justify="center", header_style="bold", no_wrap=True)
587
+ data += [fmt_grid(input), fmt_grid(output)]
588
+ else:
589
+ data += [fmt_grid(input)]
590
+
591
+ table.add_row(*data)
592
+ print(table)
593
+ return table
594
+
595
+ def to_dict(self):
596
+ return {
597
+ "id": self.id,
598
+ "train": [{"input": input.tolist(), "output": output.tolist()} for input, output in self.train],
599
+ "test": [{"input": input.tolist(), "output": output.tolist()} for input, output in self.test]
600
+ }
601
+
602
+ def dreamcoder_format(self):
603
+ # TODO: Separate out the train/test data
604
+ # Currently, dreamcoder gets to search on the train examples too
605
+ # This is included to keep compatibility with Simon's results, but should be corrected and written about
606
+ grids = []
607
+ for inp, out in self.train:
608
+ grids += [inp, out]
609
+ for inp, out in self.test:
610
+ grids += [inp, out]
611
+ return {"name": self.id, "grids": grids}
612
+
613
+ def scoreA(self, output):
614
+ output = np.array(output).astype(int)
615
+ if output.shape != self.test[0][1].shape:
616
+ return False
617
+ return (output == self.test[0][1]).all()
618
+
619
+ def gpt_prompt(self, i_test, mode="chatgpt", include_completion=False, rot90=False, transpose=False, spaces=True):
620
+ if mode == "chatgpt":
621
+ prompt = "We are playing a game which involves transforming an input grid of digits into an output grid of digits. In general, digits form objects in 2D and the task is to perform some spatial transformation of these objects to go from the input grid to the output grid. All the information about the transformation is contained within the input pairs themselves, and your answer will only be correct if the output grid is exactly correct, so this is what I expect from you. I will begin by giving you several examples of input-output pairs. You will then be given a new input grid, and you must provide the corresponding output grid.\n"
622
+ elif mode == "gpt3":
623
+ # prompt = "We are playing a game which involves transforming an input grid of digits into an output grid of digits. Every below pair of grids contains the same transformation. In general, digits form objects in 2D and the task is to perform some spatial transformation of these objects to go from the input tile to the output tile. One such example of tiles is below.\n"
624
+ prompt = "We are playing a game which involves transformaing a 2D input grid of digits into an output grid of digits. Every below pair of grids contains the same transformation (e.g. rotation, symmetry, manipulation of objects). Each Input grid is followed by an Output grid which applies the same transformation as previous Input/Output pairs. One such example is below.\n"
625
+ else:
626
+ raise ValueError(f"Unknown mode: {mode}")
627
+
628
+ i = 1
629
+ for input, output in self.train:
630
+ if rot90:
631
+ input = np.rot90(input)
632
+ output = np.rot90(output)
633
+ if transpose:
634
+ input = np.transpose(input)
635
+ output = np.transpose(output)
636
+
637
+ prompt += f"""Input {i}:
638
+ {fmt_grid(input, colour=False, spaces=spaces)}
639
+ Output {i}:
640
+ {fmt_grid(output, colour=False, spaces=spaces)}\n
641
+ """
642
+ i += 1
643
+
644
+ test_grid = self.test[i_test][0]
645
+ if rot90:
646
+ test_grid = np.rot90(test_grid)
647
+ if transpose:
648
+ test_grid = np.transpose(test_grid)
649
+
650
+ prompt += f"Input {i}:\n"
651
+ prompt += f"{fmt_grid(test_grid, colour=False, spaces=spaces)}"
652
+ if mode == "gpt3":
653
+ prompt += f"\nOutput {i}:"
654
+ else:
655
+ prompt += f"\nOutput {i}: (please provide the output grid only)\n"
656
+
657
+ if include_completion:
658
+ if rot90:
659
+ output = np.rot90(self.test[i_test][1])
660
+ if transpose:
661
+ output = np.transpose(self.test[i_test][1])
662
+ prompt += f"\n{fmt_grid(self.test[i_test][1], colour=False, spaces=spaces)}"
663
+ return prompt
664
+
665
+ class TaskSet:
666
+ def __init__(self, tasks):
667
+ tasks = sorted(tasks)
668
+ self.tasks = tasks
669
+ self.task_dict = {task.id: task for task in tasks}
670
+
671
+ def __getitem__(self, item):
672
+ if isinstance(item, slice):
673
+ return TaskSet(self.tasks[item])
674
+ get = self.task_dict.get(item)
675
+ if get is None:
676
+ try:
677
+ return self.tasks[item]
678
+ except (TypeError, IndexError):
679
+ raise KeyError(f"Task {item} not found")
680
+ return get
681
+
682
+ def __len__(self):
683
+ return len(self.tasks)
684
+
685
+ def __iter__(self):
686
+ return iter(self.tasks)
687
+
688
+ def __repr__(self):
689
+ return f"<TaskSet: {len(self.tasks)} tasks>"
690
+
691
+ def score_submission(self,fn: str, topn=2, return_correct=False) -> int:
692
+ """
693
+ Score a submission file, in Kaggle csv format
694
+ Two columns: output_id,output
695
+ """
696
+ from collections import defaultdict
697
+ preds = defaultdict(list)
698
+
699
+ with open(fn) as f:
700
+ reader = csv.DictReader(f)
701
+ for row in reader:
702
+ task_id, test_num = row['output_id'].split('_')
703
+ test_num = int(test_num)
704
+ assert test_num == len(preds[task_id]), f'Predictions must be in order'
705
+ # Predictions must be in order
706
+
707
+ row_preds = row['output'].strip().split(' ')
708
+ row_preds = row_preds[:topn] # max 3 preds
709
+
710
+ try:
711
+ array_preds = []
712
+ for p in row_preds:
713
+ p = p.strip('|').split('|')
714
+ p = [[int(x) for x in row] for row in p]
715
+ array_preds.append(np.array(p))
716
+ except:
717
+ raise ValueError(f'Could not parse prediction: {row_preds}')
718
+
719
+ preds[task_id].append(array_preds)
720
+
721
+ total_score = 0
722
+ correct = set()
723
+ for task in self.tasks:
724
+ test_examples = task.test
725
+ assert len(test_examples) == len(preds[task.id])
726
+
727
+ score = 0
728
+ for ex, ex_preds in zip(test_examples, preds[task.id]):
729
+ if any([np.array_equal(ex[1], pred) for pred in ex_preds]):
730
+ score += 1
731
+
732
+ if score == len(test_examples):
733
+ total_score += 1
734
+ correct.add(task.id)
735
+
736
+ if return_correct:
737
+ return total_score, correct
738
+ else:
739
+ return total_score
740
+
741
+ def get_data_json(version):
742
+ version = version.lower()
743
+ if version in ['latest', 'arcagi2', 'f3283f7']:
744
+ return json.load(open(f"{os.path.dirname(__file__)}/data/arcagi2_f3283f7.json"))
745
+
746
+ elif version in ['arcagi', 'aa922be', 'arcagi1', 'arc-agi-1', 'arc-agi']:
747
+ return json.load(open(f"{os.path.dirname(__file__)}/data/arcagi_aa922be.json"))
748
+
749
+ elif version in ['kaggle', 'kaggle2025', 'kaggle250808']:
750
+ return json.load(open(f"{os.path.dirname(__file__)}/data/kaggle2025_250808.json"))
751
+
752
+ elif version in ['kaggle2024']:
753
+ return json.load(open(f"{os.path.dirname(__file__)}/data/kaggle2024.json"))
754
+
755
+ elif version in ['arc', 'kaggle2019']:
756
+ return json.load(open(f"{os.path.dirname(__file__)}/data/arc1.json"))
757
+
758
+ else:
759
+ raise ValueError(f"Unknown ARC dataset version: {version}")
760
+
761
+ def load_data(version='latest') -> tuple[TaskSet, TaskSet]:
762
+ """
763
+ Load the ARC dataset from disk. Optionally, specify a specific version of the dataset to load.
764
+ """
765
+
766
+ data = get_data_json(version)
767
+
768
+ train_tasks = []
769
+ eval_tasks = []
770
+ for id, task in data['train'].items():
771
+ train_tasks.append(Task(id, task['train'], task['test'], 'train', version=version))
772
+
773
+ for id, task in data['eval'].items():
774
+ eval_tasks.append(Task(id, task['train'], task['test'], 'eval', version=version))
775
+
776
+ return TaskSet(train_tasks), TaskSet(eval_tasks)
777
+
778
+
779
+ def load_single(id: str, version='latest') -> Task:
780
+ """
781
+ Load a single task from disk. IDs are of the form 'train0', 'eval14', '007bbfb7', etc.
782
+ Note that if iterating through tasks, it is more efficient to use load_data() and index into it.
783
+
784
+ Optionally, specify a specific version of the dataset to load.
785
+ """
786
+
787
+ data = get_data_json(version)
788
+
789
+ # task = data['train'][id]
790
+ # return Task(id, task['train'], task['test'], 'train'
791
+ if id.startswith('train'):
792
+ dataset_tasks = sorted(data['train'].items())
793
+ taskid, task = dataset_tasks[int(id[5:])]
794
+ return Task(taskid, task['train'], task['test'], 'train', version=version)
795
+ elif id.startswith('eval'):
796
+ dataset_tasks = sorted(data['eval'].items())
797
+ taskid, task = dataset_tasks[int(id[4:])]
798
+ return Task(taskid, task['train'], task['test'], 'eval', version=version)
799
+ elif id in data['train']:
800
+ task = data['train'][id]
801
+ return Task(id, task['train'], task['test'], 'train', version=version)
802
+ elif id in data['eval']:
803
+ task = data['eval'][id]
804
+ return Task(id, task['train'], task['test'], 'eval', version=version)
805
+ else:
806
+ raise ValueError(f"Unknown task id: {id}")
807
+
808
+ if __name__ == "__main__":
809
+ train_tasks, eval_tasks = load_data()
810
+ print(train_tasks)
811
+ print(eval_tasks)
812
+ print(train_tasks["007bbfb7"])
813
+ for i in range(10):
814
+ train_tasks[i].show()
815
+
816
+ print(train_tasks["08ed6ac7"].gpt_prompt("gpt3"))
817
+
818
+
819
+
820
+ ================================================
821
+ FILE: arckit/importtool.py
822
+ ================================================
823
+ import glob
824
+ import ujson # dumps minified by default
825
+ import os
826
+ import argparse
827
+
828
+
829
+ def import_arc_agi_2(repo_path, commit_hash):
830
+ train_files = sorted(glob.glob(f'{repo_path}/data/training/*.json'))
831
+ eval_files = sorted(glob.glob(f'{repo_path}/data/evaluation/*.json'))
832
+
833
+ print(f"Found {len(train_files)} train tasks, {len(eval_files)} eval tasks")
834
+
835
+ data = {"train": {}, "eval": {}}
836
+ for json_file in train_files:
837
+ taskname = os.path.basename(json_file).split('.')[0]
838
+ taskdata = ujson.load(open(json_file))
839
+ data['train'][taskname] = taskdata
840
+
841
+ for json_file in eval_files:
842
+ taskname = os.path.basename(json_file).split('.')[0]
843
+ taskdata = ujson.load(open(json_file))
844
+ data['eval'][taskname] = taskdata
845
+
846
+ output_path = f"{os.path.dirname(__file__)}/data/arcagi2_{commit_hash}.json"
847
+
848
+ ujson.dump(data, open(output_path, "w"))
849
+
850
+ def import_kaggle_2025(repo_path, id):
851
+ train_challenges = ujson.load(open(f'{repo_path}/arc-agi_training_challenges.json', 'r'))
852
+ eval_challenges = ujson.load(open(f'{repo_path}/arc-agi_evaluation_challenges.json', 'r'))
853
+ train_solutions = ujson.load(open(f'{repo_path}/arc-agi_training_solutions.json', 'r'))
854
+ eval_solutions = ujson.load(open(f'{repo_path}/arc-agi_evaluation_solutions.json', 'r'))
855
+
856
+ # Populate the solutions into the challenges
857
+ train_data = {}
858
+ for challenge, challenge_data in train_challenges.items():
859
+ challenge_test = train_solutions[challenge]
860
+ for i, test in enumerate(challenge_test):
861
+ challenge_data['test'][i]['output'] = test
862
+
863
+ train_data[challenge] = challenge_data
864
+
865
+ eval_data = {}
866
+ for challenge, challenge_data in eval_challenges.items():
867
+ challenge_test = eval_solutions[challenge]
868
+ for i, test in enumerate(challenge_test):
869
+ challenge_data['test'][i]['output'] = test
870
+
871
+ eval_data[challenge] = challenge_data
872
+
873
+ data = {"train": train_data, "eval": eval_data}
874
+
875
+ output_path = f"{os.path.dirname(__file__)}/data/kaggle2025_{id}.json"
876
+ ujson.dump(data, open(output_path, "w"))
877
+
878
+
879
+ def compare_json(json1="arckit/data/kaggle2025_250808.json", json2="arckit/data/arcagi2_f3283f7.json"):
880
+ json1 = ujson.load(open(json1, "r"))
881
+ json2 = ujson.load(open(json2, "r"))
882
+ assert len(json1['train']) == len(json2['train'])
883
+ assert len(json1['eval']) == len(json2['eval'])
884
+ for k, v in json1['train'].items():
885
+ if k not in json2['train']:
886
+ print(k, "missing")
887
+ if str(json2['train'][k]) != str(v):
888
+ print(k, "not matching")
889
+ for k, v in json2['eval'].items():
890
+ if k not in json1['eval']:
891
+ print(k, "missing")
892
+ if str(json1['eval'][k]) != str(v):
893
+ print(k, "not matching")
894
+ exit()
895
+
896
+ if __name__ == "__main__":
897
+ parser = argparse.ArgumentParser()
898
+ parser.add_argument('--arcagi2', action="store_true")
899
+ parser.add_argument('--kaggle2025', action="store_true")
900
+ parser.add_argument('--repo-path')
901
+ parser.add_argument('--id')
902
+ args = parser.parse_args()
903
+
904
+ if args.arcagi2:
905
+ import_arc_agi_2(args.repo_path, args.id)
906
+ elif args.kaggle2025:
907
+ import_kaggle_2025(args.repo_path, args.id)
908
+ else:
909
+ print("Unknown importer.")
910
+
911
+
912
+ ================================================
913
+ FILE: arckit/vis.py
914
+ ================================================
915
+ import drawsvg
916
+ import numpy as np
917
+ import io
918
+ import rich
919
+
920
+ cmap = [
921
+ '#252525', # black
922
+ '#0074D9', # blue
923
+ '#FF4136', # red
924
+ '#37D449', #2ECC40', # green
925
+ '#FFDC00', # yellow
926
+ '#E6E6E6', # grey
927
+ '#F012BE', # pink
928
+ '#FF871E', # orange
929
+ '#54D2EB', #7FDBFF', # light blue
930
+ '#8D1D2C',#870C25', # brown
931
+ '#FFFFFF'
932
+ ]
933
+
934
+ bg_color = '#EEEFF6' # White
935
+
936
+ def draw_grid(grid, xmax=10, ymax=10, padding=.5, extra_bottom_padding=0.5, group=False, add_size=True, label='', bordercol='#111111ff'):
937
+ """
938
+ Draws a grid,
939
+
940
+ Parameters
941
+ ----------
942
+ grid : np.ndarray
943
+ The grid to draw
944
+ xmax : float, optional
945
+ The maximum horizontal size of the drawing, by default 10
946
+ ymax : float, optional
947
+ The maximum vertical size of the drawing, by default 10
948
+ padding : float, optional
949
+ The padding around the grid, half on each side, by default .5
950
+ extra_bottom_padding : float, optional
951
+ Extra padding at the bottom of the drawing, by default 0.5
952
+ This is used to draw the label
953
+ group : bool, optional
954
+ If enabled, return a drawsvg.Group to include within a bigger drawing
955
+ Otherwise, return a drawsvg.Drawing (default)
956
+ label : str, optional
957
+ A label to draw at the bottom left of the drawing, by default ''
958
+ This does not affect drawing of the size.
959
+ bordercol : str, optional
960
+ The colour of the border, by default '#111111ff'
961
+ """
962
+ # Size is the total size of the LARGER axis.
963
+ # With 0.5 cell padding, we consider the grid to be 1 unit larger than the number of cells
964
+ # padding *= size # padding is proportional
965
+
966
+ gridy, gridx = grid.shape
967
+ # Calculate cell size based on the two restrictions
968
+ # The actual cell size is the minimum of the two
969
+ cellsize_x = xmax / gridx
970
+ cellsize_y = ymax / gridy
971
+ cellsize = min(cellsize_x, cellsize_y)
972
+
973
+ xsize = gridx * cellsize
974
+ ysize = gridy * cellsize
975
+
976
+ line_thickness = 0.01
977
+ circle_radius = 0
978
+ border_width = 0.08
979
+ lt = line_thickness / 2
980
+
981
+ if group:
982
+ drawing = drawsvg.Group()
983
+ else:
984
+ drawing = drawsvg.Drawing(xsize+padding, ysize+padding+extra_bottom_padding, origin=(-0.5*padding, -0.5*padding))
985
+ # Add background rectangle first
986
+ drawing.append(drawsvg.Rectangle(
987
+ -0.5*padding, -0.5*padding, # x, y position with extra padding
988
+ xsize+padding, ysize+padding+extra_bottom_padding, # width, height with padding
989
+ fill=bg_color # background color `bg_color`
990
+ ))
991
+ drawing.set_pixel_scale(40)
992
+ # drawing = drawsvg.Group()
993
+ for j, row in enumerate(grid):
994
+ for i, cell in enumerate(row):
995
+ drawing.append(drawsvg.Rectangle(i*cellsize+lt, j*cellsize+lt, cellsize-lt, cellsize-lt, fill=cmap[cell]))
996
+
997
+ # white dot at each vertex
998
+ if circle_radius > 0:
999
+ for i in range(1, gridx):
1000
+ for j in range(1, gridy):
1001
+ drawing.append(drawsvg.Circle(i*cellsize, j*cellsize, circle_radius, fill='white'))
1002
+
1003
+ # Add a border
1004
+ bw = border_width / 3 # slightly more than 2 to avoid white border
1005
+ drawing.append(drawsvg.Rectangle(-bw, -bw, xsize+bw*2, ysize+bw*2, fill='none', stroke=bordercol, stroke_width=border_width))
1006
+
1007
+ if not group:
1008
+ drawing.embed_google_font('Anuphan:wght@400;600;700', text=set(f'Input Output 0123456789x Test Task ABCDEFGHIJ? abcdefghjklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
1009
+
1010
+ # Write size on the bottom right
1011
+ # drawing.append(drawsvg.Text(text=f'{gridx}x{gridy}', x=-0.05, y=-0.25, font_size=padding/4, fill='black', text_anchor='start'))
1012
+ fontsize = (padding/2 + extra_bottom_padding)/2
1013
+ if add_size:
1014
+ drawing.append(drawsvg.Text(text=f'{gridx}x{gridy}', x=xsize, y=ysize+fontsize*1.25+0, font_size=fontsize, fill='black', text_anchor='end', font_family='Anuphan'))
1015
+ if label:
1016
+ drawing.append(drawsvg.Text(text=label, x=-0.1*fontsize, y=ysize+fontsize*1.25+0, font_size=fontsize, fill='black', text_anchor='start', font_family='Anuphan', font_weight='600'))
1017
+
1018
+ if group:
1019
+ # return group, origin, (xsize, ysize)
1020
+ return drawing, (-0.5*padding, -0.5*padding), (xsize+padding, ysize+padding+extra_bottom_padding)
1021
+ return drawing
1022
+
1023
+ def draw_task(task, width=30, height=12, include_test=False, label=True, bordercols=['#111111ff', '#111111ff'], shortdesc=False):
1024
+ """
1025
+ Plot an entire task vertically, fitting the desired dimensions.
1026
+ The output is displayed below the input, with an arrow in between.
1027
+
1028
+ Note that dimensions are a best effort, you should check .width and .height on the output
1029
+
1030
+ Parameters
1031
+ ----------
1032
+ task : Task
1033
+ The task to plot
1034
+ width : float, optional
1035
+ The desired width of the drawing, by default 30
1036
+ height : float, optional
1037
+ The desired height of the drawing, by default 12
1038
+ include_test : bool, optional
1039
+ If enabled, include the test examples in the plot, by default False
1040
+ If set to 'all', ALSO include the output of the test examples
1041
+ label: bool, default True
1042
+ bordercols: list of str, default None
1043
+ """
1044
+
1045
+ padding = 0.5
1046
+ bonus_padding = 0.25
1047
+ io_gap = 0.4
1048
+ ymax = (height - padding - bonus_padding - io_gap)/2
1049
+
1050
+ if include_test:
1051
+ examples = task.train + task.test
1052
+ else:
1053
+ examples = task.train
1054
+ n_train = len(task.train)
1055
+ paddingless_width = width - padding * len(examples)
1056
+
1057
+ max_widths = np.zeros(len(examples))
1058
+ # If any examples would exceed the height restriction, scale their width down and redistribute the space
1059
+ for i, (input_grid, output_grid) in enumerate(examples):
1060
+ input_grid_ratio = input_grid.shape[1] / input_grid.shape[0]
1061
+ output_grid_ratio = output_grid.shape[1] / output_grid.shape[0]
1062
+ max_ratio = max(input_grid_ratio, output_grid_ratio) # could be min
1063
+ xmax = ymax * max_ratio
1064
+ max_widths[i] = xmax
1065
+
1066
+ # Allocate paddingless width to each example
1067
+ allocation = np.zeros_like(max_widths)
1068
+ increment = 0.01
1069
+ for i in range(int(paddingless_width//increment)):
1070
+ incr = (allocation + increment) <= max_widths
1071
+ allocation[incr] += increment / incr.sum()
1072
+
1073
+ drawlist = []
1074
+ x_ptr = 0
1075
+ y_ptr = 0
1076
+ for i, (input_grid, output_grid) in enumerate(examples):
1077
+ if shortdesc:
1078
+ if i >= n_train:
1079
+ input_label = ''#f'T{i-n_train+1}'
1080
+ output_label = ''#f'T{i-n_train+1}'
1081
+ else:
1082
+ input_label = ''#f'I{i+1}'
1083
+ output_label = ''#f'O{i+1}'
1084
+ else:
1085
+ if i >= n_train:
1086
+ input_label = f'Test {i-n_train+1}'
1087
+ output_label = f'Test {i-n_train+1}'
1088
+ else:
1089
+ input_label = f'Input {i+1}'
1090
+ output_label = f'Output {i+1}'
1091
+
1092
+ # input_label, output_label = '', ''
1093
+
1094
+ input_grid, offset, (input_x, input_y) = draw_grid(input_grid, padding=padding, xmax=allocation[i], ymax=ymax, group=True, label=input_label, extra_bottom_padding=0.5, bordercol=bordercols[0])
1095
+ output_grid, offset, (output_x, output_y) = draw_grid(output_grid, padding=padding, xmax=allocation[i], ymax=ymax, group=True, label=output_label, extra_bottom_padding=0.5, bordercol=bordercols[1])
1096
+
1097
+ drawlist.append(drawsvg.Use(input_grid, x=x_ptr + (allocation[i]+padding-input_x)/2 - offset[0], y=-offset[1]))
1098
+ # drawlist.append(drawsvg.Use(output_grid, x=x_ptr + (allocation[i]+padding-output_x)/2 - offset[0], y=ymax-offset[1]+2))
1099
+ x_ptr += max(input_x, output_x)
1100
+ y_ptr = max(y_ptr, input_y)
1101
+
1102
+ x_ptr = 0
1103
+ y_ptr2 = 0
1104
+ for i, (input_grid, output_grid) in enumerate(examples):
1105
+ if shortdesc:
1106
+ if i >= n_train:
1107
+ input_label = ''#f'T{i-n_train+1}'
1108
+ output_label = ''#f'T{i-n_train+1}'
1109
+ else:
1110
+ input_label = ''#f'I{i+1}'
1111
+ output_label = ''#f'O{i+1}'
1112
+ else:
1113
+ if i >= n_train:
1114
+ input_label = f'Test {i-n_train+1}'
1115
+ output_label = f'Test {i-n_train+1}'
1116
+ else:
1117
+ input_label = f'Input {i+1}'
1118
+ output_label = f'Output {i+1}'
1119
+ # input_label, output_label = '', ''
1120
+
1121
+ input_grid, offset, (input_x, input_y) = draw_grid(input_grid, padding=padding, xmax=allocation[i], ymax=ymax, group=True, label=input_label, extra_bottom_padding=0.5, bordercol=bordercols[0])
1122
+ output_grid, offset, (output_x, output_y) = draw_grid(output_grid, padding=padding, xmax=allocation[i], ymax=ymax, group=True, label=output_label, extra_bottom_padding=0.5, bordercol=bordercols[1])
1123
+ # Down arrow
1124
+ drawlist.append(drawsvg.Line(
1125
+ x_ptr + input_x/2,
1126
+ y_ptr + padding - 0.6,
1127
+ x_ptr + input_x/2,
1128
+ y_ptr + padding + io_gap - 0.6,
1129
+ stroke_width=0.05, stroke='#888888'))
1130
+ drawlist.append(drawsvg.Line(
1131
+ x_ptr + input_x/2 - 0.15,
1132
+ y_ptr + padding + io_gap - 0.8,
1133
+ x_ptr + input_x/2,
1134
+ y_ptr + padding + io_gap - 0.6,
1135
+ stroke_width=0.05, stroke='#888888'))
1136
+ drawlist.append(drawsvg.Line(
1137
+ x_ptr + input_x/2 + 0.15,
1138
+ y_ptr + padding + io_gap - 0.8,
1139
+ x_ptr + input_x/2,
1140
+ y_ptr + padding + io_gap - 0.6,
1141
+ stroke_width=0.05, stroke='#888888'))
1142
+
1143
+
1144
+ if i < n_train or include_test == 'all':
1145
+ drawlist.append(drawsvg.Use(output_grid, x=x_ptr + (allocation[i]+padding-output_x)/2 - offset[0], y=y_ptr-offset[1]+io_gap))
1146
+ else:
1147
+ # Add a question mark
1148
+ drawlist.append(drawsvg.Text(
1149
+ '?',
1150
+ x=x_ptr + (allocation[i]+padding)/2,
1151
+ y=y_ptr + output_y/2+bonus_padding,
1152
+ font_size=1,
1153
+ font_family='Anuphan',
1154
+ font_weight='700',
1155
+ fill='#333333',
1156
+ text_anchor='middle',
1157
+ alignment_baseline='middle',
1158
+ ))
1159
+ x_ptr += max(input_x, output_x)
1160
+ y_ptr2 = max(y_ptr2, y_ptr+output_y+io_gap)
1161
+
1162
+ x_ptr = round(x_ptr, 1)
1163
+ y_ptr2 = round(y_ptr2, 1)
1164
+ d = drawsvg.Drawing(x_ptr, y_ptr2+0.2, origin=(0, 0))
1165
+ d.append(drawsvg.Rectangle(0, 0, '100%', '100%', fill='#eeeff6'))
1166
+ d.embed_google_font('Anuphan:wght@400;600;700', text=set(f'Input Output 0123456789x Test Task ABCDEFGHIJ? abcdefghjklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
1167
+ for item in drawlist:
1168
+ d.append(item)
1169
+
1170
+ fontsize=0.3
1171
+ d.append(drawsvg.Text(f"Task {task.id}", x=x_ptr-0.1, y=y_ptr2+0.1, font_size=fontsize, font_family='Anuphan', font_weight='600', fill='#666666', text_anchor='end', alignment_baseline='bottom'))
1172
+
1173
+ d.set_pixel_scale(40)
1174
+ return d
1175
+
1176
+ def output_drawing(d: drawsvg.Drawing, filename: str, context=None):
1177
+ if filename.endswith('.svg'):
1178
+ d.save_svg(filename)
1179
+ elif filename.endswith('.png'):
1180
+ d.save_png(filename)
1181
+ elif filename.endswith('.pdf'):
1182
+ buffer = io.StringIO()
1183
+ d.as_svg(output_file=buffer, context=context)
1184
+
1185
+ import cairosvg
1186
+ cairosvg.svg2pdf(bytestring=buffer.getvalue(), write_to=filename)
1187
+ else:
1188
+ raise ValueError(f'Unknown file extension for {filename}')
1189
+
1190
+ def print_grid(grid: np.ndarray):
1191
+ """
1192
+ Print a grid to the terminal using rich library
1193
+
1194
+ Parameters
1195
+ ----------
1196
+ grid : np.ndarray
1197
+ the standard grid format for Task
1198
+ """
1199
+ CELL_WIDTH = 2
1200
+
1201
+ def get_color(color_str):
1202
+ color_str = color_str.strip('#')
1203
+ return rich.color.Color.from_rgb(*bytes.fromhex(color_str))
1204
+
1205
+ # Translate 'cmap' to rich style with respective color as background
1206
+ rich_scmap = {
1207
+ i: rich.style.Style(bgcolor=get_color(color))
1208
+ for i, color in enumerate(cmap)
1209
+ }
1210
+
1211
+ # Create and populate rich table
1212
+ table = rich.table.Table.grid(expand=False)
1213
+
1214
+ height, width = grid.shape
1215
+
1216
+ # Add columns
1217
+ for x in range(width):
1218
+ table.add_column()
1219
+ table.columns[x]._cells = [''] * height
1220
+
1221
+ table.rows = [rich.table.Row()] * height
1222
+
1223
+ # Populate cells
1224
+ for y in range(height):
1225
+ for x in range(width):
1226
+ color_idx = grid[y, x]
1227
+ table.columns[x]._cells[y] = rich.text.Text(' ' * CELL_WIDTH, style=rich_scmap[color_idx])
1228
+
1229
+ rich.print(table)
1230
+
1231
+
1232
+
1233
+ ================================================
1234
+ FILE: .github/workflows/pypi.yml
1235
+ ================================================
1236
+ name: Build & Release
1237
+
1238
+ on:
1239
+ workflow_dispatch:
1240
+ inputs:
1241
+ environment:
1242
+ description: 'Choose PyPI environment'
1243
+ required: true
1244
+ default: 'test'
1245
+ type: choice
1246
+ options:
1247
+ - test
1248
+ - production
1249
+ push:
1250
+
1251
+ jobs:
1252
+ build:
1253
+ name: Build wheel
1254
+ runs-on: ubuntu-latest
1255
+ steps:
1256
+ - name: Checkout
1257
+ uses: actions/checkout@v4
1258
+
1259
+ - name: Set up Python
1260
+ uses: actions/setup-python@v5
1261
+ with:
1262
+ python-version: ${{ inputs.python_version || '3.11' }}
1263
+
1264
+ - name: Install build backend
1265
+ run: |
1266
+ python -m pip install --upgrade pip
1267
+ python -m pip install build
1268
+
1269
+ - name: Build dists
1270
+ run: |
1271
+ python -m build
1272
+
1273
+ - name: Upload dists artifact
1274
+ uses: actions/upload-artifact@v4
1275
+ with:
1276
+ name: dist
1277
+ path: dist/
1278
+
1279
+ publish:
1280
+ name: Publish to PyPI
1281
+ needs: build
1282
+ runs-on: ubuntu-latest
1283
+ permissions:
1284
+ id-token: write
1285
+ if: github.event_name == 'workflow_dispatch'
1286
+ steps:
1287
+ - name: Download dists artifact
1288
+ uses: actions/download-artifact@v4
1289
+ with:
1290
+ name: dist
1291
+ path: dist/
1292
+
1293
+ - name: Publish to TestPyPI
1294
+ if: inputs.environment == 'test'
1295
+ uses: pypa/gh-action-pypi-publish@release/v1
1296
+ with:
1297
+ repository-url: https://test.pypi.org/legacy/
1298
+
1299
+ - name: Publish to Production PyPI
1300
+ if: inputs.environment == 'production'
1301
+ uses: pypa/gh-action-pypi-publish@release/v1
1302
+