Update original Skills Desk tasks
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- LICENSES/README.txt +0 -1
- MANIFEST.json +122 -210
- README.md +4 -4
- SHA256SUMS +47 -69
- SOURCE_LOCK.json +4 -4
- components/dnakhla/.dockerignore +0 -5
- components/dnakhla/Dockerfile +0 -8
- components/dnakhla/NOTICE +0 -4
- components/dnakhla/README.md +0 -5
- components/dnakhla/SOURCE_MANIFEST.json +0 -66
- components/dnakhla/runtime/dnakhla_compat/__init__.py +0 -1
- components/dnakhla/upstream/terminal_desk/families/__init__.py +0 -21
- components/dnakhla/upstream/terminal_desk/families/finance.py +0 -228
- components/dnakhla/upstream/terminal_desk/families/finance3.py +0 -428
- components/dnakhla/upstream/terminal_desk/families/industrial.py +0 -194
- components/dnakhla/upstream/terminal_desk/families/industrial3.py +0 -470
- components/dnakhla/upstream/terminal_desk/families/mathematics.py +0 -177
- components/dnakhla/upstream/terminal_desk/families/mathematics3.py +0 -471
- components/dnakhla/upstream/terminal_desk/families/media.py +0 -180
- components/dnakhla/upstream/terminal_desk/families/media3.py +0 -557
- components/dnakhla/upstream/terminal_desk/families/office.py +0 -234
- components/dnakhla/upstream/terminal_desk/families/office3.py +0 -505
- components/dnakhla/upstream/terminal_desk/families/science.py +0 -250
- components/dnakhla/upstream/terminal_desk/families/science3.py +0 -452
- components/dnakhla/upstream/terminal_desk/families/security.py +0 -224
- components/dnakhla/upstream/terminal_desk/families/security3.py +0 -521
- components/dnakhla/upstream/terminal_desk/families/software3.py +0 -665
- components/dnakhla/upstream/terminal_desk/oracles/__init__.py +0 -40
- components/dnakhla/upstream/terminal_desk/oracles/fin3_invoice_fraud.py +0 -34
- components/dnakhla/upstream/terminal_desk/oracles/fin3_loan_schedule.py +0 -55
- components/dnakhla/upstream/terminal_desk/oracles/fin3_portfolio_value.py +0 -42
- components/dnakhla/upstream/terminal_desk/oracles/ind3_service_due.py +0 -47
- components/dnakhla/upstream/terminal_desk/oracles/ind3_stl_mass.py +0 -42
- components/dnakhla/upstream/terminal_desk/oracles/ind3_tank_balance.py +0 -50
- components/dnakhla/upstream/terminal_desk/oracles/math3_count_items.py +0 -32
- components/dnakhla/upstream/terminal_desk/oracles/math3_exam_slots.py +0 -50
- components/dnakhla/upstream/terminal_desk/oracles/math3_route_plan.py +0 -48
- components/dnakhla/upstream/terminal_desk/oracles/med3_silence_report.py +0 -44
- components/dnakhla/upstream/terminal_desk/oracles/med3_sprite_count.py +0 -44
- components/dnakhla/upstream/terminal_desk/oracles/med3_subtitle_retime.py +0 -43
- components/dnakhla/upstream/terminal_desk/oracles/off3_ar_recon.py +0 -39
- components/dnakhla/upstream/terminal_desk/oracles/off3_meeting_slot.py +0 -44
- components/dnakhla/upstream/terminal_desk/oracles/off3_pdf_xlsx_diff.py +0 -36
- components/dnakhla/upstream/terminal_desk/oracles/sci3_kinetics_fit.py +0 -38
- components/dnakhla/upstream/terminal_desk/oracles/sci3_lightcurve_period.py +0 -38
- components/dnakhla/upstream/terminal_desk/oracles/sci3_stoich_batch.py +0 -46
- components/dnakhla/upstream/terminal_desk/oracles/sec3_auth_triage.py +0 -37
- components/dnakhla/upstream/terminal_desk/oracles/sec3_exfil_flows.py +0 -35
- components/dnakhla/upstream/terminal_desk/oracles/sec3_fw_verdicts.py +0 -49
- components/dnakhla/upstream/terminal_desk/oracles/sw3_dep_lock.py +0 -51
LICENSES/README.txt
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
Terminal Desk declares Apache-2.0. The standard license text was added by this distribution; see components/dnakhla/LICENSE and NOTICE for attribution.
|
|
|
|
|
|
MANIFEST.json
CHANGED
|
@@ -1,284 +1,196 @@
|
|
| 1 |
{
|
| 2 |
"files": {
|
| 3 |
-
"LICENSES/README.txt": {
|
| 4 |
-
"bytes": 152,
|
| 5 |
-
"sha256": "73b6e48016e027d623e5b6e03c4a6eae26ea366447f10cc09d6a7f06bfef8913"
|
| 6 |
-
},
|
| 7 |
"README.md": {
|
| 8 |
-
"bytes":
|
| 9 |
-
"sha256": "
|
| 10 |
},
|
| 11 |
"SOURCE_LOCK.json": {
|
| 12 |
-
"bytes":
|
| 13 |
-
"sha256": "
|
| 14 |
},
|
| 15 |
-
"components/
|
| 16 |
-
"bytes":
|
| 17 |
-
"sha256": "
|
| 18 |
},
|
| 19 |
-
"components/
|
| 20 |
-
"bytes":
|
| 21 |
-
"sha256": "
|
| 22 |
},
|
| 23 |
-
"components/
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
"bytes": 11358,
|
| 25 |
"sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"
|
| 26 |
},
|
| 27 |
-
"components/
|
| 28 |
-
"bytes":
|
| 29 |
-
"sha256": "
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
},
|
| 31 |
-
"components/
|
| 32 |
-
"bytes":
|
| 33 |
-
"sha256": "
|
| 34 |
},
|
| 35 |
-
"components/
|
| 36 |
-
"bytes":
|
| 37 |
-
"sha256": "
|
| 38 |
},
|
| 39 |
-
"components/
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
"bytes": 1,
|
| 41 |
"sha256": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b"
|
| 42 |
},
|
| 43 |
-
"components/
|
| 44 |
"bytes": 1015,
|
| 45 |
"sha256": "b1e1429208e84aefc2422ee1d2400ad793c43cd5c0e8db213a3b669fe0947ce1"
|
| 46 |
},
|
| 47 |
-
"components/
|
| 48 |
"bytes": 1941,
|
| 49 |
"sha256": "6a1ac8e55af6168d3fdd6b17c700a15cf0546b6154773aa3c59c97d6bffa2ffd"
|
| 50 |
},
|
| 51 |
-
"components/
|
| 52 |
-
"bytes":
|
| 53 |
-
"sha256": "
|
| 54 |
},
|
| 55 |
-
"components/
|
| 56 |
-
"bytes":
|
| 57 |
-
"sha256": "
|
| 58 |
},
|
| 59 |
-
"components/
|
| 60 |
-
"bytes":
|
| 61 |
-
"sha256": "
|
| 62 |
},
|
| 63 |
-
"components/
|
| 64 |
-
"bytes":
|
| 65 |
-
"sha256": "
|
| 66 |
},
|
| 67 |
-
"components/
|
| 68 |
"bytes": 0,
|
| 69 |
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
| 70 |
},
|
| 71 |
-
"components/
|
| 72 |
"bytes": 0,
|
| 73 |
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
| 74 |
},
|
| 75 |
-
"components/
|
| 76 |
-
"bytes":
|
| 77 |
-
"sha256": "
|
| 78 |
-
},
|
| 79 |
-
"components/dnakhla/upstream/terminal_desk/core/shell.py": {
|
| 80 |
-
"bytes": 5014,
|
| 81 |
-
"sha256": "59b4b07b0d59e01792c8dbbf7877555e2da2346ddf5d2c17df3bbd4e17cb847f"
|
| 82 |
},
|
| 83 |
-
"components/
|
| 84 |
-
"bytes":
|
| 85 |
-
"sha256": "
|
| 86 |
-
},
|
| 87 |
-
"components/dnakhla/upstream/terminal_desk/families/base.py": {
|
| 88 |
-
"bytes": 2632,
|
| 89 |
-
"sha256": "d76cab459096d3748d2c4198753853d85418de61f64436cf4772b89345fdcf17"
|
| 90 |
-
},
|
| 91 |
-
"components/dnakhla/upstream/terminal_desk/families/finance.py": {
|
| 92 |
-
"bytes": 9887,
|
| 93 |
-
"sha256": "312a26e2d48ac10a07716384d3059a697f75f16e5b37fcabb8c07fcac3397f6f"
|
| 94 |
-
},
|
| 95 |
-
"components/dnakhla/upstream/terminal_desk/families/finance3.py": {
|
| 96 |
-
"bytes": 23433,
|
| 97 |
-
"sha256": "a4839540c7a54198ea8e480248428e9ca65bdaf45adea5ae9f81cad71cbb1311"
|
| 98 |
},
|
| 99 |
-
"components/
|
| 100 |
-
"bytes":
|
| 101 |
-
"sha256": "
|
| 102 |
},
|
| 103 |
-
"components/
|
| 104 |
-
"bytes":
|
| 105 |
-
"sha256": "
|
| 106 |
},
|
| 107 |
-
"components/
|
| 108 |
-
"bytes":
|
| 109 |
-
"sha256": "
|
| 110 |
},
|
| 111 |
-
"components/
|
| 112 |
-
"bytes":
|
| 113 |
-
"sha256": "
|
| 114 |
},
|
| 115 |
-
"components/
|
| 116 |
-
"bytes":
|
| 117 |
-
"sha256": "
|
| 118 |
},
|
| 119 |
-
"components/
|
| 120 |
-
"bytes":
|
| 121 |
-
"sha256": "
|
| 122 |
},
|
| 123 |
-
"components/
|
| 124 |
-
"bytes":
|
| 125 |
-
"sha256": "
|
| 126 |
},
|
| 127 |
-
"components/
|
| 128 |
-
"bytes":
|
| 129 |
-
"sha256": "
|
| 130 |
},
|
| 131 |
-
"components/
|
| 132 |
-
"bytes":
|
| 133 |
-
"sha256": "
|
| 134 |
},
|
| 135 |
-
"components/
|
| 136 |
-
"bytes":
|
| 137 |
-
"sha256": "
|
| 138 |
},
|
| 139 |
-
"components/
|
| 140 |
-
"bytes":
|
| 141 |
-
"sha256": "
|
| 142 |
},
|
| 143 |
-
"components/
|
| 144 |
-
"bytes":
|
| 145 |
-
"sha256": "
|
| 146 |
},
|
| 147 |
-
"components/
|
| 148 |
-
"bytes":
|
| 149 |
-
"sha256": "
|
| 150 |
},
|
| 151 |
-
"components/
|
| 152 |
-
"bytes": 31784,
|
| 153 |
-
"sha256": "d526ae88ca53ef22dbc1e578055fc27ebb491c184474e662736b8be9523086a7"
|
| 154 |
-
},
|
| 155 |
-
"components/dnakhla/upstream/terminal_desk/models.py": {
|
| 156 |
"bytes": 1750,
|
| 157 |
"sha256": "f31264b0909878c6f2d4d18a270c7d92bc895052150c56e5ac3e6b38d4ceebb4"
|
| 158 |
},
|
| 159 |
-
"components/
|
| 160 |
-
"bytes":
|
| 161 |
-
"sha256": "
|
| 162 |
-
},
|
| 163 |
-
"components/dnakhla/upstream/terminal_desk/oracles/fin3_invoice_fraud.py": {
|
| 164 |
-
"bytes": 1162,
|
| 165 |
-
"sha256": "975ff8045d42b2f483924e368e304c451bca894ddb4ba593d9dd3aea1c505329"
|
| 166 |
-
},
|
| 167 |
-
"components/dnakhla/upstream/terminal_desk/oracles/fin3_loan_schedule.py": {
|
| 168 |
-
"bytes": 1752,
|
| 169 |
-
"sha256": "b0a32266ec725f5a4f76d8b40a27fc52759f679d74e4dfe5c7885a1b19a36711"
|
| 170 |
-
},
|
| 171 |
-
"components/dnakhla/upstream/terminal_desk/oracles/fin3_portfolio_value.py": {
|
| 172 |
-
"bytes": 1729,
|
| 173 |
-
"sha256": "152a3516b9ec6811121747ea875fc1a73cb768ba6a98e05c2bee91325e4f7247"
|
| 174 |
-
},
|
| 175 |
-
"components/dnakhla/upstream/terminal_desk/oracles/ind3_service_due.py": {
|
| 176 |
-
"bytes": 1819,
|
| 177 |
-
"sha256": "47914a6e1a5bde126ce301bc11d4dc95b11cb0910ac0208a4c78596d7e65e30e"
|
| 178 |
-
},
|
| 179 |
-
"components/dnakhla/upstream/terminal_desk/oracles/ind3_stl_mass.py": {
|
| 180 |
-
"bytes": 1562,
|
| 181 |
-
"sha256": "53e6adc26768256ce6665bda20c4b04ad87602e24eb31b074c25dc8fbbc00653"
|
| 182 |
-
},
|
| 183 |
-
"components/dnakhla/upstream/terminal_desk/oracles/ind3_tank_balance.py": {
|
| 184 |
-
"bytes": 1573,
|
| 185 |
-
"sha256": "c1049fdb6b4f11f0b5e0194b41e84b525d5a340213c2c94f5f99ffd6c2b75a42"
|
| 186 |
-
},
|
| 187 |
-
"components/dnakhla/upstream/terminal_desk/oracles/math3_count_items.py": {
|
| 188 |
-
"bytes": 1005,
|
| 189 |
-
"sha256": "0fd62812cd9ef1d5be6d6ae9fa2fa047eb6bb0a4508ccb5a5369373aefbf8dd3"
|
| 190 |
-
},
|
| 191 |
-
"components/dnakhla/upstream/terminal_desk/oracles/math3_exam_slots.py": {
|
| 192 |
-
"bytes": 1770,
|
| 193 |
-
"sha256": "03908ec43159f4a66678f37fb0366389608eeeba41361758d966c96eea50dc3f"
|
| 194 |
-
},
|
| 195 |
-
"components/dnakhla/upstream/terminal_desk/oracles/math3_route_plan.py": {
|
| 196 |
-
"bytes": 1686,
|
| 197 |
-
"sha256": "c2bb32b08a3705a4be56ff8c4e3af94d64441c9a7432f5dcec4dce0b378ee465"
|
| 198 |
-
},
|
| 199 |
-
"components/dnakhla/upstream/terminal_desk/oracles/med3_silence_report.py": {
|
| 200 |
-
"bytes": 1602,
|
| 201 |
-
"sha256": "554e36455da66fd258e6ad2c39e80acbc3856237fee4608ce57b494f23c3d16d"
|
| 202 |
-
},
|
| 203 |
-
"components/dnakhla/upstream/terminal_desk/oracles/med3_sprite_count.py": {
|
| 204 |
-
"bytes": 1517,
|
| 205 |
-
"sha256": "8f0a1169d6e5b10c4981b53a22e957c4befad44d95e5d250cf53734105a40256"
|
| 206 |
-
},
|
| 207 |
-
"components/dnakhla/upstream/terminal_desk/oracles/med3_subtitle_retime.py": {
|
| 208 |
-
"bytes": 1494,
|
| 209 |
-
"sha256": "72f448ba58ac9ee6082692dec88ddb6f279ae69bdb99d39b30d1acce12c19bfe"
|
| 210 |
-
},
|
| 211 |
-
"components/dnakhla/upstream/terminal_desk/oracles/off3_ar_recon.py": {
|
| 212 |
-
"bytes": 1454,
|
| 213 |
-
"sha256": "b5320a71696443f1b04c0c5e02e35d0baee67a175a912bff86e32df7c2acb357"
|
| 214 |
-
},
|
| 215 |
-
"components/dnakhla/upstream/terminal_desk/oracles/off3_meeting_slot.py": {
|
| 216 |
-
"bytes": 1711,
|
| 217 |
-
"sha256": "6eef5e15337e5029c8e0b3353adee791ea9ebe73c6d79e47d84d6b7294cb5a38"
|
| 218 |
-
},
|
| 219 |
-
"components/dnakhla/upstream/terminal_desk/oracles/off3_pdf_xlsx_diff.py": {
|
| 220 |
-
"bytes": 1301,
|
| 221 |
-
"sha256": "82b5c15f02a03615699429a2342dbad4b8985aab76d82fa8a8b96f7fbebc544f"
|
| 222 |
-
},
|
| 223 |
-
"components/dnakhla/upstream/terminal_desk/oracles/sci3_kinetics_fit.py": {
|
| 224 |
-
"bytes": 1527,
|
| 225 |
-
"sha256": "1ebc19667bf1963c83a47bd4905e99e0c32c3ce249b63ae2d7b39fcffa1b1bb7"
|
| 226 |
-
},
|
| 227 |
-
"components/dnakhla/upstream/terminal_desk/oracles/sci3_lightcurve_period.py": {
|
| 228 |
-
"bytes": 1540,
|
| 229 |
-
"sha256": "a983fb3c03ba15bc0591ab32ce41ddb99f2f38329e273f3f5da20f775d6bd8ab"
|
| 230 |
-
},
|
| 231 |
-
"components/dnakhla/upstream/terminal_desk/oracles/sci3_stoich_batch.py": {
|
| 232 |
-
"bytes": 1747,
|
| 233 |
-
"sha256": "56a84763e746f034571dc50a71f3716f340e4f8d9dee823eb3c9b209f471f48a"
|
| 234 |
-
},
|
| 235 |
-
"components/dnakhla/upstream/terminal_desk/oracles/sec3_auth_triage.py": {
|
| 236 |
-
"bytes": 1443,
|
| 237 |
-
"sha256": "c5fb5f697e8cfdb6008fcd59d6c3095a509d9a488dc28d7b99da4f4fe128b8a6"
|
| 238 |
},
|
| 239 |
-
"components/
|
| 240 |
-
"bytes":
|
| 241 |
-
"sha256": "
|
| 242 |
},
|
| 243 |
-
"components/
|
| 244 |
-
"bytes":
|
| 245 |
-
"sha256": "
|
| 246 |
},
|
| 247 |
-
"components/
|
| 248 |
-
"bytes":
|
| 249 |
-
"sha256": "
|
| 250 |
},
|
| 251 |
-
"components/
|
| 252 |
-
"bytes":
|
| 253 |
-
"sha256": "
|
| 254 |
},
|
| 255 |
-
"components/
|
| 256 |
-
"bytes":
|
| 257 |
-
"sha256": "
|
| 258 |
},
|
| 259 |
-
"components/
|
| 260 |
"bytes": 0,
|
| 261 |
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
| 262 |
},
|
| 263 |
-
"components/
|
| 264 |
"bytes": 802,
|
| 265 |
"sha256": "6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8"
|
| 266 |
},
|
| 267 |
-
"components/
|
| 268 |
-
"bytes":
|
| 269 |
-
"sha256": "
|
| 270 |
},
|
| 271 |
"schema.json": {
|
| 272 |
"bytes": 1911,
|
| 273 |
"sha256": "10993deaaa8553929fa0b3b6bf3c1ad100baaaf9ff10ae8ed139a8ec4279a3c4"
|
| 274 |
},
|
| 275 |
"tasks.jsonl": {
|
| 276 |
-
"bytes":
|
| 277 |
-
"sha256": "
|
| 278 |
},
|
| 279 |
"validate_dataset.py": {
|
| 280 |
-
"bytes":
|
| 281 |
-
"sha256": "
|
| 282 |
}
|
| 283 |
}
|
| 284 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"files": {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
"README.md": {
|
| 4 |
+
"bytes": 966,
|
| 5 |
+
"sha256": "bd0d465f995e6e88f99a624901bbf6577b31c7230a4ff959ca48516be0339af7"
|
| 6 |
},
|
| 7 |
"SOURCE_LOCK.json": {
|
| 8 |
+
"bytes": 328,
|
| 9 |
+
"sha256": "df3acef0a949edac8c6ec87a15e4d7c5a87534a83d49186549699a59bdf22f98"
|
| 10 |
},
|
| 11 |
+
"components/skillsdesk/.dockerignore": {
|
| 12 |
+
"bytes": 29,
|
| 13 |
+
"sha256": "60c9bdd905fcf45ac485c680d32e9773962cf061b6f041dcddd033911558a672"
|
| 14 |
},
|
| 15 |
+
"components/skillsdesk/ADAPTER_NOTICE": {
|
| 16 |
+
"bytes": 167,
|
| 17 |
+
"sha256": "843b71a3a9f9de899cbb9d260d55c9bd082f3df2b7771a1c31100ce5767a0a53"
|
| 18 |
},
|
| 19 |
+
"components/skillsdesk/Dockerfile": {
|
| 20 |
+
"bytes": 1010,
|
| 21 |
+
"sha256": "4f047d60bc07987131be2c9cf0662c6e6feef91125adda81eda04d4b88882f6b"
|
| 22 |
+
},
|
| 23 |
+
"components/skillsdesk/LICENSE": {
|
| 24 |
"bytes": 11358,
|
| 25 |
"sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"
|
| 26 |
},
|
| 27 |
+
"components/skillsdesk/NOTICE": {
|
| 28 |
+
"bytes": 676,
|
| 29 |
+
"sha256": "dca813e02ab76d4bc5afdcd2a2de3480d3fc0a7a710edea24c395adf23a99883"
|
| 30 |
+
},
|
| 31 |
+
"components/skillsdesk/README.md": {
|
| 32 |
+
"bytes": 303,
|
| 33 |
+
"sha256": "11775067d2cfb4c254084dd741f0b13a1a5058081c171712bdb9923d430a9cd4"
|
| 34 |
},
|
| 35 |
+
"components/skillsdesk/SOURCE_MANIFEST.json": {
|
| 36 |
+
"bytes": 3982,
|
| 37 |
+
"sha256": "789ef47ecb391dfe876f65207ba8f477b064c1d9cded1becaf177ae7112a3d99"
|
| 38 |
},
|
| 39 |
+
"components/skillsdesk/UPSTREAM_DOCKERFILE": {
|
| 40 |
+
"bytes": 1899,
|
| 41 |
+
"sha256": "2c07033febd78777deeff04350ae6887c9bb170b152d38c26cf148efa1b75d1e"
|
| 42 |
},
|
| 43 |
+
"components/skillsdesk/UPSTREAM_TRAINING_TASKS.txt": {
|
| 44 |
+
"bytes": 666,
|
| 45 |
+
"sha256": "90e6e08d4269b5bb8308b5f2f05c61aa0cb9b71643b6abe6e47b34795828dd1e"
|
| 46 |
+
},
|
| 47 |
+
"components/skillsdesk/runtime/common/__init__.py": {
|
| 48 |
"bytes": 1,
|
| 49 |
"sha256": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b"
|
| 50 |
},
|
| 51 |
+
"components/skillsdesk/runtime/common/contracts.py": {
|
| 52 |
"bytes": 1015,
|
| 53 |
"sha256": "b1e1429208e84aefc2422ee1d2400ad793c43cd5c0e8db213a3b669fe0947ce1"
|
| 54 |
},
|
| 55 |
+
"components/skillsdesk/runtime/common/models.py": {
|
| 56 |
"bytes": 1941,
|
| 57 |
"sha256": "6a1ac8e55af6168d3fdd6b17c700a15cf0546b6154773aa3c59c97d6bffa2ffd"
|
| 58 |
},
|
| 59 |
+
"components/skillsdesk/runtime/skillsdesk_compat/__init__.py": {
|
| 60 |
+
"bytes": 0,
|
| 61 |
+
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
| 62 |
},
|
| 63 |
+
"components/skillsdesk/runtime/skillsdesk_compat/environment.py": {
|
| 64 |
+
"bytes": 8142,
|
| 65 |
+
"sha256": "22a0011808344bdeeb635082afbacac2810bdf14e617ac72011e211dfa14c176"
|
| 66 |
},
|
| 67 |
+
"components/skillsdesk/runtime/skillsdesk_compat/server.py": {
|
| 68 |
+
"bytes": 457,
|
| 69 |
+
"sha256": "634fd3bd58cb4ade2c5d959ae7fb09dfb24b102830170c00a140a3ff949e590c"
|
| 70 |
},
|
| 71 |
+
"components/skillsdesk/upstream/openenv.yaml": {
|
| 72 |
+
"bytes": 403,
|
| 73 |
+
"sha256": "88e8863954ec9a9d34d07cdde0d5d4688f1fc85a2c595f13c7b9d4d10be6218e"
|
| 74 |
},
|
| 75 |
+
"components/skillsdesk/upstream/terminal_desk/__init__.py": {
|
| 76 |
"bytes": 0,
|
| 77 |
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
| 78 |
},
|
| 79 |
+
"components/skillsdesk/upstream/terminal_desk/core/__init__.py": {
|
| 80 |
"bytes": 0,
|
| 81 |
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
| 82 |
},
|
| 83 |
+
"components/skillsdesk/upstream/terminal_desk/core/grading.py": {
|
| 84 |
+
"bytes": 10754,
|
| 85 |
+
"sha256": "d61652f92fc3691f55e71b76c9ef17ccabb4502ff7038f7626b69f52918907c9"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
},
|
| 87 |
+
"components/skillsdesk/upstream/terminal_desk/core/shell.py": {
|
| 88 |
+
"bytes": 4743,
|
| 89 |
+
"sha256": "e6af14ad4263f3067f47dc841f28fc6d24de64c8400df91facce1fdd71dced5d"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
},
|
| 91 |
+
"components/skillsdesk/upstream/terminal_desk/families/__init__.py": {
|
| 92 |
+
"bytes": 2614,
|
| 93 |
+
"sha256": "3d04bdea30395f1e8fa03d804a5728777633bf319f4e00575ef047f2011fa411"
|
| 94 |
},
|
| 95 |
+
"components/skillsdesk/upstream/terminal_desk/families/base.py": {
|
| 96 |
+
"bytes": 1915,
|
| 97 |
+
"sha256": "a0ef4dec6a2932ead3331d0cea6e5bb3b91fa91075508560aa9cf08495b0ad6f"
|
| 98 |
},
|
| 99 |
+
"components/skillsdesk/upstream/terminal_desk/families/compute.py": {
|
| 100 |
+
"bytes": 10755,
|
| 101 |
+
"sha256": "60c1e5c80f42479d79c86e222c3a101182955822b5b555b25cf0cff40d7bc7c3"
|
| 102 |
},
|
| 103 |
+
"components/skillsdesk/upstream/terminal_desk/families/compute2.py": {
|
| 104 |
+
"bytes": 12743,
|
| 105 |
+
"sha256": "91cdb191a4af146bc8901e585f213d7377584ea6c493c60839a4aeddd7e63d33"
|
| 106 |
},
|
| 107 |
+
"components/skillsdesk/upstream/terminal_desk/families/constraints.py": {
|
| 108 |
+
"bytes": 9807,
|
| 109 |
+
"sha256": "25494ac58d4fa7196b5e702dfc9cc55e9635dbaa1603de160a80d39fb09d3ea0"
|
| 110 |
},
|
| 111 |
+
"components/skillsdesk/upstream/terminal_desk/families/constraints2.py": {
|
| 112 |
+
"bytes": 14665,
|
| 113 |
+
"sha256": "411991bca80cbbdfb08eacc5192a07ba45442e41a3e600780b2efdac1b072cc4"
|
| 114 |
},
|
| 115 |
+
"components/skillsdesk/upstream/terminal_desk/families/evidence.py": {
|
| 116 |
+
"bytes": 10896,
|
| 117 |
+
"sha256": "c2ff755246cc006d04f36acf9f8787efad0ca22a6e2c0c9b2dc14bb4d3fb7045"
|
| 118 |
},
|
| 119 |
+
"components/skillsdesk/upstream/terminal_desk/families/evidence2.py": {
|
| 120 |
+
"bytes": 14514,
|
| 121 |
+
"sha256": "d32eedf32ee8e385bd123501b33c2d15c75a7604cc9a029e97d8dabf6de97e60"
|
| 122 |
},
|
| 123 |
+
"components/skillsdesk/upstream/terminal_desk/families/repair.py": {
|
| 124 |
+
"bytes": 17806,
|
| 125 |
+
"sha256": "a3392b6cf21d6cdb562862fb9f0999ec8a57a4116162e3b58d1c00f9fb19b781"
|
| 126 |
},
|
| 127 |
+
"components/skillsdesk/upstream/terminal_desk/families/repair2.py": {
|
| 128 |
+
"bytes": 20016,
|
| 129 |
+
"sha256": "1d22338235ffb0e25786a45ddb0c28be00081f89df1bee94052d57f6ac01ace6"
|
| 130 |
},
|
| 131 |
+
"components/skillsdesk/upstream/terminal_desk/families/transform.py": {
|
| 132 |
+
"bytes": 6815,
|
| 133 |
+
"sha256": "d478ea588230f6394fdad03fef1d377399086015f7a33d1f892e78c268808df1"
|
| 134 |
},
|
| 135 |
+
"components/skillsdesk/upstream/terminal_desk/families/transform2.py": {
|
| 136 |
+
"bytes": 13415,
|
| 137 |
+
"sha256": "2c176531664ffcbfb998283b1b6cc145ddac976c7b2137b5535a2a9e1b422af2"
|
| 138 |
},
|
| 139 |
+
"components/skillsdesk/upstream/terminal_desk/families/util.py": {
|
| 140 |
+
"bytes": 3899,
|
| 141 |
+
"sha256": "0e3b71ebcd82ccce47ea3bcbcc98efafb23b297f9831b2e37afd399d44eb5832"
|
| 142 |
},
|
| 143 |
+
"components/skillsdesk/upstream/terminal_desk/models.py": {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
"bytes": 1750,
|
| 145 |
"sha256": "f31264b0909878c6f2d4d18a270c7d92bc895052150c56e5ac3e6b38d4ceebb4"
|
| 146 |
},
|
| 147 |
+
"components/skillsdesk/upstream/terminal_desk/reserved/__init__.py": {
|
| 148 |
+
"bytes": 647,
|
| 149 |
+
"sha256": "012f259f4fd2aad8af71accaf7686f8e76235491d9ad200bfbec9f3641afa330"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
},
|
| 151 |
+
"components/skillsdesk/upstream/terminal_desk/reserved/compute.py": {
|
| 152 |
+
"bytes": 12349,
|
| 153 |
+
"sha256": "e87cfd26e155b8c0a830cfd6809274c930ee45d31f2ac44398f35385b2dbe083"
|
| 154 |
},
|
| 155 |
+
"components/skillsdesk/upstream/terminal_desk/reserved/constraints.py": {
|
| 156 |
+
"bytes": 15358,
|
| 157 |
+
"sha256": "ca168704db89a1da64fd0262c44280e0461d2a58d4f9191a6c9747d19cb0bee0"
|
| 158 |
},
|
| 159 |
+
"components/skillsdesk/upstream/terminal_desk/reserved/evidence.py": {
|
| 160 |
+
"bytes": 12524,
|
| 161 |
+
"sha256": "e3c5f779c29f730fd2844018150078640c17425bfe6ddb922103a661a86c5ee0"
|
| 162 |
},
|
| 163 |
+
"components/skillsdesk/upstream/terminal_desk/reserved/repair.py": {
|
| 164 |
+
"bytes": 16541,
|
| 165 |
+
"sha256": "121c2be70cd21ca16c254153eebbce895f2bb86c37aedcaaaa237662917e18e5"
|
| 166 |
},
|
| 167 |
+
"components/skillsdesk/upstream/terminal_desk/reserved/transform.py": {
|
| 168 |
+
"bytes": 11909,
|
| 169 |
+
"sha256": "bd97f765a7e468bd2e4b4a6e1e959177df999a123d712c5c2b4f93e4359c99cf"
|
| 170 |
},
|
| 171 |
+
"components/skillsdesk/upstream/terminal_desk/server/__init__.py": {
|
| 172 |
"bytes": 0,
|
| 173 |
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
| 174 |
},
|
| 175 |
+
"components/skillsdesk/upstream/terminal_desk/server/app.py": {
|
| 176 |
"bytes": 802,
|
| 177 |
"sha256": "6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8"
|
| 178 |
},
|
| 179 |
+
"components/skillsdesk/upstream/terminal_desk/server/environment.py": {
|
| 180 |
+
"bytes": 6820,
|
| 181 |
+
"sha256": "82aa929676d76fe2f8d81a5122598986ac2950339dbfc4366de03a3604cd7319"
|
| 182 |
},
|
| 183 |
"schema.json": {
|
| 184 |
"bytes": 1911,
|
| 185 |
"sha256": "10993deaaa8553929fa0b3b6bf3c1ad100baaaf9ff10ae8ed139a8ec4279a3c4"
|
| 186 |
},
|
| 187 |
"tasks.jsonl": {
|
| 188 |
+
"bytes": 17061,
|
| 189 |
+
"sha256": "2a3fe43c4b55a123f5a80f0c2d60c15f86d94470cd2a4fc86adbaec85c12054b"
|
| 190 |
},
|
| 191 |
"validate_dataset.py": {
|
| 192 |
+
"bytes": 8206,
|
| 193 |
+
"sha256": "db3704682eefb03f47a6c951865e9fb2113851f8bdf0266f6c4f517961f2973b"
|
| 194 |
}
|
| 195 |
}
|
| 196 |
}
|
README.md
CHANGED
|
@@ -11,10 +11,10 @@ configs:
|
|
| 11 |
path: tasks.jsonl
|
| 12 |
---
|
| 13 |
|
| 14 |
-
|
| 15 |
|
| 16 |
-
|
| 17 |
|
| 18 |
-
|
| 19 |
|
| 20 |
-
Run `python3 -B validate_dataset.py` to verify the file inventory.
|
|
|
|
| 11 |
path: tasks.jsonl
|
| 12 |
---
|
| 13 |
|
| 14 |
+
Twenty original Skills Desk tasks covering evidence matching, computation, data transformation, code repair and constrained planning.
|
| 15 |
|
| 16 |
+
Each task ID identifies a fixed original instance. Use the tools shown at reset and `op=finish` to grade the artifact. Reward is one when all original checks pass, otherwise zero. Code repair tasks also run hidden-input checks.
|
| 17 |
|
| 18 |
+
Run one episode per fresh sandbox, with one active session. Each episode allows 32 actions, 8192 completion tokens and 16384 context tokens; later observations count toward completion tokens. Commands have the original 20-second limit.
|
| 19 |
|
| 20 |
+
Task IDs and pinned source references are in `tasks.jsonl`. Original licenses and attribution are in `components/skillsdesk/`. Run `python3 -B validate_dataset.py` to verify the file inventory.
|
SHA256SUMS
CHANGED
|
@@ -1,70 +1,48 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 components/
|
| 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 |
-
c1049fdb6b4f11f0b5e0194b41e84b525d5a340213c2c94f5f99ffd6c2b75a42 components/dnakhla/upstream/terminal_desk/oracles/ind3_tank_balance.py
|
| 47 |
-
0fd62812cd9ef1d5be6d6ae9fa2fa047eb6bb0a4508ccb5a5369373aefbf8dd3 components/dnakhla/upstream/terminal_desk/oracles/math3_count_items.py
|
| 48 |
-
03908ec43159f4a66678f37fb0366389608eeeba41361758d966c96eea50dc3f components/dnakhla/upstream/terminal_desk/oracles/math3_exam_slots.py
|
| 49 |
-
c2bb32b08a3705a4be56ff8c4e3af94d64441c9a7432f5dcec4dce0b378ee465 components/dnakhla/upstream/terminal_desk/oracles/math3_route_plan.py
|
| 50 |
-
554e36455da66fd258e6ad2c39e80acbc3856237fee4608ce57b494f23c3d16d components/dnakhla/upstream/terminal_desk/oracles/med3_silence_report.py
|
| 51 |
-
8f0a1169d6e5b10c4981b53a22e957c4befad44d95e5d250cf53734105a40256 components/dnakhla/upstream/terminal_desk/oracles/med3_sprite_count.py
|
| 52 |
-
72f448ba58ac9ee6082692dec88ddb6f279ae69bdb99d39b30d1acce12c19bfe components/dnakhla/upstream/terminal_desk/oracles/med3_subtitle_retime.py
|
| 53 |
-
b5320a71696443f1b04c0c5e02e35d0baee67a175a912bff86e32df7c2acb357 components/dnakhla/upstream/terminal_desk/oracles/off3_ar_recon.py
|
| 54 |
-
6eef5e15337e5029c8e0b3353adee791ea9ebe73c6d79e47d84d6b7294cb5a38 components/dnakhla/upstream/terminal_desk/oracles/off3_meeting_slot.py
|
| 55 |
-
82b5c15f02a03615699429a2342dbad4b8985aab76d82fa8a8b96f7fbebc544f components/dnakhla/upstream/terminal_desk/oracles/off3_pdf_xlsx_diff.py
|
| 56 |
-
1ebc19667bf1963c83a47bd4905e99e0c32c3ce249b63ae2d7b39fcffa1b1bb7 components/dnakhla/upstream/terminal_desk/oracles/sci3_kinetics_fit.py
|
| 57 |
-
a983fb3c03ba15bc0591ab32ce41ddb99f2f38329e273f3f5da20f775d6bd8ab components/dnakhla/upstream/terminal_desk/oracles/sci3_lightcurve_period.py
|
| 58 |
-
56a84763e746f034571dc50a71f3716f340e4f8d9dee823eb3c9b209f471f48a components/dnakhla/upstream/terminal_desk/oracles/sci3_stoich_batch.py
|
| 59 |
-
c5fb5f697e8cfdb6008fcd59d6c3095a509d9a488dc28d7b99da4f4fe128b8a6 components/dnakhla/upstream/terminal_desk/oracles/sec3_auth_triage.py
|
| 60 |
-
5a4cc8a38f0554be4b287e2592bd26553db2f3ee6b5c10339d641246a7a6af90 components/dnakhla/upstream/terminal_desk/oracles/sec3_exfil_flows.py
|
| 61 |
-
b91c7389813445d55edbdaadec60aa4c5d0b6c5ead6fdfca5268e425f512820f components/dnakhla/upstream/terminal_desk/oracles/sec3_fw_verdicts.py
|
| 62 |
-
6b46601bc7e4bdc42c62242344aa431a34e7a6d1a8c7201e77315c66c6a4ae09 components/dnakhla/upstream/terminal_desk/oracles/sw3_dep_lock.py
|
| 63 |
-
43eee7f24a02ca3f0d3b12db5a44c132a931fc8dba10f9c1d4028d7fa5775bf4 components/dnakhla/upstream/terminal_desk/oracles/sw3_fix_module.py
|
| 64 |
-
4f1f187ae42f47faecc85d84e1f0341c848b03eb2bba1bf538927e2e62758314 components/dnakhla/upstream/terminal_desk/oracles/sw3_rate_limit.py
|
| 65 |
-
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/dnakhla/upstream/terminal_desk/server/__init__.py
|
| 66 |
-
6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8 components/dnakhla/upstream/terminal_desk/server/app.py
|
| 67 |
-
8e92f991e14098a0858490fe5beb43ca9b0ee2cfbddb36e73ecf987ba3922902 components/dnakhla/upstream/terminal_desk/server/environment.py
|
| 68 |
10993deaaa8553929fa0b3b6bf3c1ad100baaaf9ff10ae8ed139a8ec4279a3c4 schema.json
|
| 69 |
-
|
| 70 |
-
|
|
|
|
| 1 |
+
bd0d465f995e6e88f99a624901bbf6577b31c7230a4ff959ca48516be0339af7 README.md
|
| 2 |
+
df3acef0a949edac8c6ec87a15e4d7c5a87534a83d49186549699a59bdf22f98 SOURCE_LOCK.json
|
| 3 |
+
60c9bdd905fcf45ac485c680d32e9773962cf061b6f041dcddd033911558a672 components/skillsdesk/.dockerignore
|
| 4 |
+
843b71a3a9f9de899cbb9d260d55c9bd082f3df2b7771a1c31100ce5767a0a53 components/skillsdesk/ADAPTER_NOTICE
|
| 5 |
+
4f047d60bc07987131be2c9cf0662c6e6feef91125adda81eda04d4b88882f6b components/skillsdesk/Dockerfile
|
| 6 |
+
cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 components/skillsdesk/LICENSE
|
| 7 |
+
dca813e02ab76d4bc5afdcd2a2de3480d3fc0a7a710edea24c395adf23a99883 components/skillsdesk/NOTICE
|
| 8 |
+
11775067d2cfb4c254084dd741f0b13a1a5058081c171712bdb9923d430a9cd4 components/skillsdesk/README.md
|
| 9 |
+
789ef47ecb391dfe876f65207ba8f477b064c1d9cded1becaf177ae7112a3d99 components/skillsdesk/SOURCE_MANIFEST.json
|
| 10 |
+
2c07033febd78777deeff04350ae6887c9bb170b152d38c26cf148efa1b75d1e components/skillsdesk/UPSTREAM_DOCKERFILE
|
| 11 |
+
90e6e08d4269b5bb8308b5f2f05c61aa0cb9b71643b6abe6e47b34795828dd1e components/skillsdesk/UPSTREAM_TRAINING_TASKS.txt
|
| 12 |
+
01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b components/skillsdesk/runtime/common/__init__.py
|
| 13 |
+
b1e1429208e84aefc2422ee1d2400ad793c43cd5c0e8db213a3b669fe0947ce1 components/skillsdesk/runtime/common/contracts.py
|
| 14 |
+
6a1ac8e55af6168d3fdd6b17c700a15cf0546b6154773aa3c59c97d6bffa2ffd components/skillsdesk/runtime/common/models.py
|
| 15 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/skillsdesk/runtime/skillsdesk_compat/__init__.py
|
| 16 |
+
22a0011808344bdeeb635082afbacac2810bdf14e617ac72011e211dfa14c176 components/skillsdesk/runtime/skillsdesk_compat/environment.py
|
| 17 |
+
634fd3bd58cb4ade2c5d959ae7fb09dfb24b102830170c00a140a3ff949e590c components/skillsdesk/runtime/skillsdesk_compat/server.py
|
| 18 |
+
88e8863954ec9a9d34d07cdde0d5d4688f1fc85a2c595f13c7b9d4d10be6218e components/skillsdesk/upstream/openenv.yaml
|
| 19 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/skillsdesk/upstream/terminal_desk/__init__.py
|
| 20 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/skillsdesk/upstream/terminal_desk/core/__init__.py
|
| 21 |
+
d61652f92fc3691f55e71b76c9ef17ccabb4502ff7038f7626b69f52918907c9 components/skillsdesk/upstream/terminal_desk/core/grading.py
|
| 22 |
+
e6af14ad4263f3067f47dc841f28fc6d24de64c8400df91facce1fdd71dced5d components/skillsdesk/upstream/terminal_desk/core/shell.py
|
| 23 |
+
3d04bdea30395f1e8fa03d804a5728777633bf319f4e00575ef047f2011fa411 components/skillsdesk/upstream/terminal_desk/families/__init__.py
|
| 24 |
+
a0ef4dec6a2932ead3331d0cea6e5bb3b91fa91075508560aa9cf08495b0ad6f components/skillsdesk/upstream/terminal_desk/families/base.py
|
| 25 |
+
60c1e5c80f42479d79c86e222c3a101182955822b5b555b25cf0cff40d7bc7c3 components/skillsdesk/upstream/terminal_desk/families/compute.py
|
| 26 |
+
91cdb191a4af146bc8901e585f213d7377584ea6c493c60839a4aeddd7e63d33 components/skillsdesk/upstream/terminal_desk/families/compute2.py
|
| 27 |
+
25494ac58d4fa7196b5e702dfc9cc55e9635dbaa1603de160a80d39fb09d3ea0 components/skillsdesk/upstream/terminal_desk/families/constraints.py
|
| 28 |
+
411991bca80cbbdfb08eacc5192a07ba45442e41a3e600780b2efdac1b072cc4 components/skillsdesk/upstream/terminal_desk/families/constraints2.py
|
| 29 |
+
c2ff755246cc006d04f36acf9f8787efad0ca22a6e2c0c9b2dc14bb4d3fb7045 components/skillsdesk/upstream/terminal_desk/families/evidence.py
|
| 30 |
+
d32eedf32ee8e385bd123501b33c2d15c75a7604cc9a029e97d8dabf6de97e60 components/skillsdesk/upstream/terminal_desk/families/evidence2.py
|
| 31 |
+
a3392b6cf21d6cdb562862fb9f0999ec8a57a4116162e3b58d1c00f9fb19b781 components/skillsdesk/upstream/terminal_desk/families/repair.py
|
| 32 |
+
1d22338235ffb0e25786a45ddb0c28be00081f89df1bee94052d57f6ac01ace6 components/skillsdesk/upstream/terminal_desk/families/repair2.py
|
| 33 |
+
d478ea588230f6394fdad03fef1d377399086015f7a33d1f892e78c268808df1 components/skillsdesk/upstream/terminal_desk/families/transform.py
|
| 34 |
+
2c176531664ffcbfb998283b1b6cc145ddac976c7b2137b5535a2a9e1b422af2 components/skillsdesk/upstream/terminal_desk/families/transform2.py
|
| 35 |
+
0e3b71ebcd82ccce47ea3bcbcc98efafb23b297f9831b2e37afd399d44eb5832 components/skillsdesk/upstream/terminal_desk/families/util.py
|
| 36 |
+
f31264b0909878c6f2d4d18a270c7d92bc895052150c56e5ac3e6b38d4ceebb4 components/skillsdesk/upstream/terminal_desk/models.py
|
| 37 |
+
012f259f4fd2aad8af71accaf7686f8e76235491d9ad200bfbec9f3641afa330 components/skillsdesk/upstream/terminal_desk/reserved/__init__.py
|
| 38 |
+
e87cfd26e155b8c0a830cfd6809274c930ee45d31f2ac44398f35385b2dbe083 components/skillsdesk/upstream/terminal_desk/reserved/compute.py
|
| 39 |
+
ca168704db89a1da64fd0262c44280e0461d2a58d4f9191a6c9747d19cb0bee0 components/skillsdesk/upstream/terminal_desk/reserved/constraints.py
|
| 40 |
+
e3c5f779c29f730fd2844018150078640c17425bfe6ddb922103a661a86c5ee0 components/skillsdesk/upstream/terminal_desk/reserved/evidence.py
|
| 41 |
+
121c2be70cd21ca16c254153eebbce895f2bb86c37aedcaaaa237662917e18e5 components/skillsdesk/upstream/terminal_desk/reserved/repair.py
|
| 42 |
+
bd97f765a7e468bd2e4b4a6e1e959177df999a123d712c5c2b4f93e4359c99cf components/skillsdesk/upstream/terminal_desk/reserved/transform.py
|
| 43 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 components/skillsdesk/upstream/terminal_desk/server/__init__.py
|
| 44 |
+
6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8 components/skillsdesk/upstream/terminal_desk/server/app.py
|
| 45 |
+
82aa929676d76fe2f8d81a5122598986ac2950339dbfc4366de03a3604cd7319 components/skillsdesk/upstream/terminal_desk/server/environment.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
10993deaaa8553929fa0b3b6bf3c1ad100baaaf9ff10ae8ed139a8ec4279a3c4 schema.json
|
| 47 |
+
2a3fe43c4b55a123f5a80f0c2d60c15f86d94470cd2a4fc86adbaec85c12054b tasks.jsonl
|
| 48 |
+
db3704682eefb03f47a6c951865e9fb2113851f8bdf0266f6c4f517961f2973b validate_dataset.py
|
SOURCE_LOCK.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
{
|
| 2 |
"components": {
|
| 3 |
-
"
|
| 4 |
-
"repository": "
|
| 5 |
-
"revision": "
|
| 6 |
"license": "Apache-2.0",
|
| 7 |
"source_file": "SOURCE_MANIFEST.json",
|
| 8 |
-
"record_sha256": "
|
| 9 |
}
|
| 10 |
}
|
| 11 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"components": {
|
| 3 |
+
"skillsdesk": {
|
| 4 |
+
"repository": "Syndicate604/skills-desk",
|
| 5 |
+
"revision": "a785ccdc9784ed863d0ffecec826d72176c0a785",
|
| 6 |
"license": "Apache-2.0",
|
| 7 |
"source_file": "SOURCE_MANIFEST.json",
|
| 8 |
+
"record_sha256": "789ef47ecb391dfe876f65207ba8f477b064c1d9cded1becaf177ae7112a3d99"
|
| 9 |
}
|
| 10 |
}
|
| 11 |
}
|
components/dnakhla/.dockerignore
DELETED
|
@@ -1,5 +0,0 @@
|
|
| 1 |
-
upstream
|
| 2 |
-
README.md
|
| 3 |
-
LICENSE
|
| 4 |
-
NOTICE
|
| 5 |
-
**/__pycache__
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/Dockerfile
DELETED
|
@@ -1,8 +0,0 @@
|
|
| 1 |
-
FROM ghcr.io/dnakhla/terminal-desk@sha256:de59e5f70a416641a5cc39cd3510a0a91c57808841448e44dc7f4eaf10376c5e
|
| 2 |
-
USER root
|
| 3 |
-
COPY runtime /opt/dnakhla_compat
|
| 4 |
-
COPY SOURCE_MANIFEST.json /opt/dnakhla_compat/SOURCE_MANIFEST.json
|
| 5 |
-
RUN chmod -R go-rwx /opt/dnakhla_compat
|
| 6 |
-
ENV PYTHONPATH=/opt/dnakhla_compat:/opt/terminal_desk OPENENV_MODE=production
|
| 7 |
-
WORKDIR /opt/dnakhla_compat
|
| 8 |
-
CMD ["python", "-m", "dnakhla_compat.server"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/NOTICE
DELETED
|
@@ -1,4 +0,0 @@
|
|
| 1 |
-
Terminal Desk by dnakhla
|
| 2 |
-
Source: https://huggingface.co/datasets/dnakhla/terminal-desk/tree/08fab0beb50b665b42f0ac73840f03140f4ad1c9
|
| 3 |
-
License declaration: Apache-2.0. The accompanying standard license text was added by this distribution.
|
| 4 |
-
This distribution adds a shared Arena interface and a four-task registry. Original task source remains unchanged.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/README.md
DELETED
|
@@ -1,5 +0,0 @@
|
|
| 1 |
-
Original Terminal Desk tasks by dnakhla. The shared adapter preserves original tools, random resets and artifact grading. Registered IDs are listed in SOURCE_MANIFEST.json.
|
| 2 |
-
|
| 3 |
-
Run: `python -m dnakhla_compat.server`
|
| 4 |
-
|
| 5 |
-
Run one episode per sandbox, with one active session.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/SOURCE_MANIFEST.json
DELETED
|
@@ -1,66 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"base_image": "ghcr.io/dnakhla/terminal-desk@sha256:de59e5f70a416641a5cc39cd3510a0a91c57808841448e44dc7f4eaf10376c5e",
|
| 3 |
-
"dataset": "dnakhla/terminal-desk",
|
| 4 |
-
"revision": "08fab0beb50b665b42f0ac73840f03140f4ad1c9",
|
| 5 |
-
"license_declaration": "Apache-2.0",
|
| 6 |
-
"original_files": {
|
| 7 |
-
"openenv.yaml": "8c68fdfde651ec70155ec1a8d4b15f5c14cdd1f9d98197fc5037b49d6dc74524",
|
| 8 |
-
"terminal_desk/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 9 |
-
"terminal_desk/core/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 10 |
-
"terminal_desk/core/grading.py": "8606129c5aa3f99cc540a7c8269b65e9bb6c42e81bca36085c16963a0cccd2bd",
|
| 11 |
-
"terminal_desk/core/shell.py": "59b4b07b0d59e01792c8dbbf7877555e2da2346ddf5d2c17df3bbd4e17cb847f",
|
| 12 |
-
"terminal_desk/families/__init__.py": "2ca3d4eda1fb04a84a236fbb43b71d13d46ea68109f545e036842211be3e3958",
|
| 13 |
-
"terminal_desk/families/base.py": "d76cab459096d3748d2c4198753853d85418de61f64436cf4772b89345fdcf17",
|
| 14 |
-
"terminal_desk/families/finance.py": "312a26e2d48ac10a07716384d3059a697f75f16e5b37fcabb8c07fcac3397f6f",
|
| 15 |
-
"terminal_desk/families/finance3.py": "a4839540c7a54198ea8e480248428e9ca65bdaf45adea5ae9f81cad71cbb1311",
|
| 16 |
-
"terminal_desk/families/industrial.py": "9140985ca44b1bcfc78b853f44496b7a9b77288284675f3656898de5be70d6aa",
|
| 17 |
-
"terminal_desk/families/industrial3.py": "48e914996b67accb09350a6714a5cea4a6191c0a05ac12a8f3045309f961c49c",
|
| 18 |
-
"terminal_desk/families/mathematics.py": "552855819cbe4983529b864279c915bc56f8d68d850a3f221d84864066c0e2a5",
|
| 19 |
-
"terminal_desk/families/mathematics3.py": "9dc54710cd826aadbe5de55d9093959e38c59dc59ae080e40d379cc4db1987c1",
|
| 20 |
-
"terminal_desk/families/media.py": "52523502e6c679e34bd2dbeb46c3f539ba53ae2d4e1033adafca7ce859bc4de8",
|
| 21 |
-
"terminal_desk/families/media3.py": "9c91cfbde8ad60da034c15ba3418e21ae5891a12ce3932ecaf8035fcd6eef4bd",
|
| 22 |
-
"terminal_desk/families/office.py": "11f76ce7d62e18b535278b487f798703fd6f2bef04dd7ffaefae2c95bcba1102",
|
| 23 |
-
"terminal_desk/families/office3.py": "1926c4a6e600cabb4cd35fab9528b4e4d55ef4adc1623b7229ac356ef28c987b",
|
| 24 |
-
"terminal_desk/families/science.py": "836ab819a2231700a4bff2929a4579034c45a637992e883ddfbdb0c1f711446a",
|
| 25 |
-
"terminal_desk/families/science3.py": "59477a1f9d38dbe5607f6432b4f8538342eec93faeed09bb6c9cb1402980c9a1",
|
| 26 |
-
"terminal_desk/families/security.py": "1228db896b6ce796ccf1f133e2f2ba9aaa9d54b745d5ffaf4b584a63a6aab2bd",
|
| 27 |
-
"terminal_desk/families/security3.py": "6f5ec9c2dfe9aad81ba382d4f6ffdb7f64493d92cd7fe5d653134ef0dac107af",
|
| 28 |
-
"terminal_desk/families/software.py": "4bca03797d701fe33f567729baa9a4fb2cef59cf220d0b79a941cc3817f8ba3a",
|
| 29 |
-
"terminal_desk/families/software3.py": "d526ae88ca53ef22dbc1e578055fc27ebb491c184474e662736b8be9523086a7",
|
| 30 |
-
"terminal_desk/models.py": "f31264b0909878c6f2d4d18a270c7d92bc895052150c56e5ac3e6b38d4ceebb4",
|
| 31 |
-
"terminal_desk/oracles/__init__.py": "04e4b102444b5db19507a46814820d78ad1e9782f963e5764f8f4adfe4d366a3",
|
| 32 |
-
"terminal_desk/oracles/fin3_invoice_fraud.py": "975ff8045d42b2f483924e368e304c451bca894ddb4ba593d9dd3aea1c505329",
|
| 33 |
-
"terminal_desk/oracles/fin3_loan_schedule.py": "b0a32266ec725f5a4f76d8b40a27fc52759f679d74e4dfe5c7885a1b19a36711",
|
| 34 |
-
"terminal_desk/oracles/fin3_portfolio_value.py": "152a3516b9ec6811121747ea875fc1a73cb768ba6a98e05c2bee91325e4f7247",
|
| 35 |
-
"terminal_desk/oracles/ind3_service_due.py": "47914a6e1a5bde126ce301bc11d4dc95b11cb0910ac0208a4c78596d7e65e30e",
|
| 36 |
-
"terminal_desk/oracles/ind3_stl_mass.py": "53e6adc26768256ce6665bda20c4b04ad87602e24eb31b074c25dc8fbbc00653",
|
| 37 |
-
"terminal_desk/oracles/ind3_tank_balance.py": "c1049fdb6b4f11f0b5e0194b41e84b525d5a340213c2c94f5f99ffd6c2b75a42",
|
| 38 |
-
"terminal_desk/oracles/math3_count_items.py": "0fd62812cd9ef1d5be6d6ae9fa2fa047eb6bb0a4508ccb5a5369373aefbf8dd3",
|
| 39 |
-
"terminal_desk/oracles/math3_exam_slots.py": "03908ec43159f4a66678f37fb0366389608eeeba41361758d966c96eea50dc3f",
|
| 40 |
-
"terminal_desk/oracles/math3_route_plan.py": "c2bb32b08a3705a4be56ff8c4e3af94d64441c9a7432f5dcec4dce0b378ee465",
|
| 41 |
-
"terminal_desk/oracles/med3_silence_report.py": "554e36455da66fd258e6ad2c39e80acbc3856237fee4608ce57b494f23c3d16d",
|
| 42 |
-
"terminal_desk/oracles/med3_sprite_count.py": "8f0a1169d6e5b10c4981b53a22e957c4befad44d95e5d250cf53734105a40256",
|
| 43 |
-
"terminal_desk/oracles/med3_subtitle_retime.py": "72f448ba58ac9ee6082692dec88ddb6f279ae69bdb99d39b30d1acce12c19bfe",
|
| 44 |
-
"terminal_desk/oracles/off3_ar_recon.py": "b5320a71696443f1b04c0c5e02e35d0baee67a175a912bff86e32df7c2acb357",
|
| 45 |
-
"terminal_desk/oracles/off3_meeting_slot.py": "6eef5e15337e5029c8e0b3353adee791ea9ebe73c6d79e47d84d6b7294cb5a38",
|
| 46 |
-
"terminal_desk/oracles/off3_pdf_xlsx_diff.py": "82b5c15f02a03615699429a2342dbad4b8985aab76d82fa8a8b96f7fbebc544f",
|
| 47 |
-
"terminal_desk/oracles/sci3_kinetics_fit.py": "1ebc19667bf1963c83a47bd4905e99e0c32c3ce249b63ae2d7b39fcffa1b1bb7",
|
| 48 |
-
"terminal_desk/oracles/sci3_lightcurve_period.py": "a983fb3c03ba15bc0591ab32ce41ddb99f2f38329e273f3f5da20f775d6bd8ab",
|
| 49 |
-
"terminal_desk/oracles/sci3_stoich_batch.py": "56a84763e746f034571dc50a71f3716f340e4f8d9dee823eb3c9b209f471f48a",
|
| 50 |
-
"terminal_desk/oracles/sec3_auth_triage.py": "c5fb5f697e8cfdb6008fcd59d6c3095a509d9a488dc28d7b99da4f4fe128b8a6",
|
| 51 |
-
"terminal_desk/oracles/sec3_exfil_flows.py": "5a4cc8a38f0554be4b287e2592bd26553db2f3ee6b5c10339d641246a7a6af90",
|
| 52 |
-
"terminal_desk/oracles/sec3_fw_verdicts.py": "b91c7389813445d55edbdaadec60aa4c5d0b6c5ead6fdfca5268e425f512820f",
|
| 53 |
-
"terminal_desk/oracles/sw3_dep_lock.py": "6b46601bc7e4bdc42c62242344aa431a34e7a6d1a8c7201e77315c66c6a4ae09",
|
| 54 |
-
"terminal_desk/oracles/sw3_fix_module.py": "43eee7f24a02ca3f0d3b12db5a44c132a931fc8dba10f9c1d4028d7fa5775bf4",
|
| 55 |
-
"terminal_desk/oracles/sw3_rate_limit.py": "4f1f187ae42f47faecc85d84e1f0341c848b03eb2bba1bf538927e2e62758314",
|
| 56 |
-
"terminal_desk/server/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 57 |
-
"terminal_desk/server/app.py": "6bf7658ec8ad07dda230a01fd893091a9b87df18ebf6af25af6c35965ed01fd8",
|
| 58 |
-
"terminal_desk/server/environment.py": "8e92f991e14098a0858490fe5beb43ca9b0ee2cfbddb36e73ecf987ba3922902"
|
| 59 |
-
},
|
| 60 |
-
"selected_tasks": [
|
| 61 |
-
"math3_exam_slots-L2",
|
| 62 |
-
"off3_meeting_slot-L2",
|
| 63 |
-
"med3_subtitle_retime-L2",
|
| 64 |
-
"med3_silence_report-L2"
|
| 65 |
-
]
|
| 66 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/runtime/dnakhla_compat/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
"""Local compatibility prototype for the original Terminal Desk environment."""
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/__init__.py
DELETED
|
@@ -1,21 +0,0 @@
|
|
| 1 |
-
"""Registry of task families. A task id is '<family>-L<level>', e.g. 'ind_tank-L2'."""
|
| 2 |
-
|
| 3 |
-
from . import finance, finance3, industrial, industrial3, mathematics, mathematics3, media, media3, office, office3, science, science3, security, security3, software, software3
|
| 4 |
-
from .base import Family
|
| 5 |
-
|
| 6 |
-
FAMILIES: dict[str, Family] = {
|
| 7 |
-
f.id: f
|
| 8 |
-
for module in (software, industrial, industrial3, science, office, finance, mathematics, security, media, office3, security3, mathematics3, science3, media3, software3, finance3)
|
| 9 |
-
for f in module.FAMILIES
|
| 10 |
-
}
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
def parse_task_id(task_id: str) -> tuple[str, int]:
|
| 14 |
-
family_id, _, level = task_id.rpartition("-L")
|
| 15 |
-
if family_id not in FAMILIES or not level.isdigit() or int(level) not in FAMILIES[family_id].levels:
|
| 16 |
-
raise ValueError(f"unknown task_id {task_id!r}")
|
| 17 |
-
return family_id, int(level)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def all_task_ids() -> list[str]:
|
| 21 |
-
return [f"{fid}-L{lv}" for fid, fam in FAMILIES.items() for lv in fam.levels]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/finance.py
DELETED
|
@@ -1,228 +0,0 @@
|
|
| 1 |
-
"""Finance: amortize a loan with extras and a rate reset; value a portfolio through corporate actions."""
|
| 2 |
-
|
| 3 |
-
import datetime as dt
|
| 4 |
-
import random
|
| 5 |
-
from decimal import ROUND_HALF_UP, Decimal, getcontext
|
| 6 |
-
|
| 7 |
-
from .base import Artifact, Built, Family, Field
|
| 8 |
-
|
| 9 |
-
getcontext().prec = 40
|
| 10 |
-
CENT = Decimal("0.01")
|
| 11 |
-
|
| 12 |
-
# ---------------------------------------------------------------- fin_loan
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def _r(x: Decimal) -> Decimal:
|
| 16 |
-
return x.quantize(CENT, rounding=ROUND_HALF_UP)
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
def _payment(balance: Decimal, annual_pct: Decimal, months: int) -> Decimal:
|
| 20 |
-
i = annual_pct / 1200
|
| 21 |
-
return _r(balance * i / (1 - (1 + i) ** -months))
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
def build_loan(level: int, rng: random.Random) -> Built:
|
| 25 |
-
while True:
|
| 26 |
-
principal = Decimal(rng.randrange(100, 4000) * 100)
|
| 27 |
-
rate = Decimal(f"{rng.uniform(3, 9):.3f}")
|
| 28 |
-
months = rng.choice([60, 120, 180, 240, 360])
|
| 29 |
-
extras = {}
|
| 30 |
-
if level >= 2:
|
| 31 |
-
for m in rng.sample(range(6, months // 2), rng.randint(2, 4)):
|
| 32 |
-
extras[m] = Decimal(rng.randrange(5, 60) * 100)
|
| 33 |
-
reset_month, new_rate = None, None
|
| 34 |
-
if level == 3:
|
| 35 |
-
reset_month = rng.randint(13, min(60, months - 12))
|
| 36 |
-
new_rate = Decimal(f"{float(rate) + rng.uniform(-1.5, 2.5):.3f}")
|
| 37 |
-
pay = _payment(principal, rate, months)
|
| 38 |
-
bal, cur_rate, month, new_pay = principal, rate, 0, None
|
| 39 |
-
rows = []
|
| 40 |
-
while bal > 0:
|
| 41 |
-
month += 1
|
| 42 |
-
if reset_month and month == reset_month:
|
| 43 |
-
cur_rate = new_rate
|
| 44 |
-
pay = new_pay = _payment(bal, new_rate, months - month + 1)
|
| 45 |
-
interest = _r(bal * cur_rate / 1200)
|
| 46 |
-
if bal + interest <= pay or month == months:
|
| 47 |
-
rows.append({"month": month, "payment": float(bal + interest), "interest": float(interest),
|
| 48 |
-
"principal": float(bal), "balance": 0.0})
|
| 49 |
-
bal = Decimal(0)
|
| 50 |
-
break
|
| 51 |
-
bal -= pay - interest
|
| 52 |
-
row = {"month": month, "payment": float(pay), "interest": float(interest), "principal": float(pay - interest)}
|
| 53 |
-
if month in extras:
|
| 54 |
-
bal -= min(extras[month], bal)
|
| 55 |
-
row["balance"] = float(bal)
|
| 56 |
-
rows.append(row)
|
| 57 |
-
if level < 3 or new_pay is not None:
|
| 58 |
-
break
|
| 59 |
-
lines = [
|
| 60 |
-
f"Principal: {principal}",
|
| 61 |
-
f"Annual interest rate: {rate}% (monthly rate = annual rate / 12)",
|
| 62 |
-
f"Term: {months} months",
|
| 63 |
-
"Monthly payment: the standard annuity payment for the term, rounded to the cent.",
|
| 64 |
-
]
|
| 65 |
-
if extras:
|
| 66 |
-
lines.append("Extra principal payments (made right after that month's regular payment):")
|
| 67 |
-
lines += [f" month {m}: {v}" for m, v in sorted(extras.items())]
|
| 68 |
-
if reset_month:
|
| 69 |
-
lines.append(
|
| 70 |
-
f"Rate reset: from month {reset_month} the annual rate is {new_rate}%. At that point the payment is "
|
| 71 |
-
f"recomputed as the annuity payment on the balance then owed over the {months - reset_month + 1} "
|
| 72 |
-
"months left, rounded to the cent."
|
| 73 |
-
)
|
| 74 |
-
files = {"loan.txt": "\n".join(lines) + "\n"}
|
| 75 |
-
instruction = (
|
| 76 |
-
"loan.txt in /app describes a loan. Write its amortization schedule to /app/schedule.csv with the header "
|
| 77 |
-
"month,payment,interest,principal,balance and one row per month until the loan is paid off, for example "
|
| 78 |
-
"1,1932.56,500.00,1432.56,98567.44. Interest = balance x monthly rate, rounded half up to the cent; "
|
| 79 |
-
"principal = payment - interest; balance is what remains after the row, after any extra payment that "
|
| 80 |
-
"month. If balance plus interest is no more than the payment (or in the last month of the term), that row "
|
| 81 |
-
"pays exactly balance plus interest and the balance is 0."
|
| 82 |
-
)
|
| 83 |
-
artifact = Artifact(
|
| 84 |
-
path="schedule.csv",
|
| 85 |
-
kind="csv",
|
| 86 |
-
key=("month",),
|
| 87 |
-
ordered=True,
|
| 88 |
-
fields=[
|
| 89 |
-
Field("month", "int"),
|
| 90 |
-
Field("payment", "number", tol=0.005),
|
| 91 |
-
Field("interest", "number", tol=0.005),
|
| 92 |
-
Field("principal", "number", tol=0.005),
|
| 93 |
-
Field("balance", "number", tol=0.005),
|
| 94 |
-
],
|
| 95 |
-
expected=rows,
|
| 96 |
-
)
|
| 97 |
-
return Built(instruction=instruction, files=files, artifact=artifact, notes={"payoff_month": month})
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
# ---------------------------------------------------------------- fin_portfolio
|
| 101 |
-
|
| 102 |
-
TICKERS = ["ALDR", "BRKS", "CNDL", "DRFT", "EMBR", "FJRD"]
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
def _trading_days(start: dt.date, n: int) -> list[dt.date]:
|
| 106 |
-
out, d = [], start
|
| 107 |
-
while len(out) < n:
|
| 108 |
-
if d.weekday() < 5:
|
| 109 |
-
out.append(d)
|
| 110 |
-
d += dt.timedelta(days=1)
|
| 111 |
-
return out
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
def build_portfolio(level: int, rng: random.Random) -> Built:
|
| 115 |
-
n_tick, n_days, n_trades = {1: (3, 20, 5), 2: (4, 40, 9), 3: (5, 60, 13)}[level]
|
| 116 |
-
while True:
|
| 117 |
-
tickers = rng.sample(TICKERS, n_tick)
|
| 118 |
-
days = _trading_days(dt.date(2026, 6, 1), n_days)
|
| 119 |
-
split = None
|
| 120 |
-
if level >= 2:
|
| 121 |
-
split = (rng.choice(tickers), days[rng.randint(n_days // 3, 2 * n_days // 3)], rng.choice([2, 3]))
|
| 122 |
-
closes = {}
|
| 123 |
-
for t in tickers:
|
| 124 |
-
p = rng.uniform(20, 300)
|
| 125 |
-
for d in days:
|
| 126 |
-
p *= 1 + rng.gauss(0.0005, 0.018)
|
| 127 |
-
adj = p / split[2] if split and t == split[0] and d >= split[1] else p
|
| 128 |
-
closes[(d, t)] = Decimal(f"{adj:.2f}")
|
| 129 |
-
divs = []
|
| 130 |
-
if level == 3:
|
| 131 |
-
for t in rng.sample(tickers, 2):
|
| 132 |
-
d = rng.choice(days[3:-1])
|
| 133 |
-
if split and d == split[1]:
|
| 134 |
-
continue
|
| 135 |
-
divs.append((d, t, Decimal(f"{rng.uniform(0.2, 1.5):.2f}")))
|
| 136 |
-
cash = Decimal(100000)
|
| 137 |
-
hold = {t: 0 for t in tickers}
|
| 138 |
-
trade_days = sorted(rng.sample(days[:-2], n_trades))
|
| 139 |
-
trades, div_income = [], Decimal(0)
|
| 140 |
-
events = sorted(
|
| 141 |
-
([(split[1], 0, "split", None)] if split else [])
|
| 142 |
-
+ [(d, 1, "div", (t, v)) for d, t, v in divs]
|
| 143 |
-
+ [(d, 2, "trade", None) for d in trade_days],
|
| 144 |
-
key=lambda e: (e[0], e[1]),
|
| 145 |
-
)
|
| 146 |
-
ok = True
|
| 147 |
-
for d, _, kind, info in events:
|
| 148 |
-
if kind == "split":
|
| 149 |
-
hold[split[0]] *= split[2]
|
| 150 |
-
elif kind == "div":
|
| 151 |
-
t, v = info
|
| 152 |
-
div_income += v * hold[t] # holdings at the end of the previous trading day
|
| 153 |
-
cash += v * hold[t]
|
| 154 |
-
else:
|
| 155 |
-
t = rng.choice(tickers)
|
| 156 |
-
price = closes[(d, t)] + Decimal(f"{rng.uniform(-0.5, 0.5):.2f}")
|
| 157 |
-
if hold[t] > 0 and rng.random() < 0.35:
|
| 158 |
-
qty, side = rng.randint(1, hold[t]), "SELL"
|
| 159 |
-
cash += qty * price
|
| 160 |
-
hold[t] -= qty
|
| 161 |
-
else:
|
| 162 |
-
qty, side = rng.randint(5, 200), "BUY"
|
| 163 |
-
if qty * price > cash:
|
| 164 |
-
ok = False
|
| 165 |
-
break
|
| 166 |
-
cash -= qty * price
|
| 167 |
-
hold[t] += qty
|
| 168 |
-
trades.append((d, t, side, qty, price))
|
| 169 |
-
if not ok:
|
| 170 |
-
continue
|
| 171 |
-
last = days[-1]
|
| 172 |
-
values = {t: hold[t] * closes[(last, t)] for t in tickers}
|
| 173 |
-
ranked = sorted(values.items(), key=lambda kv: -kv[1])
|
| 174 |
-
if ranked[0][1] > 0 and (len(ranked) < 2 or ranked[0][1] - ranked[1][1] > 50):
|
| 175 |
-
break
|
| 176 |
-
files = {
|
| 177 |
-
"prices.csv": "date,ticker,close\n"
|
| 178 |
-
+ "".join(f"{d.isoformat()},{t},{closes[(d, t)]}\n" for d in days for t in tickers),
|
| 179 |
-
"trades.csv": "date,ticker,side,shares,price\n"
|
| 180 |
-
+ "".join(f"{d.isoformat()},{t},{s},{q},{p}\n" for d, t, s, q, p in trades),
|
| 181 |
-
}
|
| 182 |
-
notes = []
|
| 183 |
-
if split or divs:
|
| 184 |
-
lines = []
|
| 185 |
-
if split:
|
| 186 |
-
lines.append(
|
| 187 |
-
f"{split[1].isoformat()} {split[0]} {split[2]}-for-1 stock split before the open: every share held "
|
| 188 |
-
"becomes " + str(split[2]) + " shares. Closes and trades from that date on are post-split."
|
| 189 |
-
)
|
| 190 |
-
for d, t, v in sorted(divs):
|
| 191 |
-
lines.append(
|
| 192 |
-
f"{d.isoformat()} {t} cash dividend of {v} per share, paid on shares held at the end of the "
|
| 193 |
-
"previous trading day."
|
| 194 |
-
)
|
| 195 |
-
files["corporate_actions.txt"] = "\n".join(lines) + "\n"
|
| 196 |
-
notes.append("Apply corporate_actions.txt.")
|
| 197 |
-
instruction = (
|
| 198 |
-
"prices.csv and trades.csv in /app are a brokerage account's daily closes and trades. The account starts "
|
| 199 |
-
"with 100000.00 in cash and no shares; trades execute at their listed price (BUY spends cash, SELL adds "
|
| 200 |
-
"it; no fees). " + " ".join(notes) + f" Write /app/positions.csv with the header ticker,shares,close,"
|
| 201 |
-
f"market_value: one row per ticker still held after the last date in prices.csv ({last.isoformat()}), "
|
| 202 |
-
"with its shares, that day's close and shares x close, plus a row CASH,0,0,<cash balance>. "
|
| 203 |
-
"Example: ALDR,120,45.10,5412.00"
|
| 204 |
-
)
|
| 205 |
-
rows = [
|
| 206 |
-
{"ticker": t, "shares": float(hold[t]), "close": float(closes[(last, t)]), "market_value": float(values[t])}
|
| 207 |
-
for t in tickers
|
| 208 |
-
if hold[t] > 0
|
| 209 |
-
] + [{"ticker": "CASH", "shares": 0.0, "close": 0.0, "market_value": float(cash)}]
|
| 210 |
-
artifact = Artifact(
|
| 211 |
-
path="positions.csv",
|
| 212 |
-
kind="csv",
|
| 213 |
-
key=("ticker",),
|
| 214 |
-
fields=[
|
| 215 |
-
Field("ticker", "text"),
|
| 216 |
-
Field("shares", "number", tol=1e-6),
|
| 217 |
-
Field("close", "number", tol=0.005),
|
| 218 |
-
Field("market_value", "number", tol=0.01),
|
| 219 |
-
],
|
| 220 |
-
expected=rows,
|
| 221 |
-
)
|
| 222 |
-
return Built(instruction=instruction, files=files, artifact=artifact, notes={"dividend_income": float(div_income)})
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
FAMILIES = [
|
| 226 |
-
Family("fin_loan", "finance and economics", "Amortize a loan", build_loan),
|
| 227 |
-
Family("fin_portfolio", "finance and economics", "Value a portfolio", build_portfolio),
|
| 228 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/finance3.py
DELETED
|
@@ -1,428 +0,0 @@
|
|
| 1 |
-
"""Finance v3: amortize one loan from a loan book, value a brokerage account, screen invoices for fraud.
|
| 2 |
-
|
| 3 |
-
All three are stdlib csv/json tasks rooted at /root. Each generator computes its expected answer itself;
|
| 4 |
-
the oracle scripts in terminal_desk/oracles/ only prove the files carry everything the answer needs.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import datetime as dt
|
| 8 |
-
import json
|
| 9 |
-
import random
|
| 10 |
-
from decimal import Decimal
|
| 11 |
-
|
| 12 |
-
from .base import Artifact, Built, Family
|
| 13 |
-
from .finance import TICKERS, _payment, _r, _trading_days
|
| 14 |
-
|
| 15 |
-
TOL = 0.005 + 1e-9 # "to the cent": a value two-decimal rounded the same way passes, one cent off fails
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def _num(s) -> float:
|
| 19 |
-
return float(str(s).strip())
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def _col_close(rows: list[dict], want: list[dict], col: str, tol: float = TOL) -> bool:
|
| 23 |
-
return len(rows) == len(want) and all(abs(_num(r[col]) - w[col]) <= tol for r, w in zip(rows, want))
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
# ---------------------------------------------------------------- fin3_loan_schedule
|
| 27 |
-
|
| 28 |
-
LOAN_TERMS = (36, 48, 60)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
class Overpaid(Exception):
|
| 32 |
-
"""An extra would clear the loan; the instruction does not cover that case, so the generator resamples."""
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
def _loan_id(rng: random.Random, used: set) -> str:
|
| 36 |
-
while True:
|
| 37 |
-
lid = f"LN-{rng.randrange(1000, 10000)}"
|
| 38 |
-
if lid not in used:
|
| 39 |
-
used.add(lid)
|
| 40 |
-
return lid
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def _amortize(principal: Decimal, rate: Decimal, term: int, extras: dict, reset) -> list[dict]:
|
| 44 |
-
"""The schedule, in Decimal: v2 build_loan arithmetic plus an extra column. reset = (month, new_rate) or None."""
|
| 45 |
-
pay, bal, cur, month, rows = _payment(principal, rate, term), principal, rate, 0, []
|
| 46 |
-
while bal > 0:
|
| 47 |
-
month += 1
|
| 48 |
-
if reset and month == reset[0]:
|
| 49 |
-
cur = reset[1]
|
| 50 |
-
pay = _payment(bal, cur, term - month + 1)
|
| 51 |
-
interest = _r(bal * cur / 1200)
|
| 52 |
-
if bal + interest <= pay or month == term:
|
| 53 |
-
rows.append({"month": month, "payment": bal + interest, "interest": interest, "principal": bal,
|
| 54 |
-
"extra": Decimal(0), "balance": Decimal(0)})
|
| 55 |
-
break
|
| 56 |
-
bal -= pay - interest
|
| 57 |
-
extra = extras.get(month, Decimal(0))
|
| 58 |
-
if extra >= bal:
|
| 59 |
-
raise Overpaid(f"month {month}: extra {extra} >= balance {bal}")
|
| 60 |
-
bal -= extra
|
| 61 |
-
rows.append({"month": month, "payment": pay, "interest": interest, "principal": pay - interest,
|
| 62 |
-
"extra": extra, "balance": bal})
|
| 63 |
-
return rows
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
def build_loan_schedule(level: int, rng: random.Random) -> Built:
|
| 67 |
-
n_book = {1: 130, 2: 140, 3: 150}[level]
|
| 68 |
-
while True:
|
| 69 |
-
used: set = set()
|
| 70 |
-
book = [(_loan_id(rng, used), Decimal(rng.randrange(100, 900) * 100), Decimal(f"{rng.uniform(4, 8):.3f}"),
|
| 71 |
-
rng.choice(LOAN_TERMS)) for _ in range(n_book)]
|
| 72 |
-
target = rng.randrange(n_book)
|
| 73 |
-
lid, principal, rate, term = book[target]
|
| 74 |
-
extras, ledger, reset, resets, reversed_m = {}, [], None, [], 0
|
| 75 |
-
if level >= 2:
|
| 76 |
-
months = rng.sample(range(3, term // 2), rng.randint(3, 4))
|
| 77 |
-
months.append(rng.choice(months)) # two extras on one payment add up
|
| 78 |
-
for m in months:
|
| 79 |
-
amt = Decimal(rng.randrange(5, 40) * 100)
|
| 80 |
-
extras[m] = extras.get(m, Decimal(0)) + amt
|
| 81 |
-
ledger.append((lid, m, amt, "POSTED"))
|
| 82 |
-
if level == 3: # a reversed extra that would change the answer if applied
|
| 83 |
-
reversed_m = rng.choice([m for m in range(3, term // 2) if m not in extras])
|
| 84 |
-
ledger.append((lid, reversed_m, Decimal(rng.randrange(5, 40) * 100), "REVERSED"))
|
| 85 |
-
for other, _, _, oterm in rng.sample(book[:target] + book[target + 1:], 30):
|
| 86 |
-
for m in rng.sample(range(2, oterm // 2), rng.randint(1, 3)):
|
| 87 |
-
status = "REVERSED" if level == 3 and rng.random() < 0.15 else "POSTED"
|
| 88 |
-
ledger.append((other, m, Decimal(rng.randrange(5, 40) * 100), status))
|
| 89 |
-
rng.shuffle(ledger)
|
| 90 |
-
if level == 3:
|
| 91 |
-
reset = (rng.randint(max(extras) + 1, term - 12), Decimal(f"{float(rate) + rng.uniform(-1.5, 2.5):.3f}"))
|
| 92 |
-
resets = [(lid,) + reset] + [(o, rng.randint(13, t - 12), Decimal(f"{float(r) + rng.uniform(-1, 2):.3f}"))
|
| 93 |
-
for o, _, r, t in rng.sample(book[:target] + book[target + 1:], 14)]
|
| 94 |
-
rng.shuffle(resets)
|
| 95 |
-
try:
|
| 96 |
-
rows = _amortize(principal, rate, term, extras, reset)
|
| 97 |
-
except Overpaid:
|
| 98 |
-
continue
|
| 99 |
-
payoff = rows[-1]["month"]
|
| 100 |
-
if max([0, reversed_m, *extras]) >= payoff or reset and reset[0] >= payoff:
|
| 101 |
-
continue
|
| 102 |
-
break
|
| 103 |
-
files = {
|
| 104 |
-
"data/loans.csv": "loan_id,principal,annual_rate_pct,term_months\n"
|
| 105 |
-
+ "".join(f"{i},{p},{r},{t}\n" for i, p, r, t in book),
|
| 106 |
-
"data/ticket.txt": f"Ticket: SRV-{rng.randrange(10000, 99999)}\nLoan: {lid}\n"
|
| 107 |
-
"Request: rebuild the repayment schedule; the borrower disputes the balance on the statement.\n",
|
| 108 |
-
}
|
| 109 |
-
cols = ["month", "payment", "interest", "principal"] + (["extra"] if level >= 2 else []) + ["balance"]
|
| 110 |
-
inputs = f"ticket /root/data/ticket.txt names loan {lid}." + (
|
| 111 |
-
" Its terms are in the loan book /root/data/loans.csv (loan_id, principal, annual_rate_pct, term_months)"
|
| 112 |
-
if level < 3 else " The loan book /root/data/loans.csv")
|
| 113 |
-
steps = [
|
| 114 |
-
"Payment = annuity payment on the principal over the term at monthly rate annual rate / 1200.",
|
| 115 |
-
"Each month: interest = balance x monthly rate; principal = payment - interest. Round every payment and "
|
| 116 |
-
"interest half up to the cent.",
|
| 117 |
-
]
|
| 118 |
-
if level >= 2:
|
| 119 |
-
files["data/extra_payments.csv"] = "loan_id,payment_no,amount" + (",status" if level == 3 else "") + "\n" + (
|
| 120 |
-
"".join(f"{a},{m},{v:.2f}" + (f",{s}" if level == 3 else "") + "\n" for a, m, v, s in ledger))
|
| 121 |
-
inputs += (". /root/data/extra_payments.csv (loan_id, payment_no, amount) covers every loan" if level == 2 else
|
| 122 |
-
", /root/data/extra_payments.csv and /root/data/rate_resets.csv cover every loan")
|
| 123 |
-
steps.append("Extras are paid right after the regular payment with that payment_no and add up"
|
| 124 |
-
+ ("; REVERSED rows were never paid." if level == 3 else "."))
|
| 125 |
-
if level == 3:
|
| 126 |
-
files["data/rate_resets.csv"] = "loan_id,from_payment,new_rate_pct\n" + "".join(
|
| 127 |
-
f"{a},{m},{r}\n" for a, m, r in resets)
|
| 128 |
-
steps.append("From a reset's from_payment on, use new_rate_pct and re-amortize the balance then owed over the "
|
| 129 |
-
"payments left, this one included.")
|
| 130 |
-
steps.append("If balance + interest <= payment, or in the term's last month, pay balance + interest, set "
|
| 131 |
-
"balance to 0 and stop.")
|
| 132 |
-
ex_p, ex_r = Decimal(rng.randrange(100, 900) * 100), Decimal(f"{rng.uniform(4, 8):.3f}") # another loan
|
| 133 |
-
ex_i = _r(ex_p * ex_r / 1200)
|
| 134 |
-
ex_pay = _payment(ex_p, ex_r, rng.choice(LOAN_TERMS))
|
| 135 |
-
ex_vals = {"payment": ex_pay, "interest": ex_i, "principal": ex_pay - ex_i, "extra": Decimal(0),
|
| 136 |
-
"balance": ex_p - ex_pay + ex_i}
|
| 137 |
-
example = ",".join("1" if c == "month" else f"{ex_vals[c]:.2f}" for c in cols)
|
| 138 |
-
opener = rng.choice(["A borrower disputes a statement:", "Servicing needs a fixed schedule:"])
|
| 139 |
-
instruction = (
|
| 140 |
-
f"{opener} {inputs}.\n\n" + "\n".join(f"{i}. {s}" for i, s in enumerate(steps, 1))
|
| 141 |
-
+ f"\n\nWrite /root/schedule.csv with header {','.join(cols)}, one row per month from 1, two decimals, "
|
| 142 |
-
f"e.g.\n{example}\nValues must match to the cent."
|
| 143 |
-
)
|
| 144 |
-
want = [{c: float(r[c]) for c in cols} for r in rows]
|
| 145 |
-
|
| 146 |
-
def render() -> str:
|
| 147 |
-
return ",".join(cols) + "\n" + "".join(
|
| 148 |
-
",".join(str(r["month"]) if c == "month" else f"{r[c]:.2f}" for c in cols) + "\n" for r in rows)
|
| 149 |
-
|
| 150 |
-
checks = [
|
| 151 |
-
("test_header", lambda p: p["header"] == cols),
|
| 152 |
-
("test_row_count", lambda p: len(p["rows"]) == len(want)),
|
| 153 |
-
("test_months_in_order", lambda p: [r["month"] for r in p["rows"]] == [str(i) for i in range(1, payoff + 1)]),
|
| 154 |
-
] + [(f"test_{c}", lambda p, c=c: _col_close(p["rows"], want, c)) for c in cols[1:]]
|
| 155 |
-
return Built(
|
| 156 |
-
instruction=instruction,
|
| 157 |
-
files=files,
|
| 158 |
-
artifact=Artifact(path="schedule.csv", kind="checks", parse="csv", checks=checks, render=render),
|
| 159 |
-
notes={"payoff_month": payoff, "loan_id": lid},
|
| 160 |
-
root="/root",
|
| 161 |
-
)
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
# ---------------------------------------------------------------- fin3_portfolio_value
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
def build_portfolio_value(level: int, rng: random.Random) -> Built:
|
| 168 |
-
n_tick, n_days, n_trades = {1: (4, 30, 6), 2: (5, 36, 10), 3: (6, 40, 14)}[level]
|
| 169 |
-
while True:
|
| 170 |
-
tickers = sorted(rng.sample(TICKERS, n_tick))
|
| 171 |
-
days = _trading_days(dt.date(2026, 6, 1) + dt.timedelta(days=rng.randrange(0, 60)), n_days)
|
| 172 |
-
split = None
|
| 173 |
-
if level >= 2:
|
| 174 |
-
split = (rng.choice(tickers), days[rng.randint(n_days // 3, 2 * n_days // 3)], rng.choice([2, 3]))
|
| 175 |
-
closes = {}
|
| 176 |
-
for t in tickers:
|
| 177 |
-
p = rng.uniform(20, 300)
|
| 178 |
-
for d in days:
|
| 179 |
-
p *= 1 + rng.gauss(0.0005, 0.018)
|
| 180 |
-
adj = p / split[2] if split and t == split[0] and d >= split[1] else p
|
| 181 |
-
closes[(d, t)] = Decimal(f"{adj:.2f}")
|
| 182 |
-
divs = []
|
| 183 |
-
if level == 3:
|
| 184 |
-
for t in rng.sample(tickers, 2):
|
| 185 |
-
d = rng.choice(days[3:-1])
|
| 186 |
-
if not (split and d == split[1]):
|
| 187 |
-
divs.append((d, t, Decimal(f"{rng.uniform(0.2, 1.5):.2f}")))
|
| 188 |
-
cash, hold = Decimal(100000), {t: 0 for t in tickers}
|
| 189 |
-
trades = []
|
| 190 |
-
events = sorted(([(split[1], 0, "split", None)] if split else [])
|
| 191 |
-
+ [(d, 1, "div", (t, v)) for d, t, v in divs]
|
| 192 |
-
+ [(d, 2, "trade", None) for d in sorted(rng.sample(days[:-2], n_trades))],
|
| 193 |
-
key=lambda e: (e[0], e[1]))
|
| 194 |
-
ok, paid, split_shares = True, Decimal(0), 0
|
| 195 |
-
for d, _, kind, info in events:
|
| 196 |
-
if kind == "split":
|
| 197 |
-
split_shares = hold[split[0]]
|
| 198 |
-
hold[split[0]] *= split[2]
|
| 199 |
-
elif kind == "div":
|
| 200 |
-
paid += info[1] * hold[info[0]] # shares held at the end of the previous trading day
|
| 201 |
-
cash += info[1] * hold[info[0]]
|
| 202 |
-
else:
|
| 203 |
-
t = rng.choice(tickers)
|
| 204 |
-
price = closes[(d, t)] + Decimal(f"{rng.uniform(-0.5, 0.5):.2f}")
|
| 205 |
-
if hold[t] > 0 and rng.random() < 0.35:
|
| 206 |
-
qty, side = rng.randint(1, hold[t]), "SELL"
|
| 207 |
-
cash += qty * price
|
| 208 |
-
hold[t] -= qty
|
| 209 |
-
else:
|
| 210 |
-
qty, side = rng.randint(5, 200), "BUY"
|
| 211 |
-
if qty * price > cash:
|
| 212 |
-
ok = False
|
| 213 |
-
break
|
| 214 |
-
cash -= qty * price
|
| 215 |
-
hold[t] += qty
|
| 216 |
-
trades.append((d, t, side, qty, price))
|
| 217 |
-
if not ok or sum(1 for t in tickers if hold[t]) < 2:
|
| 218 |
-
continue
|
| 219 |
-
if split and not (split_shares and hold[split[0]]) or divs and paid == 0: # the caveat changes the answer
|
| 220 |
-
continue
|
| 221 |
-
break
|
| 222 |
-
last = days[-1]
|
| 223 |
-
want = {t: (hold[t], closes[(last, t)], hold[t] * closes[(last, t)]) for t in tickers if hold[t] > 0}
|
| 224 |
-
want["CASH"] = (0, Decimal(0), cash)
|
| 225 |
-
files = {
|
| 226 |
-
"data/prices.csv": "date,ticker,close\n" + "".join(f"{d.isoformat()},{t},{closes[(d, t)]}\n"
|
| 227 |
-
for d in days for t in tickers),
|
| 228 |
-
"data/trades.csv": "date,ticker,side,shares,price\n" + "".join(f"{d.isoformat()},{t},{s},{q},{p}\n"
|
| 229 |
-
for d, t, s, q, p in trades),
|
| 230 |
-
}
|
| 231 |
-
caveat = ""
|
| 232 |
-
if level >= 2:
|
| 233 |
-
lines = [f"{split[1].isoformat()} {split[0]} {split[2]}-for-1 stock split before the open: every share held "
|
| 234 |
-
f"becomes {split[2]} shares. Closes and trades from that date on are post-split."]
|
| 235 |
-
lines += [f"{d.isoformat()} {t} cash dividend of {v} per share, paid on shares held at the end of the previous "
|
| 236 |
-
"trading day." for d, t, v in sorted(divs)]
|
| 237 |
-
files["data/corporate_actions.txt"] = "\n".join(lines) + "\n"
|
| 238 |
-
caveat = " Apply every event in /root/data/corporate_actions.txt on its date, before that day's trades."
|
| 239 |
-
ex_t = rng.choice(("GLNT", "HRBR", "KSTL")) # not a ticker in any instance
|
| 240 |
-
ex_q, ex_c = rng.randint(5, 300), Decimal(rng.randrange(2000, 30000)) / 100
|
| 241 |
-
opener = rng.choice([
|
| 242 |
-
"You are reconciling a brokerage account for the month-end report.",
|
| 243 |
-
"The operations team needs a month-end valuation of a brokerage account.",
|
| 244 |
-
])
|
| 245 |
-
instruction = (
|
| 246 |
-
f"{opener} /root/data/prices.csv holds daily closes (date, ticker, close) and /root/data/trades.csv the "
|
| 247 |
-
"account's trades (date, ticker, side, shares, price).\n\n"
|
| 248 |
-
"The account starts with 100000.00 in cash and no shares. Replay the trades in date order: a BUY spends "
|
| 249 |
-
"shares x price in cash, a SELL adds it, with no fees." + caveat + "\n\n"
|
| 250 |
-
f"Write /root/positions.csv with the header ticker,shares,close,market_value: one row per ticker still held "
|
| 251 |
-
f"after the last date in prices.csv ({last.isoformat()}), with its shares, that day's close and shares x "
|
| 252 |
-
"close; leave out tickers with zero shares. Add a final row CASH,0,0,<cash balance>. Money has two "
|
| 253 |
-
f"decimals, for example:\n{ex_t},{ex_q},{ex_c:.2f},{ex_q * ex_c:.2f}\n"
|
| 254 |
-
"Shares must match exactly and money to the cent."
|
| 255 |
-
)
|
| 256 |
-
|
| 257 |
-
def render() -> str:
|
| 258 |
-
return "ticker,shares,close,market_value\n" + "".join(
|
| 259 |
-
f"{t},{s},{c:.2f},{v:.2f}\n" for t, (s, c, v) in want.items())
|
| 260 |
-
|
| 261 |
-
def by_ticker(p):
|
| 262 |
-
return {r["ticker"]: r for r in p["rows"]}
|
| 263 |
-
|
| 264 |
-
checks = [
|
| 265 |
-
("test_header", lambda p: p["header"] == ["ticker", "shares", "close", "market_value"]),
|
| 266 |
-
("test_tickers", lambda p: len(p["rows"]) == len(want) and set(by_ticker(p)) == set(want)),
|
| 267 |
-
("test_shares", lambda p: all(_num(by_ticker(p)[t]["shares"]) == s for t, (s, _, _) in want.items())),
|
| 268 |
-
("test_close", lambda p: all(abs(_num(by_ticker(p)[t]["close"]) - float(c)) <= TOL
|
| 269 |
-
for t, (_, c, _) in want.items() if t != "CASH")),
|
| 270 |
-
("test_market_value", lambda p: all(abs(_num(by_ticker(p)[t]["market_value"]) - float(v)) <= 0.01 + 1e-9
|
| 271 |
-
for t, (_, _, v) in want.items() if t != "CASH")),
|
| 272 |
-
("test_cash", lambda p: abs(_num(by_ticker(p)["CASH"]["market_value"]) - float(cash)) <= 0.01 + 1e-9),
|
| 273 |
-
]
|
| 274 |
-
return Built(
|
| 275 |
-
instruction=instruction,
|
| 276 |
-
files=files,
|
| 277 |
-
artifact=Artifact(path="positions.csv", kind="checks", parse="csv", checks=checks, render=render),
|
| 278 |
-
notes={"dividend_income": float(paid), "split_shares": split_shares},
|
| 279 |
-
root="/root",
|
| 280 |
-
)
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
# ---------------------------------------------------------------- fin3_invoice_fraud
|
| 284 |
-
|
| 285 |
-
TOLERANCE_PCT = 2 # an amount more than 2% away from its PO amount is out of tolerance
|
| 286 |
-
REASONS = ("Unknown Vendor", "Missing PO", "Amount Mismatch", "Duplicate Invoice")
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
def _screen(invoices: list[tuple], vendors: dict | None, pos: dict, level: int) -> list[dict]:
|
| 290 |
-
"""The rules in order, first match wins. invoices: (invoice_no, vendor_id, po_number, amount)."""
|
| 291 |
-
report, seen = [], set()
|
| 292 |
-
for row, (no, vid, po, amt) in enumerate(invoices, 1):
|
| 293 |
-
reason = None
|
| 294 |
-
if vendors is not None and vendors.get(vid) != "ACTIVE":
|
| 295 |
-
reason = "Unknown Vendor"
|
| 296 |
-
elif level >= 2 and po not in pos:
|
| 297 |
-
reason = "Missing PO"
|
| 298 |
-
elif abs(amt - pos[po]) * 100 > TOLERANCE_PCT * pos[po]:
|
| 299 |
-
reason = "Amount Mismatch"
|
| 300 |
-
elif level == 3 and (vid, no) in seen:
|
| 301 |
-
reason = "Duplicate Invoice"
|
| 302 |
-
seen.add((vid, no))
|
| 303 |
-
if reason:
|
| 304 |
-
report.append({"row": row, "invoice_no": no, "amount": float(amt), "reason": reason})
|
| 305 |
-
return report
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
def build_invoice_fraud(level: int, rng: random.Random) -> Built:
|
| 309 |
-
n_inv, n_spare = {1: (70, 30), 2: (80, 30), 3: (90, 25)}[level]
|
| 310 |
-
live = REASONS[2:3] if level == 1 else REASONS[:3] if level == 2 else REASONS
|
| 311 |
-
while True:
|
| 312 |
-
vendor_ids = rng.sample(range(101, 200), 18)
|
| 313 |
-
listed = vendor_ids[:14] # in vendors.csv; the last four are not
|
| 314 |
-
inactive = set(rng.sample(listed, 2))
|
| 315 |
-
vendors = {f"V{v}": ("INACTIVE" if v in inactive else "ACTIVE") for v in listed}
|
| 316 |
-
good = [f"V{v}" for v in listed if v not in inactive]
|
| 317 |
-
bad = [f"V{v}" for v in inactive] + [f"V{v}" for v in vendor_ids[14:]]
|
| 318 |
-
po_nums = [f"PO-{n}" for n in rng.sample(range(1000, 10000), n_inv + n_spare + 10)]
|
| 319 |
-
pos = {n: Decimal(rng.randrange(10000, 2000000)) / 100 for n in po_nums[:n_inv + n_spare]}
|
| 320 |
-
po_vendor = {n: rng.choice(good) for n in pos}
|
| 321 |
-
ghost_pos = po_nums[n_inv + n_spare:] # never issued
|
| 322 |
-
inv_nos = iter(rng.sample(range(10000, 100000), n_inv + 5))
|
| 323 |
-
free = list(pos)[:n_inv]
|
| 324 |
-
invoices = []
|
| 325 |
-
for i in range(n_inv):
|
| 326 |
-
po = free[i]
|
| 327 |
-
vid, amt = po_vendor[po], pos[po]
|
| 328 |
-
roll = rng.random()
|
| 329 |
-
if roll < 0.35: # clean but not exact: inside the tolerance
|
| 330 |
-
amt = _r(amt * (1 + Decimal(rng.uniform(-1.5, 1.5)) / 100))
|
| 331 |
-
elif roll < 0.55:
|
| 332 |
-
amt = _r(amt * (1 + Decimal(rng.choice((-1, 1)) * rng.uniform(3, 25)) / 100))
|
| 333 |
-
elif level >= 2 and roll < 0.67:
|
| 334 |
-
vid = rng.choice(bad)
|
| 335 |
-
if rng.random() < 0.5: # also out of tolerance: the order decides the reason
|
| 336 |
-
amt = _r(amt * Decimal("1.1"))
|
| 337 |
-
elif level >= 2 and roll < 0.79:
|
| 338 |
-
po = rng.choice(["", rng.choice(ghost_pos)])
|
| 339 |
-
invoices.append((f"INV-{next(inv_nos)}", vid, po, amt))
|
| 340 |
-
if level == 3:
|
| 341 |
-
for k in rng.sample(range(n_inv // 3), 3): # resubmissions of earlier invoices, appended later
|
| 342 |
-
no, vid, po, amt = invoices[k]
|
| 343 |
-
if rng.random() < 0.3:
|
| 344 |
-
amt = _r(amt * Decimal("1.08")) # resubmitted and inflated: Amount Mismatch outranks Duplicate
|
| 345 |
-
invoices.insert(rng.randrange(k + 5, len(invoices)), (no, vid, po, amt))
|
| 346 |
-
k = rng.randrange(len(invoices)) # same number, another vendor: not a duplicate
|
| 347 |
-
no = invoices[k][0]
|
| 348 |
-
spare = next(n for n in list(pos)[n_inv:] if po_vendor[n] != invoices[k][1])
|
| 349 |
-
invoices.insert(rng.randrange(k + 1, len(invoices) + 1), (no, po_vendor[spare], spare, pos[spare]))
|
| 350 |
-
report = _screen(invoices, vendors if level >= 2 else None, pos, level)
|
| 351 |
-
reasons = [r["reason"] for r in report]
|
| 352 |
-
if not all(reasons.count(x) >= 2 for x in live):
|
| 353 |
-
continue
|
| 354 |
-
if not 0.15 <= len(report) / len(invoices) <= 0.4:
|
| 355 |
-
continue
|
| 356 |
-
if level >= 2: # the status caveat, the unlisted vendor and the rule order each change the answer
|
| 357 |
-
used = {vid for _, vid, _, _ in invoices}
|
| 358 |
-
unknown_over = [r for r in report if r["reason"] == "Unknown Vendor"
|
| 359 |
-
and invoices[r["row"] - 1][2] in pos
|
| 360 |
-
and abs(invoices[r["row"] - 1][3] - pos[invoices[r["row"] - 1][2]]) * 100
|
| 361 |
-
> TOLERANCE_PCT * pos[invoices[r["row"] - 1][2]]]
|
| 362 |
-
if not (used & {f"V{v}" for v in inactive} and used - set(vendors) and unknown_over):
|
| 363 |
-
continue
|
| 364 |
-
break
|
| 365 |
-
files = {
|
| 366 |
-
"data/invoices.csv": "invoice_no,vendor_id,po_number,amount\n"
|
| 367 |
-
+ "".join(f"{no},{vid},{po},{amt:.2f}\n" for no, vid, po, amt in invoices),
|
| 368 |
-
"data/purchase_orders.csv": "po_number,vendor_id,amount\n"
|
| 369 |
-
+ "".join(f"{n},{po_vendor[n]},{a:.2f}\n" for n, a in pos.items()),
|
| 370 |
-
}
|
| 371 |
-
rule_amount = (f"the invoice amount differs from its PO's amount by more than {TOLERANCE_PCT}% of the PO amount")
|
| 372 |
-
if level == 1:
|
| 373 |
-
rules = f"Flag an invoice as Amount Mismatch when {rule_amount}. Every invoice cites a valid PO."
|
| 374 |
-
else:
|
| 375 |
-
files["data/vendors.csv"] = "vendor_id,status\n" + "".join(f"{v},{s}\n" for v, s in vendors.items())
|
| 376 |
-
rules = ("Check each invoice against these rules in order and report only the first that applies:\n"
|
| 377 |
-
"1. Unknown Vendor: vendor_id is not in /root/data/vendors.csv with status ACTIVE.\n"
|
| 378 |
-
"2. Missing PO: po_number is empty or not in the PO list.\n"
|
| 379 |
-
f"3. Amount Mismatch: {rule_amount}.")
|
| 380 |
-
if level == 3:
|
| 381 |
-
rules += "\n4. Duplicate Invoice: an earlier row has the same vendor_id and invoice_no."
|
| 382 |
-
ex = {"row": rng.randint(2, 60), "invoice_no": f"INV-{rng.randrange(10000, 100000)}",
|
| 383 |
-
"amount": float(Decimal(rng.randrange(10000, 2000000)) / 100), "reason": rng.choice(live)}
|
| 384 |
-
opener = rng.choice([
|
| 385 |
-
"Accounts payable must screen this month's invoices before they are paid.",
|
| 386 |
-
"You are screening supplier invoices for fraud before the payment run.",
|
| 387 |
-
])
|
| 388 |
-
instruction = (
|
| 389 |
-
f"{opener} /root/data/invoices.csv has one invoice per row (invoice_no, vendor_id, po_number, amount) and "
|
| 390 |
-
"/root/data/purchase_orders.csv lists the issued purchase orders (po_number, vendor_id, amount).\n\n"
|
| 391 |
-
f"{rules}\n\nWrite /root/fraud_report.json as a JSON array of the flagged invoices only, in file order. Each "
|
| 392 |
-
"item has row (the 1-based position in invoices.csv, header not counted), invoice_no, amount (a number) and "
|
| 393 |
-
f"reason, for example:\n{json.dumps(ex)}"
|
| 394 |
-
)
|
| 395 |
-
|
| 396 |
-
def render() -> str:
|
| 397 |
-
return json.dumps(report, indent=1) + "\n"
|
| 398 |
-
|
| 399 |
-
def rows_of(p):
|
| 400 |
-
return [r["row"] for r in p]
|
| 401 |
-
|
| 402 |
-
checks = [
|
| 403 |
-
("test_is_list", lambda p: isinstance(p, list) and all(isinstance(r, dict) for r in p)),
|
| 404 |
-
("test_record_keys", lambda p: all(set(r) == {"row", "invoice_no", "amount", "reason"} for r in p)),
|
| 405 |
-
("test_file_order", lambda p: rows_of(p) == sorted(set(rows_of(p)))),
|
| 406 |
-
("test_flagged_rows", lambda p: rows_of(p) == [r["row"] for r in report]),
|
| 407 |
-
("test_reasons", lambda p: [r["reason"] for r in p] == reasons),
|
| 408 |
-
("test_invoice_numbers", lambda p: [r["invoice_no"] for r in p] == [r["invoice_no"] for r in report]),
|
| 409 |
-
("test_amounts", lambda p: all(isinstance(r["amount"], (int, float)) and not isinstance(r["amount"], bool)
|
| 410 |
-
and abs(r["amount"] - w["amount"]) <= 0.01 + 1e-9
|
| 411 |
-
for r, w in zip(p, report, strict=True))),
|
| 412 |
-
]
|
| 413 |
-
return Built(
|
| 414 |
-
instruction=instruction,
|
| 415 |
-
files=files,
|
| 416 |
-
artifact=Artifact(path="fraud_report.json", kind="checks", parse="json", checks=checks, render=render),
|
| 417 |
-
notes={"flagged": len(report), "invoices": len(invoices)},
|
| 418 |
-
root="/root",
|
| 419 |
-
)
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
FAMILIES = [
|
| 423 |
-
Family("fin3_loan_schedule", "finance and economics", "Amortize a loan from the loan book", build_loan_schedule,
|
| 424 |
-
v3=True),
|
| 425 |
-
Family("fin3_portfolio_value", "finance and economics", "Value a brokerage account", build_portfolio_value,
|
| 426 |
-
v3=True),
|
| 427 |
-
Family("fin3_invoice_fraud", "finance and economics", "Screen invoices for fraud", build_invoice_fraud, v3=True),
|
| 428 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/industrial.py
DELETED
|
@@ -1,194 +0,0 @@
|
|
| 1 |
-
"""Industrial and physical systems: integrate a flow log; find overdue maintenance."""
|
| 2 |
-
|
| 3 |
-
import datetime as dt
|
| 4 |
-
import random
|
| 5 |
-
|
| 6 |
-
from .base import Artifact, Built, Family, Field
|
| 7 |
-
|
| 8 |
-
# ---------------------------------------------------------------- ind_tank
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
def build_tank(level: int, rng: random.Random) -> Built:
|
| 12 |
-
n_rows = {1: 120, 2: 240, 3: 360}[level]
|
| 13 |
-
t = dt.datetime(2026, 11, 3, 6, 0, 0)
|
| 14 |
-
flow, lvl = rng.uniform(30, 60), rng.uniform(120, 160)
|
| 15 |
-
rows = []
|
| 16 |
-
for i in range(n_rows):
|
| 17 |
-
flow = min(max(flow + rng.gauss(0, 2.5), 5.0), 95.0)
|
| 18 |
-
lvl = min(max(lvl + rng.gauss(0, 1.8), 80.0), 220.0)
|
| 19 |
-
status = "OK"
|
| 20 |
-
if level >= 2 and i > 2 and rng.random() < 0.035:
|
| 21 |
-
status = "FAULT"
|
| 22 |
-
f_out = round(flow, 2) if status == "OK" else rng.choice([0.0, 999.99, round(flow * 3, 2)])
|
| 23 |
-
l_out = round(lvl, 1) if status == "OK" else rng.choice([0.0, 999.9])
|
| 24 |
-
rows.append((t, f_out, l_out, status))
|
| 25 |
-
step = 30 if level < 3 else rng.choice([10, 20, 30, 30, 60])
|
| 26 |
-
t += dt.timedelta(seconds=step)
|
| 27 |
-
good = [r for r in rows if r[3] == "OK"]
|
| 28 |
-
levels = sorted(r[2] for r in good)
|
| 29 |
-
threshold = round(levels[int(len(levels) * rng.uniform(0.6, 0.75))], 0)
|
| 30 |
-
cal_time = None
|
| 31 |
-
if level == 3:
|
| 32 |
-
cal_time = good[len(good) // 2 + rng.randint(-20, 20)][0]
|
| 33 |
-
|
| 34 |
-
def corrected(r):
|
| 35 |
-
return r[1] / 1.04 if cal_time is not None and r[0] < cal_time else r[1]
|
| 36 |
-
|
| 37 |
-
total = 0.0
|
| 38 |
-
for a, b in zip(good, good[1:]):
|
| 39 |
-
total += (corrected(a) + corrected(b)) / 2 * (b[0] - a[0]).total_seconds() / 60
|
| 40 |
-
longest, run_start = 0.0, None
|
| 41 |
-
for r in good:
|
| 42 |
-
if r[2] > threshold:
|
| 43 |
-
if run_start is None:
|
| 44 |
-
run_start = r[0]
|
| 45 |
-
longest = max(longest, (r[0] - run_start).total_seconds() / 60)
|
| 46 |
-
else:
|
| 47 |
-
run_start = None
|
| 48 |
-
csv = "time,flow_lpm,level_cm,status\n" + "".join(
|
| 49 |
-
f"{r[0]:%H:%M:%S},{r[1]:.2f},{r[2]:.1f},{r[3]}\n" for r in rows
|
| 50 |
-
)
|
| 51 |
-
files = {"tank_log.csv": csv}
|
| 52 |
-
rules = [
|
| 53 |
-
"flow_lpm is the inflow in litres per minute; level_cm is the tank level.",
|
| 54 |
-
]
|
| 55 |
-
if level >= 2:
|
| 56 |
-
rules.append("Rows with status FAULT are sensor glitches: drop them before any calculation.")
|
| 57 |
-
if cal_time is not None:
|
| 58 |
-
files["maintenance_note.txt"] = (
|
| 59 |
-
f"Flow meter recalibrated at {cal_time:%H:%M:%S}. Readings taken before that time read 4% high: "
|
| 60 |
-
"divide them by 1.04. Readings from that time on are correct.\n"
|
| 61 |
-
)
|
| 62 |
-
rules.append("Read maintenance_note.txt.")
|
| 63 |
-
instruction = (
|
| 64 |
-
"/app/tank_log.csv is one morning of a holding tank's sensor log. " + " ".join(rules) + " "
|
| 65 |
-
"Total inflow is the trapezoid-rule integral of flow over time between consecutive rows (after any "
|
| 66 |
-
"dropping). A high stretch is a maximal run of consecutive rows (after any dropping) with level_cm "
|
| 67 |
-
f"strictly above {threshold:.0f}; its length runs from its first to its last row. "
|
| 68 |
-
'Write /app/tank_report.json with the keys total_liters (litres) and longest_high_minutes (minutes), '
|
| 69 |
-
'for example {"total_liters": 1234.5, "longest_high_minutes": 12.5}.'
|
| 70 |
-
)
|
| 71 |
-
return Built(
|
| 72 |
-
instruction=instruction,
|
| 73 |
-
files=files,
|
| 74 |
-
artifact=Artifact(
|
| 75 |
-
path="tank_report.json",
|
| 76 |
-
kind="json",
|
| 77 |
-
expected={"total_liters": round(total, 3), "longest_high_minutes": round(longest, 4)},
|
| 78 |
-
fields=[
|
| 79 |
-
Field("total_liters", "number", "total inflow in litres", tol=0.5, rel=0.002),
|
| 80 |
-
Field("longest_high_minutes", "number", "length of the longest high stretch in minutes", tol=0.01),
|
| 81 |
-
],
|
| 82 |
-
),
|
| 83 |
-
)
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
# ---------------------------------------------------------------- ind_maint
|
| 87 |
-
|
| 88 |
-
TYPES = {"press": (250, 30), "lathe": (400, 45), "pump": (1000, 90), "conveyor": (600, 60)}
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
def build_maint(level: int, rng: random.Random) -> Built:
|
| 92 |
-
n_mach, n_days = {1: (6, 20), 2: (10, 45), 3: (12, 60)}[level]
|
| 93 |
-
while True:
|
| 94 |
-
asof = dt.date(2026, 10, 31)
|
| 95 |
-
start = asof - dt.timedelta(days=n_days - 1)
|
| 96 |
-
end = asof + (dt.timedelta(days=3) if level >= 2 else dt.timedelta(0))
|
| 97 |
-
machines, readings, since = [], [], {}
|
| 98 |
-
swapped = None
|
| 99 |
-
swap_id = None
|
| 100 |
-
ids = [f"M{i:02d}" for i in range(1, n_mach + 1)]
|
| 101 |
-
if level == 3:
|
| 102 |
-
swap_id = rng.choice(ids)
|
| 103 |
-
for mid in ids:
|
| 104 |
-
mtype = rng.choice(sorted(TYPES))
|
| 105 |
-
hours_cap, days_cap = TYPES[mtype]
|
| 106 |
-
meter = round(rng.uniform(500, 20000), 1)
|
| 107 |
-
daily = rng.uniform(2, 20)
|
| 108 |
-
service_day = start + dt.timedelta(days=rng.randint(0, n_days - 5))
|
| 109 |
-
swap_day = None
|
| 110 |
-
if mid == swap_id:
|
| 111 |
-
swap_day = service_day + dt.timedelta(days=rng.randint(2, (asof - service_day).days))
|
| 112 |
-
day, at_service, old_last, latest = start, None, None, None
|
| 113 |
-
while day <= end:
|
| 114 |
-
if day == swap_day:
|
| 115 |
-
old_last = meter
|
| 116 |
-
meter = 0.0
|
| 117 |
-
meter = round(meter + max(0.0, rng.gauss(daily, daily * 0.3)), 1)
|
| 118 |
-
if day == service_day:
|
| 119 |
-
at_service = meter
|
| 120 |
-
protected = (service_day, swap_day, swap_day - dt.timedelta(days=1) if swap_day else None)
|
| 121 |
-
missing = level >= 2 and day not in protected and rng.random() < 0.1
|
| 122 |
-
if not missing:
|
| 123 |
-
readings.append((day, mid, meter))
|
| 124 |
-
if day <= asof:
|
| 125 |
-
latest = meter
|
| 126 |
-
day += dt.timedelta(days=1)
|
| 127 |
-
if swap_day is not None:
|
| 128 |
-
hours = old_last - at_service + latest
|
| 129 |
-
swapped = (mid, swap_day)
|
| 130 |
-
else:
|
| 131 |
-
hours = latest - at_service
|
| 132 |
-
days_since = (asof - service_day).days
|
| 133 |
-
overdue = hours >= hours_cap or days_since >= days_cap
|
| 134 |
-
since[mid] = (hours, overdue)
|
| 135 |
-
machines.append((mid, mtype, service_day, at_service))
|
| 136 |
-
ranked = sorted(since.items(), key=lambda kv: -kv[1][0])
|
| 137 |
-
if ranked[0][1][0] - ranked[1][1][0] < 1.0:
|
| 138 |
-
continue
|
| 139 |
-
overdue = sorted(m for m, (_, o) in since.items() if o)
|
| 140 |
-
if 0 < len(overdue) < n_mach:
|
| 141 |
-
break
|
| 142 |
-
rng.shuffle(readings)
|
| 143 |
-
readings.sort(key=lambda r: (r[0], rng.random()))
|
| 144 |
-
files = {
|
| 145 |
-
"machines.csv": "machine,type,last_service_date,meter_at_service\n"
|
| 146 |
-
+ "".join(f"{m},{t},{d.isoformat()},{h:.1f}\n" for m, t, d, h in machines),
|
| 147 |
-
"meter_readings.csv": "date,machine,meter_hours\n"
|
| 148 |
-
+ "".join(f"{d.isoformat()},{m},{h:.1f}\n" for d, m, h in readings),
|
| 149 |
-
"policy.txt": "Service interval by machine type (whichever limit comes first):\n"
|
| 150 |
-
+ "".join(f" {t}: every {h} run-hours or {d} days\n" for t, (h, d) in sorted(TYPES.items())),
|
| 151 |
-
}
|
| 152 |
-
notes = [
|
| 153 |
-
"meter_readings.csv holds end-of-day cumulative meter readings.",
|
| 154 |
-
"Use each machine's latest reading on or before the as-of date.",
|
| 155 |
-
]
|
| 156 |
-
if swapped:
|
| 157 |
-
files["shift_log.txt"] = (
|
| 158 |
-
f"{swapped[1].isoformat()}: {swapped[0]} hour meter failed and was replaced at the start of the day. "
|
| 159 |
-
"The new meter started from 0.0; its readings from that day on count up from zero. The old meter's "
|
| 160 |
-
"last reading is the one from the previous day.\n"
|
| 161 |
-
)
|
| 162 |
-
notes.append("Check shift_log.txt.")
|
| 163 |
-
instruction = (
|
| 164 |
-
"As of 2026-10-31, work out which machines in /app/machines.csv are due for service from "
|
| 165 |
-
"/app/meter_readings.csv and /app/policy.txt. Run-hours since service = meter now minus "
|
| 166 |
-
"meter_at_service. A machine is due when that reaches its type's hour limit or the days since its last "
|
| 167 |
-
"service (as-of date minus service date) reach its day limit. " + " ".join(notes) + " "
|
| 168 |
-
"Write /app/service_schedule.csv with the header machine,run_hours_since_service,due and one row per "
|
| 169 |
-
"machine, due being yes or no, e.g. M01,153.4,no"
|
| 170 |
-
)
|
| 171 |
-
return Built(
|
| 172 |
-
instruction=instruction,
|
| 173 |
-
files=files,
|
| 174 |
-
artifact=Artifact(
|
| 175 |
-
path="service_schedule.csv",
|
| 176 |
-
kind="csv",
|
| 177 |
-
key=("machine",),
|
| 178 |
-
fields=[
|
| 179 |
-
Field("machine", "text"),
|
| 180 |
-
Field("run_hours_since_service", "number", tol=0.15),
|
| 181 |
-
Field("due", "text"),
|
| 182 |
-
],
|
| 183 |
-
expected=[
|
| 184 |
-
{"machine": m, "run_hours_since_service": round(h, 1), "due": "yes" if o else "no"}
|
| 185 |
-
for m, (h, o) in sorted(since.items())
|
| 186 |
-
],
|
| 187 |
-
),
|
| 188 |
-
)
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
FAMILIES = [
|
| 192 |
-
Family("ind_tank", "industrial and physical systems", "Integrate a tank flow log", build_tank),
|
| 193 |
-
Family("ind_maint", "industrial and physical systems", "Find machines due for service", build_maint),
|
| 194 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/industrial3.py
DELETED
|
@@ -1,470 +0,0 @@
|
|
| 1 |
-
"""Industrial and physical systems, v3: service-due report, tank balance, STL part mass.
|
| 2 |
-
|
| 3 |
-
ind3_service_due reshapes industrial.build_maint (hour meters against service intervals) as a /root csv report.
|
| 4 |
-
ind3_tank_balance reshapes industrial.build_tank (trapezoid flow integral, high-level stretch) as a tank balance.
|
| 5 |
-
ind3_stl_mass is new, modeled on SkillsBench 3d-scan-calc: signed-tetrahedron volume of an ASCII STL.
|
| 6 |
-
|
| 7 |
-
All three are stdlib-only. Everything an instance needs beyond the fixed rules lives in its files, because the
|
| 8 |
-
family's one oracle script (terminal_desk/oracles/<family>.py) cannot read the instruction.
|
| 9 |
-
"""
|
| 10 |
-
|
| 11 |
-
import datetime as dt
|
| 12 |
-
import json
|
| 13 |
-
import math
|
| 14 |
-
import random
|
| 15 |
-
|
| 16 |
-
from .base import Artifact, Built, Family
|
| 17 |
-
from .industrial import TYPES # press (250 h, 30 d), lathe (400, 45), pump (1000, 90), conveyor (600, 60)
|
| 18 |
-
|
| 19 |
-
DOMAIN = "industrial and physical systems"
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def _close(got, want: float, tol: float) -> bool:
|
| 23 |
-
return not isinstance(got, bool) and abs(float(got) - want) <= tol + 1e-9
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def _rel(got, want: float, rel: float = 1e-3) -> bool:
|
| 27 |
-
return not isinstance(got, bool) and abs(float(got) - want) <= rel * abs(want) + 1e-12
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
# ---------------------------------------------------------------- ind3_service_due
|
| 31 |
-
|
| 32 |
-
ASOF = dt.date(2026, 10, 31) # fixed: the oracle script cannot read the instruction
|
| 33 |
-
SERVICE_HEADER = ["machine", "run_hours_since_service", "days_since_service", "due"]
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
def _service_instance(level: int, rng: random.Random):
|
| 37 |
-
"""One draw; None when the draw misses a constraint (the caller redraws)."""
|
| 38 |
-
n_mach, n_days = {1: (6, 20), 2: (9, 30), 3: (12, 40)}[level]
|
| 39 |
-
start = ASOF - dt.timedelta(days=n_days - 1)
|
| 40 |
-
end = ASOF + dt.timedelta(days=3 if level >= 2 else 0)
|
| 41 |
-
ids = [f"M{i:02d}" for i in range(1, n_mach + 1)]
|
| 42 |
-
resvc = rng.choice(ids) if level >= 2 else None
|
| 43 |
-
swap_id = rng.choice([m for m in ids if m != resvc]) if level == 3 else None
|
| 44 |
-
exact = rng.choice([m for m in ids if m not in (resvc, swap_id)]) # its days land exactly on the limit
|
| 45 |
-
machines, readings, want, notes = [], [], {}, []
|
| 46 |
-
for mid in ids:
|
| 47 |
-
mtype = rng.choice(sorted(TYPES))
|
| 48 |
-
hcap, dcap = TYPES[mtype]
|
| 49 |
-
swap_day = ASOF - dt.timedelta(days=rng.randint(3, n_days - 3)) if mid == swap_id else None
|
| 50 |
-
if mid == exact:
|
| 51 |
-
last = ASOF - dt.timedelta(days=dcap)
|
| 52 |
-
elif swap_day is not None:
|
| 53 |
-
last = swap_day - dt.timedelta(days=rng.randint(2, 60))
|
| 54 |
-
else:
|
| 55 |
-
last = ASOF - dt.timedelta(days=rng.randint(5, int(dcap * 1.3)))
|
| 56 |
-
listed = last - dt.timedelta(days=rng.randint(20, 120)) if mid == resvc else last
|
| 57 |
-
daily = rng.uniform(2, 20)
|
| 58 |
-
meter = round(rng.uniform(500, 20000), 1)
|
| 59 |
-
at, day, old_last, recs = {}, min(listed, start), None, []
|
| 60 |
-
while day <= end:
|
| 61 |
-
if day == swap_day:
|
| 62 |
-
old_last = meter
|
| 63 |
-
meter = 0.0
|
| 64 |
-
meter = round(meter + max(0.0, rng.gauss(daily, daily * 0.3)), 1)
|
| 65 |
-
if day in (listed, last):
|
| 66 |
-
at[day] = meter
|
| 67 |
-
protected = swap_day is not None and day == swap_day - dt.timedelta(days=1)
|
| 68 |
-
if day >= start and (protected or level == 1 or rng.random() >= 0.1):
|
| 69 |
-
recs.append((day, meter))
|
| 70 |
-
day += dt.timedelta(days=1)
|
| 71 |
-
readings += [(d, mid, v) for d, v in recs]
|
| 72 |
-
upto = [(d, v) for d, v in recs if d <= ASOF]
|
| 73 |
-
if not upto or upto[-1][0] <= last:
|
| 74 |
-
return None
|
| 75 |
-
if swap_day is not None:
|
| 76 |
-
if upto[-1][0] < swap_day or old_last is None:
|
| 77 |
-
return None
|
| 78 |
-
hours = old_last - at[last] + upto[-1][1]
|
| 79 |
-
else:
|
| 80 |
-
hours = upto[-1][1] - at[last]
|
| 81 |
-
hours = round(hours, 1)
|
| 82 |
-
if abs(hours - hcap) < 0.05:
|
| 83 |
-
return None
|
| 84 |
-
days = (ASOF - last).days
|
| 85 |
-
want[mid] = (hours, days, hours >= hcap, days >= dcap)
|
| 86 |
-
machines.append((mid, mtype, listed, at[listed]))
|
| 87 |
-
if mid == resvc:
|
| 88 |
-
notes.append(f"- {last.isoformat()}: {mid} was serviced again; its hour meter read {at[last]:.1f} at "
|
| 89 |
-
"the end of that day. machines.csv still shows the previous service.")
|
| 90 |
-
if mid == swap_id:
|
| 91 |
-
swap = (mid, swap_day)
|
| 92 |
-
due = [m for m, (_, _, h, d) in want.items() if h or d]
|
| 93 |
-
by_hours = [m for m, (_, _, h, d) in want.items() if h and not d]
|
| 94 |
-
by_days = [m for m, (_, _, h, d) in want.items() if d and not h]
|
| 95 |
-
if not (2 <= len(due) <= n_mach - 2 and by_hours and by_days):
|
| 96 |
-
return None
|
| 97 |
-
readings.sort(key=lambda r: (r[0], rng.random()))
|
| 98 |
-
files = {
|
| 99 |
-
"data/machines.csv": "machine,type,last_service_date,meter_at_service\n"
|
| 100 |
-
+ "".join(f"{m},{t},{d.isoformat()},{h:.1f}\n" for m, t, d, h in machines),
|
| 101 |
-
"data/meter_readings.csv": "date,machine,meter_hours\n"
|
| 102 |
-
+ "".join(f"{d.isoformat()},{m},{v:.1f}\n" for d, m, v in readings),
|
| 103 |
-
"data/service_intervals.csv": "type,max_run_hours,max_days\n"
|
| 104 |
-
+ "".join(f"{t},{h},{d}\n" for t, (h, d) in sorted(TYPES.items())),
|
| 105 |
-
}
|
| 106 |
-
if level >= 2:
|
| 107 |
-
other = rng.choice([m for m in ids if m != resvc])
|
| 108 |
-
day = ASOF - dt.timedelta(days=rng.randint(1, 15))
|
| 109 |
-
notes.append(f"- {day.isoformat()}: {other} coolant topped up and guards checked; no service performed.")
|
| 110 |
-
rng.shuffle(notes)
|
| 111 |
-
files["data/notes.md"] = "# Shop floor notes\n\n" + "\n".join(notes) + "\n"
|
| 112 |
-
if level == 3:
|
| 113 |
-
other = rng.choice([m for m in ids if m != swap[0]])
|
| 114 |
-
day = ASOF - dt.timedelta(days=rng.randint(1, n_days - 1))
|
| 115 |
-
log = [
|
| 116 |
-
f"{swap[1].isoformat()}: {swap[0]} hour meter failed and was replaced at the start of the day. The new "
|
| 117 |
-
"meter started from 0.0; its readings from that day on count up from zero. The old meter's last "
|
| 118 |
-
"reading is the one from the previous day.",
|
| 119 |
-
f"{day.isoformat()}: {other} spindle noise reported on the night shift; inspected, no fault found, "
|
| 120 |
-
"meter unchanged.",
|
| 121 |
-
]
|
| 122 |
-
rng.shuffle(log)
|
| 123 |
-
files["data/shift_log.txt"] = "\n".join(log) + "\n"
|
| 124 |
-
return files, want
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
def build_service_due(level: int, rng: random.Random) -> Built:
|
| 128 |
-
while True:
|
| 129 |
-
drawn = _service_instance(level, rng)
|
| 130 |
-
if drawn is not None:
|
| 131 |
-
break
|
| 132 |
-
files, want = drawn
|
| 133 |
-
opener = rng.choice([
|
| 134 |
-
"You are preparing a machine shop's service report as of 2026-10-31.",
|
| 135 |
-
"Our machine shop needs its service-due report as of 2026-10-31.",
|
| 136 |
-
])
|
| 137 |
-
extra = {1: "", 2: " Apply /root/data/notes.md.", 3: " Apply /root/data/notes.md and /root/data/shift_log.txt."}
|
| 138 |
-
instruction = (
|
| 139 |
-
f"{opener} /root/data/machines.csv lists each machine's type, last_service_date and meter_at_service "
|
| 140 |
-
"(the hour meter at that service). /root/data/meter_readings.csv holds end-of-day cumulative "
|
| 141 |
-
"hour-meter readings, and /root/data/service_intervals.csv gives each type's limits.\n\n"
|
| 142 |
-
"For every machine:\n"
|
| 143 |
-
"1. Take its latest reading dated on or before 2026-10-31; days can be missing.\n"
|
| 144 |
-
"2. run_hours_since_service = that reading minus meter_at_service.\n"
|
| 145 |
-
"3. days_since_service = 2026-10-31 minus the last service date.\n"
|
| 146 |
-
"4. It is due when run-hours reach max_run_hours or days reach max_days, whichever comes first; "
|
| 147 |
-
f"exactly reaching a limit counts.{extra[level]}\n\n"
|
| 148 |
-
"Write /root/service_report.csv with the header machine,run_hours_since_service,days_since_service,due, "
|
| 149 |
-
"one row per machine sorted by machine, run-hours to 1 decimal and due as yes or no, e.g. M01,153.4,40,no. "
|
| 150 |
-
"Run-hours are checked within 0.05."
|
| 151 |
-
)
|
| 152 |
-
ids = sorted(want)
|
| 153 |
-
rows = {m: (f"{h:.1f}", d, "yes" if a or b else "no") for m, (h, d, a, b) in want.items()}
|
| 154 |
-
|
| 155 |
-
def render() -> str:
|
| 156 |
-
return ",".join(SERVICE_HEADER) + "\n" + "".join(f"{m},{h},{d},{u}\n" for m, (h, d, u) in sorted(rows.items()))
|
| 157 |
-
|
| 158 |
-
checks = [
|
| 159 |
-
("test_header", lambda p: p["header"] == SERVICE_HEADER),
|
| 160 |
-
("test_row_count", lambda p: len(p["rows"]) == len(ids)),
|
| 161 |
-
("test_machine_order", lambda p: [r["machine"] for r in p["rows"]] == ids),
|
| 162 |
-
("test_run_hours", lambda p: all(_close(r["run_hours_since_service"], want[r["machine"]][0], 0.05)
|
| 163 |
-
for r in p["rows"])),
|
| 164 |
-
("test_days_since_service", lambda p: all(float(r["days_since_service"]) == want[r["machine"]][1]
|
| 165 |
-
for r in p["rows"])),
|
| 166 |
-
("test_due", lambda p: all(r["due"] == rows[r["machine"]][2] for r in p["rows"])),
|
| 167 |
-
]
|
| 168 |
-
return Built(
|
| 169 |
-
instruction=instruction,
|
| 170 |
-
files=files,
|
| 171 |
-
artifact=Artifact(path="service_report.csv", kind="checks", parse="csv", checks=checks, render=render),
|
| 172 |
-
root="/root",
|
| 173 |
-
)
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
# ---------------------------------------------------------------- ind3_tank_balance
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
def _tank_rows(level: int, rng: random.Random):
|
| 180 |
-
n_rows = {1: 120, 2: 240, 3: 360}[level]
|
| 181 |
-
t = dt.datetime(2026, 11, 3, rng.randint(5, 8), rng.choice((0, 15, 30, 45)), 0)
|
| 182 |
-
fin, fout, lvl = rng.uniform(35, 60), rng.uniform(30, 55), rng.uniform(120, 160)
|
| 183 |
-
rows = []
|
| 184 |
-
for i in range(n_rows):
|
| 185 |
-
fin = min(max(fin + rng.gauss(0, 2.5), 5.0), 95.0)
|
| 186 |
-
fout = min(max(fout + rng.gauss(0, 2.5), 5.0), 95.0)
|
| 187 |
-
lvl = min(max(lvl + rng.gauss(0, 1.8), 80.0), 220.0)
|
| 188 |
-
if level >= 2 and 2 < i < n_rows - 1 and rng.random() < 0.04:
|
| 189 |
-
rows.append((t, rng.choice((0.0, 999.9)), rng.choice((0.0, 999.9)), rng.choice((0.0, 999.9)), "FAULT"))
|
| 190 |
-
else:
|
| 191 |
-
rows.append((t, round(fin, 1), round(fout, 1), round(lvl, 1), "OK"))
|
| 192 |
-
t += dt.timedelta(seconds=30 if level < 3 else rng.choice((10, 20, 30, 30, 60)))
|
| 193 |
-
return rows
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
def _trapezoid(pts) -> float:
|
| 197 |
-
"""pts: [(datetime, flow_lpm)] -> litres."""
|
| 198 |
-
return sum((a[1] + b[1]) / 2 * (b[0] - a[0]).total_seconds() / 60 for a, b in zip(pts, pts[1:]))
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
def build_tank_balance(level: int, rng: random.Random) -> Built:
|
| 202 |
-
while True:
|
| 203 |
-
rows = _tank_rows(level, rng)
|
| 204 |
-
good = [r for r in rows if r[4] == "OK"]
|
| 205 |
-
cal, pct = None, rng.choice((3, 4, 5, 6))
|
| 206 |
-
if level == 3:
|
| 207 |
-
cal = good[len(good) // 2 + rng.randint(-20, 20)][0]
|
| 208 |
-
|
| 209 |
-
def inflow(r):
|
| 210 |
-
return r[1] / (1 + pct / 100) if cal is not None and r[0] < cal else r[1]
|
| 211 |
-
|
| 212 |
-
fin = [(r[0], inflow(r)) for r in good]
|
| 213 |
-
total_in, total_out = _trapezoid(fin), _trapezoid([(r[0], r[2]) for r in good])
|
| 214 |
-
minutes = (good[-1][0] - good[0][0]).total_seconds() / 60
|
| 215 |
-
left = sum(a[1] * (b[0] - a[0]).total_seconds() / 60 for a, b in zip(fin, fin[1:]))
|
| 216 |
-
right = sum(b[1] * (b[0] - a[0]).total_seconds() / 60 for a, b in zip(fin, fin[1:]))
|
| 217 |
-
mean = sum(f for _, f in fin) / len(fin) * minutes
|
| 218 |
-
if min(abs(total_in - x) for x in (left, right, mean)) < 0.5:
|
| 219 |
-
continue # a wrong integration rule must not land inside the tolerance
|
| 220 |
-
levels = sorted(r[3] for r in good)
|
| 221 |
-
alarm = int(levels[int(len(levels) * rng.uniform(0.6, 0.75))])
|
| 222 |
-
longest, run_start = 0.0, None
|
| 223 |
-
for r in good:
|
| 224 |
-
if r[3] > alarm:
|
| 225 |
-
run_start = r[0] if run_start is None else run_start
|
| 226 |
-
longest = max(longest, (r[0] - run_start).total_seconds() / 60)
|
| 227 |
-
else:
|
| 228 |
-
run_start = None
|
| 229 |
-
if level == 1 or longest > 0:
|
| 230 |
-
break
|
| 231 |
-
want = {"inflow_liters": total_in, "outflow_liters": total_out, "net_liters": total_in - total_out}
|
| 232 |
-
if level >= 2:
|
| 233 |
-
want["longest_high_minutes"] = longest
|
| 234 |
-
status = level >= 2
|
| 235 |
-
files = {
|
| 236 |
-
"data/tank_log.csv": "time,inflow_lpm,outflow_lpm,level_cm" + (",status" if status else "") + "\n"
|
| 237 |
-
+ "".join(f"{r[0]:%H:%M:%S},{r[1]:.1f},{r[2]:.1f},{r[3]:.1f}" + (f",{r[4]}" if status else "") + "\n"
|
| 238 |
-
for r in rows),
|
| 239 |
-
}
|
| 240 |
-
if level >= 2:
|
| 241 |
-
files["data/README.md"] = (
|
| 242 |
-
"# Tank T-4 log notes\n\n"
|
| 243 |
-
"- Rows with status FAULT are sensor glitches and their readings are meaningless. Drop them before any "
|
| 244 |
-
"calculation; the rows on either side of a dropped row then count as consecutive.\n"
|
| 245 |
-
f"- The high-level alarm setpoint is {alarm} cm.\n"
|
| 246 |
-
"- The outlet meter was replaced in spring and reads true.\n"
|
| 247 |
-
)
|
| 248 |
-
if cal is not None:
|
| 249 |
-
files["data/maintenance_note.txt"] = (
|
| 250 |
-
f"Inlet flow meter recalibrated at {cal:%H:%M:%S}. Inflow readings taken before that time read {pct}% "
|
| 251 |
-
f"high: divide them by 1.0{pct}. Readings from that time on, and all outflow readings, are correct.\n"
|
| 252 |
-
)
|
| 253 |
-
cols = "time (HH:MM:SS), inflow_lpm and outflow_lpm (litres per minute) and level_cm" + (
|
| 254 |
-
", plus a status column" if status else "")
|
| 255 |
-
notes = {1: "", 2: " Read /root/data/README.md first.",
|
| 256 |
-
3: " Read /root/data/README.md and /root/data/maintenance_note.txt first."}[level]
|
| 257 |
-
opener = rng.choice([
|
| 258 |
-
"You are checking the water balance of a holding tank over one morning shift.",
|
| 259 |
-
"The plant team wants a flow balance for holding tank T-4 over this morning's shift.",
|
| 260 |
-
])
|
| 261 |
-
steps = (
|
| 262 |
-
"1. inflow_liters and outflow_liters: the trapezoid-rule integral of each flow over time, i.e. for every "
|
| 263 |
-
"pair of consecutive rows add the average of their two flows times the minutes between them.\n"
|
| 264 |
-
"2. net_liters = inflow_liters minus outflow_liters.\n"
|
| 265 |
-
)
|
| 266 |
-
example = '"inflow_liters": 2710.45, "outflow_liters": 2532.1, "net_liters": 178.35'
|
| 267 |
-
if level >= 2:
|
| 268 |
-
steps += ("3. longest_high_minutes: the longest run of consecutive rows with level_cm strictly above the "
|
| 269 |
-
"high-level alarm setpoint, from its first to its last row (0 if none).\n")
|
| 270 |
-
example += ', "longest_high_minutes": 12.5'
|
| 271 |
-
instruction = (
|
| 272 |
-
f"{opener} /root/data/tank_log.csv has one row per sample: {cols}.{notes}\n\n{steps}\n"
|
| 273 |
-
f"Write /root/tank_report.json as one JSON object, for example {{{example}}}. Round to 2 decimals; "
|
| 274 |
-
"litres are checked within 0.05" + (" and minutes within 0.01." if level >= 2 else ".")
|
| 275 |
-
)
|
| 276 |
-
|
| 277 |
-
def render() -> str:
|
| 278 |
-
return json.dumps({k: round(v, 2) for k, v in want.items()}) + "\n"
|
| 279 |
-
|
| 280 |
-
checks = [
|
| 281 |
-
("test_is_object", lambda p: isinstance(p, dict)),
|
| 282 |
-
("test_keys", lambda p: set(p) == set(want)),
|
| 283 |
-
("test_inflow_liters", lambda p: _close(p["inflow_liters"], want["inflow_liters"], 0.05)),
|
| 284 |
-
("test_outflow_liters", lambda p: _close(p["outflow_liters"], want["outflow_liters"], 0.05)),
|
| 285 |
-
("test_net_liters", lambda p: _close(p["net_liters"], want["net_liters"], 0.05)),
|
| 286 |
-
]
|
| 287 |
-
if level >= 2:
|
| 288 |
-
checks.append(("test_longest_high_minutes",
|
| 289 |
-
lambda p: _close(p["longest_high_minutes"], want["longest_high_minutes"], 0.01)))
|
| 290 |
-
return Built(
|
| 291 |
-
instruction=instruction,
|
| 292 |
-
files=files,
|
| 293 |
-
artifact=Artifact(path="tank_report.json", kind="checks", parse="json", checks=checks, render=render),
|
| 294 |
-
root="/root",
|
| 295 |
-
)
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
# ---------------------------------------------------------------- ind3_stl_mass
|
| 299 |
-
|
| 300 |
-
MATERIALS = [
|
| 301 |
-
("PLA", "PLA filament", 1.24), ("PETG", "PETG filament", 1.27), ("ABS", "ABS filament", 1.04),
|
| 302 |
-
("ASA", "ASA filament", 1.07), ("PA12", "nylon 12 powder", 1.01), ("PC", "polycarbonate", 1.20),
|
| 303 |
-
("AL6061", "aluminium 6061", 2.70), ("SS316L", "stainless steel 316L", 7.98), ("TI64", "titanium Ti-6Al-4V", 4.43),
|
| 304 |
-
("IN718", "Inconel 718", 8.19), ("CUCRZR", "copper CuCrZr", 8.89), ("MS1", "maraging steel MS1", 8.10),
|
| 305 |
-
]
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
def _cross(a, b):
|
| 309 |
-
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
def _prism(rng: random.Random, n: int, bands: int, radius: float, height: float, center, scale: float, inward: bool):
|
| 313 |
-
"""A closed star-shaped prism: fan-triangulated caps, side walls split into `bands` strips.
|
| 314 |
-
Vertices are rounded as written, so every expected value comes from the file's own numbers."""
|
| 315 |
-
cx, cy, z0 = center
|
| 316 |
-
phase = rng.uniform(0, 2 * math.pi)
|
| 317 |
-
ring = []
|
| 318 |
-
for i in range(n):
|
| 319 |
-
a, r = phase + 2 * math.pi * i / n, radius * rng.uniform(0.7, 1.0)
|
| 320 |
-
ring.append((cx + r * math.cos(a), cy + r * math.sin(a)))
|
| 321 |
-
|
| 322 |
-
def q(x, y, z):
|
| 323 |
-
return (round(x / scale, 4), round(y / scale, 4), round(z / scale, 4))
|
| 324 |
-
|
| 325 |
-
zs = [z0 + height * j / bands for j in range(bands + 1)]
|
| 326 |
-
p = [[q(x, y, z) for z in zs] for x, y in ring]
|
| 327 |
-
top, bot = q(cx, cy, zs[-1]), q(cx, cy, zs[0])
|
| 328 |
-
tris = []
|
| 329 |
-
for i in range(n):
|
| 330 |
-
k = (i + 1) % n
|
| 331 |
-
tris.append((top, p[i][bands], p[k][bands]))
|
| 332 |
-
tris.append((bot, p[k][0], p[i][0]))
|
| 333 |
-
for j in range(bands):
|
| 334 |
-
tris.append((p[i][j], p[k][j], p[k][j + 1]))
|
| 335 |
-
tris.append((p[i][j], p[k][j + 1], p[i][j + 1]))
|
| 336 |
-
if inward:
|
| 337 |
-
tris = [(a, c, b) for a, b, c in tris]
|
| 338 |
-
return tris
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
def _measure(tris):
|
| 342 |
-
vol = sum(sum(x * y for x, y in zip(a, _cross(b, c))) for a, b, c in tris) / 6
|
| 343 |
-
area = 0.0
|
| 344 |
-
for a, b, c in tris:
|
| 345 |
-
n = _cross([j - i for i, j in zip(a, b)], [j - i for i, j in zip(a, c)])
|
| 346 |
-
area += math.sqrt(sum(x * x for x in n)) / 2
|
| 347 |
-
return vol, area
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
def _stl_solid(name: str, code: str, tris) -> str:
|
| 351 |
-
out = [f"solid {name} {code}"]
|
| 352 |
-
for a, b, c in tris:
|
| 353 |
-
n = _cross([j - i for i, j in zip(a, b)], [j - i for i, j in zip(a, c)])
|
| 354 |
-
m = math.sqrt(sum(x * x for x in n))
|
| 355 |
-
if m == 0:
|
| 356 |
-
raise ValueError(f"degenerate facet in solid {name}: {a} {b} {c}")
|
| 357 |
-
out.append(" facet normal " + " ".join(f"{x / m:.4f}" for x in n))
|
| 358 |
-
out.append(" outer loop")
|
| 359 |
-
out += [f" vertex {v[0]:.4f} {v[1]:.4f} {v[2]:.4f}" for v in (a, b, c)]
|
| 360 |
-
out += [" endloop", " endfacet"]
|
| 361 |
-
out.append(f"endsolid {name}")
|
| 362 |
-
return "\n".join(out) + "\n"
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
def build_stl_mass(level: int, rng: random.Random) -> Built:
|
| 366 |
-
inches = level == 3
|
| 367 |
-
scale = 25.4 if inches else 1.0
|
| 368 |
-
# L1 draws in exactly the order the first merged version did, so L1 instances are unchanged.
|
| 369 |
-
while True:
|
| 370 |
-
count = {1: 1, 2: rng.randint(3, 4), 3: 5}[level]
|
| 371 |
-
names = [f"body{k}" for k in rng.sample(range(1, 10), count)]
|
| 372 |
-
roles = ["part", "offcut", "trap"][: {1: 1, 2: 2, 3: 3}[level]]
|
| 373 |
-
roles += ["debris"] * (count - len(roles))
|
| 374 |
-
solids = [] # (name, code, tris)
|
| 375 |
-
for role, name in zip(roles, names):
|
| 376 |
-
code = rng.choice(MATERIALS)[0]
|
| 377 |
-
center = (rng.uniform(10, 90), rng.uniform(10, 90), rng.uniform(0, 20))
|
| 378 |
-
if role in ("part", "offcut"): # the offcut draws its facet count like the part: more about half the time
|
| 379 |
-
n, bands = (rng.randint(10, 13), 2) if level < 3 else (rng.randint(10, 12), 2)
|
| 380 |
-
if level == 2:
|
| 381 |
-
n, bands = rng.randint(14, 18), rng.randint(2, 3)
|
| 382 |
-
if role == "part":
|
| 383 |
-
radius, height = rng.uniform(15, 40), rng.uniform(8, 40)
|
| 384 |
-
size = (radius, height)
|
| 385 |
-
else:
|
| 386 |
-
size = (radius * rng.uniform(0.6, 0.8), height * rng.uniform(0.6, 0.9))
|
| 387 |
-
tris = _prism(rng, n, bands, *size, center, scale, rng.random() < 0.5)
|
| 388 |
-
elif role == "trap": # more facets than the part, far less volume
|
| 389 |
-
tris = _prism(rng, rng.randint(26, 32), rng.randint(3, 4), rng.uniform(4, 6), rng.uniform(3, 5),
|
| 390 |
-
center, scale, rng.random() < 0.5)
|
| 391 |
-
else: # fixture pieces and debris
|
| 392 |
-
tris = _prism(rng, rng.randint(4, 6), 1, rng.uniform(1.5, 4), rng.uniform(1, 4), center, scale,
|
| 393 |
-
rng.random() < 0.3)
|
| 394 |
-
solids.append((name, code, tris))
|
| 395 |
-
vols = [abs(_measure(t)[0]) for _, _, t in solids]
|
| 396 |
-
small = all(vols[0] > 3 * v for r, v in zip(roles[1:], vols[1:]) if r != "offcut")
|
| 397 |
-
offcut = level == 1 or 0.3 <= vols[1] / vols[0] <= 0.6
|
| 398 |
-
if small and offcut and len({s[1] for s in solids}) == len(solids):
|
| 399 |
-
break
|
| 400 |
-
if level == 3:
|
| 401 |
-
assert len(solids[2][2]) > len(solids[0][2])
|
| 402 |
-
part_name, part_code, part_tris = solids[0]
|
| 403 |
-
vol, area = _measure(part_tris)
|
| 404 |
-
k = 2.54 if inches else 0.1 # file units -> cm
|
| 405 |
-
density = dict((c, d) for c, _, d in MATERIALS)[part_code]
|
| 406 |
-
volume_cm3, area_cm2 = abs(vol) * k ** 3, area * k ** 2
|
| 407 |
-
want = {"solid": part_name, "material": part_code, "volume_cm3": volume_cm3, "area_cm2": area_cm2,
|
| 408 |
-
"mass_g": volume_cm3 * density}
|
| 409 |
-
order = solids[:]
|
| 410 |
-
rng.shuffle(order)
|
| 411 |
-
table = rng.sample(MATERIALS, 8)
|
| 412 |
-
for _, code, _ in solids:
|
| 413 |
-
if code not in {c for c, _, _ in table}:
|
| 414 |
-
table.append(next(m for m in MATERIALS if m[0] == code))
|
| 415 |
-
rng.shuffle(table)
|
| 416 |
-
files = {
|
| 417 |
-
"data/scan.stl": "".join(_stl_solid(*s) for s in order),
|
| 418 |
-
"data/materials.csv": "code,name,density_g_cm3\n" + "".join(f"{c},{n},{d:.2f}\n" for c, n, d in table),
|
| 419 |
-
}
|
| 420 |
-
if level >= 2:
|
| 421 |
-
notes = ("# Scan notes\n\nThe scanner exported every closed surface it found as its own solid: the part, plus "
|
| 422 |
-
"an offcut from another job, fixture pieces and loose debris picked up on the bed. Only the part "
|
| 423 |
-
"matters. The part is the solid with the largest enclosed volume; ignore the other solids entirely.\n")
|
| 424 |
-
if inches:
|
| 425 |
-
notes += "\nThis scan was exported in inches, not millimetres (1 in = 2.54 cm). Convert before reporting.\n"
|
| 426 |
-
files["data/scan_notes.md"] = notes
|
| 427 |
-
opener = rng.choice([
|
| 428 |
-
"You need to calculate the mass of a 3D printed part from its scan.",
|
| 429 |
-
"Our print shop needs the mass of a finished part, computed from its 3D scan.",
|
| 430 |
-
])
|
| 431 |
-
scope = ("The file holds one solid, the part." if level == 1
|
| 432 |
-
else "Read /root/data/scan_notes.md and apply it; it overrides anything above.")
|
| 433 |
-
instruction = (
|
| 434 |
-
f"{opener} /root/data/scan.stl is an ASCII STL: each solid opens with a line `solid <name> <material code>` "
|
| 435 |
-
"and lists triangular facets as three `vertex x y z` lines, coordinates in millimetres. "
|
| 436 |
-
f"/root/data/materials.csv gives each material code's density in g/cm3. {scope}\n\n"
|
| 437 |
-
"For the part:\n"
|
| 438 |
-
"1. volume: the sum of v1 . (v2 x v3) / 6 over its facets (signed tetrahedra), then the absolute value, "
|
| 439 |
-
"because some exports wind facets inward.\n"
|
| 440 |
-
"2. surface area: the sum of |(v2 - v1) x (v3 - v1)| / 2 over its facets.\n"
|
| 441 |
-
"3. mass = volume in cm3 times the density.\n\n"
|
| 442 |
-
'Write /root/mass_report.json like {"solid": "body2", "material": "PA12", "volume_cm3": 41.268, '
|
| 443 |
-
'"area_cm2": 98.41, "mass_g": 41.68}. Numbers are checked within 0.1% (relative); names exactly.'
|
| 444 |
-
)
|
| 445 |
-
|
| 446 |
-
def render() -> str:
|
| 447 |
-
return json.dumps(want) + "\n"
|
| 448 |
-
|
| 449 |
-
checks = [
|
| 450 |
-
("test_is_object", lambda p: isinstance(p, dict)),
|
| 451 |
-
("test_keys", lambda p: set(p) == set(want)),
|
| 452 |
-
("test_solid", lambda p: p["solid"] == part_name),
|
| 453 |
-
("test_material", lambda p: p["material"] == part_code),
|
| 454 |
-
("test_volume_cm3", lambda p: _rel(p["volume_cm3"], volume_cm3)),
|
| 455 |
-
("test_area_cm2", lambda p: _rel(p["area_cm2"], area_cm2)),
|
| 456 |
-
("test_mass_g", lambda p: _rel(p["mass_g"], want["mass_g"])),
|
| 457 |
-
]
|
| 458 |
-
return Built(
|
| 459 |
-
instruction=instruction,
|
| 460 |
-
files=files,
|
| 461 |
-
artifact=Artifact(path="mass_report.json", kind="checks", parse="json", checks=checks, render=render),
|
| 462 |
-
root="/root",
|
| 463 |
-
)
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
FAMILIES = [
|
| 467 |
-
Family("ind3_service_due", DOMAIN, "Report machines due for service", build_service_due, v3=True),
|
| 468 |
-
Family("ind3_tank_balance", DOMAIN, "Balance a tank's inflow and outflow", build_tank_balance, v3=True),
|
| 469 |
-
Family("ind3_stl_mass", DOMAIN, "Compute a scanned part's mass from an STL", build_stl_mass, v3=True),
|
| 470 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/mathematics.py
DELETED
|
@@ -1,177 +0,0 @@
|
|
| 1 |
-
"""Math and formal reasoning: find a fastest route in a road graph; count integers under constraints."""
|
| 2 |
-
|
| 3 |
-
import heapq
|
| 4 |
-
import random
|
| 5 |
-
|
| 6 |
-
from .base import Artifact, Built, Family, Field
|
| 7 |
-
|
| 8 |
-
# ---------------------------------------------------------------- math_paths
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
def _dijkstra_count(nodes, edges, src, dst):
|
| 12 |
-
adj = {n: [] for n in nodes}
|
| 13 |
-
for u, v, w in edges:
|
| 14 |
-
adj[u].append((v, w))
|
| 15 |
-
dist = {n: None for n in nodes}
|
| 16 |
-
ways = {n: 0 for n in nodes}
|
| 17 |
-
dist[src], ways[src] = 0, 1
|
| 18 |
-
heap = [(0, src)]
|
| 19 |
-
done = set()
|
| 20 |
-
while heap:
|
| 21 |
-
d, u = heapq.heappop(heap)
|
| 22 |
-
if u in done:
|
| 23 |
-
continue
|
| 24 |
-
done.add(u)
|
| 25 |
-
for v, w in adj[u]:
|
| 26 |
-
nd = d + w
|
| 27 |
-
if dist[v] is None or nd < dist[v]:
|
| 28 |
-
dist[v], ways[v] = nd, ways[u]
|
| 29 |
-
heapq.heappush(heap, (nd, v))
|
| 30 |
-
elif nd == dist[v]:
|
| 31 |
-
ways[v] += ways[u]
|
| 32 |
-
return dist[dst], ways[dst]
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
def _dijkstra_path(nodes, edges, src, dst):
|
| 36 |
-
adj = {n: [] for n in nodes}
|
| 37 |
-
for u, v, w in edges:
|
| 38 |
-
adj[u].append((v, w))
|
| 39 |
-
dist, prev = {src: 0}, {}
|
| 40 |
-
heap = [(0, src)]
|
| 41 |
-
while heap:
|
| 42 |
-
d, u = heapq.heappop(heap)
|
| 43 |
-
if d > dist[u]:
|
| 44 |
-
continue
|
| 45 |
-
for v, w in adj[u]:
|
| 46 |
-
if v not in dist or d + w < dist[v]:
|
| 47 |
-
dist[v], prev[v] = d + w, u
|
| 48 |
-
heapq.heappush(heap, (d + w, v))
|
| 49 |
-
path = [dst]
|
| 50 |
-
while path[-1] != src:
|
| 51 |
-
path.append(prev[path[-1]])
|
| 52 |
-
return path[::-1]
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
def build_paths(level: int, rng: random.Random) -> Built:
|
| 56 |
-
n_nodes, out_deg = {1: (8, 2), 2: (15, 3), 3: (25, 3)}[level]
|
| 57 |
-
while True:
|
| 58 |
-
nodes = [f"N{i:02d}" for i in range(1, n_nodes + 1)]
|
| 59 |
-
src, dst = nodes[0], nodes[-1]
|
| 60 |
-
edges, seen = [], set()
|
| 61 |
-
for u in nodes:
|
| 62 |
-
for v in rng.sample([x for x in nodes if x != u], out_deg):
|
| 63 |
-
if (u, v) not in seen:
|
| 64 |
-
seen.add((u, v))
|
| 65 |
-
edges.append((u, v, rng.randint(1, 6)))
|
| 66 |
-
closed_edges, closed_nodes = set(), set()
|
| 67 |
-
if level == 3:
|
| 68 |
-
closed_edges = set(rng.sample([(u, v) for u, v, _ in edges], 6))
|
| 69 |
-
closed_nodes = set(rng.sample(nodes[1:-1], 2))
|
| 70 |
-
live = [
|
| 71 |
-
(u, v, w)
|
| 72 |
-
for u, v, w in edges
|
| 73 |
-
if (u, v) not in closed_edges and u not in closed_nodes and v not in closed_nodes
|
| 74 |
-
]
|
| 75 |
-
cost, ways = _dijkstra_count(nodes, live, src, dst)
|
| 76 |
-
if cost is None or ways < (1 if level == 1 else 2) or cost < 4:
|
| 77 |
-
continue
|
| 78 |
-
if level == 3:
|
| 79 |
-
full_cost, full_ways = _dijkstra_count(nodes, edges, src, dst)
|
| 80 |
-
if (full_cost, full_ways) == (cost, ways):
|
| 81 |
-
continue
|
| 82 |
-
break
|
| 83 |
-
rng.shuffle(edges)
|
| 84 |
-
files = {"roads.csv": "from,to,minutes\n" + "".join(f"{u},{v},{w}\n" for u, v, w in edges)}
|
| 85 |
-
extra = ""
|
| 86 |
-
if level == 3:
|
| 87 |
-
files["closures.txt"] = (
|
| 88 |
-
"Closed roads (one way, from -> to):\n"
|
| 89 |
-
+ "".join(f" {u} -> {v}\n" for u, v in sorted(closed_edges))
|
| 90 |
-
+ "Closed junctions (no road into or out of them can be used):\n"
|
| 91 |
-
+ "".join(f" {n}\n" for n in sorted(closed_nodes))
|
| 92 |
-
)
|
| 93 |
-
extra = ", avoiding the closed roads and junctions in closures.txt"
|
| 94 |
-
instruction = (
|
| 95 |
-
f"roads.csv lists one-way roads between junctions with their travel time in minutes. Find a fastest route "
|
| 96 |
-
f"from {src} to {dst}{extra}. "
|
| 97 |
-
f"Write the junction ids of the route in order, space separated, on one line in /app/route.txt, "
|
| 98 |
-
f"starting with {src} and ending with {dst}. Any fastest route is accepted."
|
| 99 |
-
)
|
| 100 |
-
best_path = _dijkstra_path(nodes, live, src, dst)
|
| 101 |
-
live_w = {}
|
| 102 |
-
for u, v, w in live:
|
| 103 |
-
live_w[(u, v)] = min(w, live_w.get((u, v), w))
|
| 104 |
-
|
| 105 |
-
def verify(app: str) -> bool:
|
| 106 |
-
from ..core.grading import read_artifact # grading imports the families package
|
| 107 |
-
|
| 108 |
-
data = read_artifact(app, "route.txt")
|
| 109 |
-
if data is None:
|
| 110 |
-
return False
|
| 111 |
-
route = data.decode("utf-8", errors="replace").split()
|
| 112 |
-
if len(route) < 2 or route[0] != src or route[-1] != dst:
|
| 113 |
-
return False
|
| 114 |
-
total = 0
|
| 115 |
-
for u, v in zip(route, route[1:]):
|
| 116 |
-
if (u, v) not in live_w:
|
| 117 |
-
return False
|
| 118 |
-
total += live_w[(u, v)]
|
| 119 |
-
return total == cost
|
| 120 |
-
|
| 121 |
-
return Built(
|
| 122 |
-
instruction=instruction,
|
| 123 |
-
files=files,
|
| 124 |
-
artifact=Artifact(path="route.txt", kind="custom", verify=verify, render=lambda: " ".join(best_path) + "\n"),
|
| 125 |
-
notes={"min_minutes": cost, "num_fastest_routes": ways},
|
| 126 |
-
)
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
# ---------------------------------------------------------------- math_count
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
def build_count(level: int, rng: random.Random) -> Built:
|
| 133 |
-
while True:
|
| 134 |
-
n = {1: rng.randint(5000, 20000), 2: rng.randint(50000, 200000), 3: rng.randint(400000, 900000)}[level]
|
| 135 |
-
a, b = rng.sample(range(3, 14), 2)
|
| 136 |
-
c = rng.choice([x for x in range(2, 10) if a % x and b % x])
|
| 137 |
-
d = rng.randint(3, 7)
|
| 138 |
-
conds = [f"is divisible by {a} or by {b} (or both)", f"is not divisible by {c}"]
|
| 139 |
-
tests = [lambda x: x % a == 0 or x % b == 0, lambda x: x % c != 0]
|
| 140 |
-
if level >= 2:
|
| 141 |
-
conds.append(f"has a digit sum divisible by {d}")
|
| 142 |
-
tests.append(lambda x: sum(map(int, str(x))) % d == 0)
|
| 143 |
-
if level >= 3:
|
| 144 |
-
conds.append("is not a palindrome (reads differently backwards)")
|
| 145 |
-
conds.append("has no two equal adjacent digits")
|
| 146 |
-
tests.append(lambda x: str(x) != str(x)[::-1])
|
| 147 |
-
tests.append(lambda x: all(p != q for p, q in zip(str(x), str(x)[1:])))
|
| 148 |
-
hits = [x for x in range(1, n + 1) if all(t(x) for t in tests)]
|
| 149 |
-
if len(hits) >= 50:
|
| 150 |
-
break
|
| 151 |
-
k = rng.randint(len(hits) // 3, len(hits) - 1)
|
| 152 |
-
text = f"Consider the integers from 1 to {n} inclusive. Keep a number when it:\n" + "".join(
|
| 153 |
-
f" - {c_}\n" for c_ in conds
|
| 154 |
-
)
|
| 155 |
-
instruction = (
|
| 156 |
-
"problem.txt defines a set of integers. Write /app/results.json with three integer keys: "
|
| 157 |
-
f'"count" (how many integers are in the set), "kth_smallest" (the integer at position {k} when the set is sorted ascending, counting from 1) '
|
| 158 |
-
'and "largest" (the largest integer in the set).'
|
| 159 |
-
)
|
| 160 |
-
expected = {"count": len(hits), "kth_smallest": hits[k - 1], "largest": hits[-1]}
|
| 161 |
-
return Built(
|
| 162 |
-
instruction=instruction,
|
| 163 |
-
files={"problem.txt": text},
|
| 164 |
-
artifact=Artifact(
|
| 165 |
-
path="results.json",
|
| 166 |
-
kind="json",
|
| 167 |
-
expected=expected,
|
| 168 |
-
fields=[Field("count", "int"), Field("kth_smallest", "int"), Field("largest", "int")],
|
| 169 |
-
),
|
| 170 |
-
notes=expected,
|
| 171 |
-
)
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
FAMILIES = [
|
| 175 |
-
Family("math_paths", "math and formal reasoning", "Count fastest routes", build_paths),
|
| 176 |
-
Family("math_count", "math and formal reasoning", "Count integers under constraints", build_count),
|
| 177 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/mathematics3.py
DELETED
|
@@ -1,471 +0,0 @@
|
|
| 1 |
-
"""Math and formal reasoning, v3: a fastest route under closures, counting raffle winners, exam-slot sequencing.
|
| 2 |
-
|
| 3 |
-
Each verifier accepts any optimal answer: it replays the submitted route or schedule and compares its value
|
| 4 |
-
with the optimum the generator computed itself (SkillsBench pddl-tpp-planning, exam-block-sequencing).
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import heapq
|
| 8 |
-
import itertools
|
| 9 |
-
import json
|
| 10 |
-
import random
|
| 11 |
-
|
| 12 |
-
from .base import Artifact, Built, Family
|
| 13 |
-
|
| 14 |
-
INF = float("inf")
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def _is_int(x) -> bool:
|
| 18 |
-
return isinstance(x, int) and not isinstance(x, bool)
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
# ---------------------------------------------------------------- math3_route_plan
|
| 22 |
-
|
| 23 |
-
CITIES = ("Northgate", "Riverton", "Ashford", "Millbrook", "Eastvale", "Harbor Point", "Kingsbridge")
|
| 24 |
-
VEHICLES = ("delivery van", "parts truck", "courier van", "service truck")
|
| 25 |
-
OPENERS = (
|
| 26 |
-
"You are planning a {vehicle}'s route across {city}.",
|
| 27 |
-
"Our {city} dispatcher needs the fastest route for a {vehicle}.",
|
| 28 |
-
"You need the quickest route across {city} for a {vehicle}.",
|
| 29 |
-
)
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
def _earliest(adj: dict, src: str, windows: dict) -> tuple[dict, dict]:
|
| 33 |
-
"""Earliest-arrival Dijkstra. windows[(u, v)] = (a, b): the road cannot be entered at a <= t < b; waiting is
|
| 34 |
-
allowed, so arrival times are FIFO and the label-setting search is exact."""
|
| 35 |
-
best, prev, heap = {src: 0}, {}, [(0, src)]
|
| 36 |
-
while heap:
|
| 37 |
-
t, u = heapq.heappop(heap)
|
| 38 |
-
if t > best[u]:
|
| 39 |
-
continue
|
| 40 |
-
for v, w in adj.get(u, ()):
|
| 41 |
-
a, b = windows.get((u, v), (0, 0))
|
| 42 |
-
arrive = (b if a <= t < b else t) + w
|
| 43 |
-
if arrive < best.get(v, INF):
|
| 44 |
-
best[v], prev[v] = arrive, u
|
| 45 |
-
heapq.heappush(heap, (arrive, v))
|
| 46 |
-
return best, prev
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
def _adj(roads: dict) -> dict:
|
| 50 |
-
adj = {}
|
| 51 |
-
for (u, v), w in roads.items():
|
| 52 |
-
adj.setdefault(u, []).append((v, w))
|
| 53 |
-
return adj
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
def _trace(prev: dict, src: str, dst: str) -> list[str]:
|
| 57 |
-
path = [dst]
|
| 58 |
-
while path[-1] != src:
|
| 59 |
-
path.append(prev[path[-1]])
|
| 60 |
-
return path[::-1]
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
def _route_instance(level: int, rng: random.Random):
|
| 64 |
-
n, deg, n_closed_roads, n_closed_nodes, n_timed = {1: (30, 3, 0, 0, 0), 2: (45, 3, 6, 2, 0),
|
| 65 |
-
3: (60, 3, 6, 2, 8)}[level]
|
| 66 |
-
prefix = rng.choice("JNX")
|
| 67 |
-
nodes = [f"{prefix}{i:02d}" for i in range(1, n + 1)]
|
| 68 |
-
src, dst = rng.sample(nodes, 2)
|
| 69 |
-
roads = {}
|
| 70 |
-
for u in nodes:
|
| 71 |
-
for v in rng.sample([x for x in nodes if x != u], deg):
|
| 72 |
-
roads[(u, v)] = rng.randint(2, 15)
|
| 73 |
-
full, full_prev = _earliest(_adj(roads), src, {})
|
| 74 |
-
if full.get(dst, 0) < 15:
|
| 75 |
-
return None
|
| 76 |
-
if level == 1: # the one-way caveat must bite: driving roads both ways finds a faster route
|
| 77 |
-
both = dict(roads)
|
| 78 |
-
for (u, v), w in roads.items():
|
| 79 |
-
both[(v, u)] = min(w, both.get((v, u), INF))
|
| 80 |
-
if _earliest(_adj(both), src, {})[0][dst] >= full[dst]:
|
| 81 |
-
return None
|
| 82 |
-
return nodes, src, dst, roads, set(), set(), {}, full[dst], _trace(full_prev, src, dst)
|
| 83 |
-
# closures: one junction and one road on the open optimum, the rest at random
|
| 84 |
-
on_path = _trace(full_prev, src, dst)
|
| 85 |
-
closed_nodes = {rng.choice(on_path[1:-1])} if len(on_path) > 2 else set()
|
| 86 |
-
while len(closed_nodes) < n_closed_nodes:
|
| 87 |
-
closed_nodes.add(rng.choice([x for x in nodes if x not in (src, dst)]))
|
| 88 |
-
closed_roads = {rng.choice(list(zip(on_path, on_path[1:])))}
|
| 89 |
-
while len(closed_roads) < n_closed_roads:
|
| 90 |
-
closed_roads.add(rng.choice(list(roads)))
|
| 91 |
-
live = {(u, v): w for (u, v), w in roads.items()
|
| 92 |
-
if (u, v) not in closed_roads and u not in closed_nodes and v not in closed_nodes}
|
| 93 |
-
static, static_prev = _earliest(_adj(live), src, {})
|
| 94 |
-
if static.get(dst, 0) < 15 or static[dst] == full[dst]:
|
| 95 |
-
return None
|
| 96 |
-
if level == 2:
|
| 97 |
-
return nodes, src, dst, roads, closed_roads, closed_nodes, {}, static[dst], _trace(static_prev, src, dst)
|
| 98 |
-
# timed closures: two or three on the static optimum around the minute the van reaches them, the rest at random
|
| 99 |
-
path = _trace(static_prev, src, dst)
|
| 100 |
-
windows = {}
|
| 101 |
-
for u, v in rng.sample(list(zip(path, path[1:])), min(rng.randint(2, 3), len(path) - 1)):
|
| 102 |
-
t = static[u]
|
| 103 |
-
windows[(u, v)] = (max(0, t - rng.randint(0, 4)), t + rng.randint(4, 14))
|
| 104 |
-
while len(windows) < n_timed:
|
| 105 |
-
a = rng.randint(0, 50)
|
| 106 |
-
windows.setdefault(rng.choice(list(live)), (a, a + rng.randint(5, 20)))
|
| 107 |
-
timed, timed_prev = _earliest(_adj(live), src, windows)
|
| 108 |
-
dropped = _earliest(_adj({k: w for k, w in live.items() if k not in windows}), src, {})[0]
|
| 109 |
-
if dst not in timed or timed[dst] == static[dst] or dropped.get(dst) == timed[dst]:
|
| 110 |
-
return None
|
| 111 |
-
return nodes, src, dst, roads, closed_roads, closed_nodes, windows, timed[dst], _trace(timed_prev, src, dst)
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
def build_route(level: int, rng: random.Random) -> Built:
|
| 115 |
-
for _ in range(500):
|
| 116 |
-
got = _route_instance(level, rng)
|
| 117 |
-
if got:
|
| 118 |
-
break
|
| 119 |
-
else:
|
| 120 |
-
raise RuntimeError(f"math3_route_plan L{level}: no instance in 500 draws")
|
| 121 |
-
nodes, src, dst, roads, closed_roads, closed_nodes, windows, best, best_path = got
|
| 122 |
-
city, vehicle = rng.choice(CITIES), rng.choice(VEHICLES)
|
| 123 |
-
depart = rng.choice(("06:45", "07:30", "08:00", "08:15", "09:00"))
|
| 124 |
-
order = list(roads)
|
| 125 |
-
rng.shuffle(order)
|
| 126 |
-
lines = [json.dumps({"from": u, "to": v, "minutes": roads[(u, v)]}) for u, v in order]
|
| 127 |
-
graph = '{"roads": [\n' + ",\n".join(lines) + '\n],\n"junctions": ' + json.dumps(sorted(nodes)) + "}\n"
|
| 128 |
-
files = {
|
| 129 |
-
"graph.json": graph,
|
| 130 |
-
"request.json": json.dumps({"vehicle": f"{vehicle} {rng.randint(2, 40)}", "from": src, "to": dst,
|
| 131 |
-
"depart": depart}) + "\n",
|
| 132 |
-
}
|
| 133 |
-
if level >= 2:
|
| 134 |
-
md = [f"# {city} closures, today", "", "## Closed roads (one way)"]
|
| 135 |
-
md += [f"- {u} -> {v}" for u, v in sorted(closed_roads)]
|
| 136 |
-
md += ["", "## Closed junctions"] + [f"- {x}" for x in sorted(closed_nodes)]
|
| 137 |
-
if windows:
|
| 138 |
-
md += ["", "## Timed closures"]
|
| 139 |
-
md += [f"- {u} -> {v}: closed from minute {a} to minute {b}" for (u, v), (a, b) in sorted(windows.items())]
|
| 140 |
-
files["closures.md"] = "\n".join(md) + "\n"
|
| 141 |
-
u0, v0 = rng.choice([(u, v) for u, v in order if (v, u) not in roads])
|
| 142 |
-
ex = rng.sample([x for x in nodes if x not in (src, dst)], 3) # format only: not the requested endpoints
|
| 143 |
-
parts = [OPENERS[rng.randrange(3)].format(vehicle=vehicle, city=city),
|
| 144 |
-
"It must arrive as early as possible.\n",
|
| 145 |
-
"- /app/request.json: the start junction, the destination and the departure time.",
|
| 146 |
-
f"- /app/graph.json: each road's start junction, end junction and travel time in "
|
| 147 |
-
f"minutes. Roads are one-way: a road from {u0} to {v0} cannot be driven from {v0} to {u0}."]
|
| 148 |
-
if level >= 2:
|
| 149 |
-
timed_clause = " and timed closures" if windows else ""
|
| 150 |
-
parts.append(f"- /app/closures.md: today's closed roads, closed junctions{timed_clause}.\n")
|
| 151 |
-
rule = "A closed road, or any road into or out of a closed junction, cannot be used."
|
| 152 |
-
if windows:
|
| 153 |
-
rule += (" A timed-closure road cannot be entered while closed (minutes from departure), but the "
|
| 154 |
-
"vehicle may wait at a junction until it reopens; waiting counts toward the total.")
|
| 155 |
-
parts.append(rule)
|
| 156 |
-
parts.append(f"\nWrite /app/route.json with the junctions of the route in order and the total minutes from "
|
| 157 |
-
f'departure to arrival, e.g. {{"path": {json.dumps(ex)}, "total_minutes": {rng.randint(20, 60)}}}. '
|
| 158 |
-
f"The path runs from the start to the destination on open roads, and total_minutes is the integer "
|
| 159 |
-
f"time it takes. Any fastest route is accepted.")
|
| 160 |
-
instruction = " ".join(parts[:2]) + "\n" + "\n".join(parts[2:])
|
| 161 |
-
|
| 162 |
-
live = {(u, v): w for (u, v), w in roads.items()
|
| 163 |
-
if (u, v) not in closed_roads and u not in closed_nodes and v not in closed_nodes}
|
| 164 |
-
|
| 165 |
-
def replay(path: list) -> int:
|
| 166 |
-
t = 0
|
| 167 |
-
for u, v in zip(path, path[1:]):
|
| 168 |
-
a, b = windows.get((u, v), (0, 0))
|
| 169 |
-
t = (b if a <= t < b else t) + live[(u, v)]
|
| 170 |
-
return t
|
| 171 |
-
|
| 172 |
-
checks = [
|
| 173 |
-
("test_is_object", lambda p: isinstance(p, dict)),
|
| 174 |
-
("test_keys", lambda p: set(p) == {"path", "total_minutes"} and isinstance(p["path"], list)
|
| 175 |
-
and len(p["path"]) >= 2 and all(isinstance(x, str) for x in p["path"]) and _is_int(p["total_minutes"])),
|
| 176 |
-
("test_endpoints", lambda p: p["path"][0] == src and p["path"][-1] == dst),
|
| 177 |
-
("test_hops_open", lambda p: all((u, v) in live for u, v in zip(p["path"], p["path"][1:]))),
|
| 178 |
-
("test_total_matches_path", lambda p: replay(p["path"]) == p["total_minutes"]),
|
| 179 |
-
("test_total_optimal", lambda p: p["total_minutes"] == best),
|
| 180 |
-
]
|
| 181 |
-
if replay(best_path) != best:
|
| 182 |
-
raise RuntimeError(f"math3_route_plan L{level}: generator path replays to {replay(best_path)}, not {best}")
|
| 183 |
-
return Built(
|
| 184 |
-
instruction=instruction,
|
| 185 |
-
files=files,
|
| 186 |
-
artifact=Artifact(path="route.json", kind="checks", parse="json", checks=checks,
|
| 187 |
-
render=lambda: json.dumps({"path": best_path, "total_minutes": best}) + "\n"),
|
| 188 |
-
notes={"src": src, "dst": dst, "min_minutes": best, "timed": len(windows)},
|
| 189 |
-
root="/app",
|
| 190 |
-
)
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
# ---------------------------------------------------------------- math3_count_items
|
| 194 |
-
|
| 195 |
-
EVENTS = ("spring", "harvest", "winter", "founders' day", "summer fair", "library")
|
| 196 |
-
BOOTHS = ("A1", "A2", "B1", "B2", "B3", "C1", "C4", "D2")
|
| 197 |
-
VOID_REASONS = ("damaged", "unpaid", "duplicate print", "returned", "misprint")
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
def _count_instance(level: int, rng: random.Random):
|
| 201 |
-
n_rows = {1: 120, 2: 260, 3: 380}[level]
|
| 202 |
-
a, b = rng.sample(range(3, 14), 2)
|
| 203 |
-
c = rng.choice([x for x in range(2, 10) if a % x and b % x])
|
| 204 |
-
d, m = rng.choice((3, 4, 5)), rng.randint(3, 9)
|
| 205 |
-
|
| 206 |
-
def wins(x: int) -> bool:
|
| 207 |
-
if not (x % a == 0 or x % b == 0) or x % c == 0:
|
| 208 |
-
return False
|
| 209 |
-
return level == 1 or sum(map(int, str(x))) % d == 0
|
| 210 |
-
|
| 211 |
-
numbers, seen = [], set()
|
| 212 |
-
while len(numbers) < n_rows:
|
| 213 |
-
if level >= 2 and numbers and rng.random() < 0.07:
|
| 214 |
-
numbers.append(rng.choice(numbers)) # a reprint: the same number on a second ticket
|
| 215 |
-
continue
|
| 216 |
-
base = rng.choice((a, b))
|
| 217 |
-
x = rng.randrange(100000 // base + 1, 999999 // base + 1) * base if rng.random() < 0.6 else \
|
| 218 |
-
rng.randint(100000, 999999)
|
| 219 |
-
if x not in seen:
|
| 220 |
-
seen.add(x)
|
| 221 |
-
numbers.append(x)
|
| 222 |
-
tickets = [(f"T{i:04d}", x, rng.choice(BOOTHS)) for i, x in enumerate(numbers, 1)]
|
| 223 |
-
voided = {t for t, _, _ in rng.sample(tickets, n_rows // 12)} if level >= 3 else set()
|
| 224 |
-
alive = [x for t, x, _ in tickets if t not in voided]
|
| 225 |
-
winners = sorted({x for x in alive if wins(x)})
|
| 226 |
-
if len(winners) < 20:
|
| 227 |
-
return None
|
| 228 |
-
# each caveat must change the answer
|
| 229 |
-
if level >= 2 and len([x for x in numbers if wins(x)]) == len({x for x in numbers if wins(x)}):
|
| 230 |
-
return None # no winning reprint: counting tickets would equal counting numbers
|
| 231 |
-
if level >= 3:
|
| 232 |
-
voided_wins = [x for t, x, _ in tickets if t in voided and wins(x)]
|
| 233 |
-
if not any(x not in alive for x in voided_wins) or not any(x in alive for x in voided_wins):
|
| 234 |
-
return None # need a voided winner that is gone and one that survives on its reprint
|
| 235 |
-
k = rng.randint(max(2, len(winners) // 4), len(winners) - 1)
|
| 236 |
-
residues = [0] * m
|
| 237 |
-
for x in winners:
|
| 238 |
-
residues[x % m] += 1
|
| 239 |
-
pairs = residues[0] * (residues[0] - 1) // 2 + sum(
|
| 240 |
-
residues[r] * residues[m - r] for r in range(1, (m + 1) // 2))
|
| 241 |
-
if m % 2 == 0:
|
| 242 |
-
pairs += residues[m // 2] * (residues[m // 2] - 1) // 2
|
| 243 |
-
expected = {"count": len(winners), "kth_smallest": winners[k - 1], "largest": winners[-1]}
|
| 244 |
-
draw = {"draw": "", "divisors": [a, b], "excluded_divisor": c, "rank": k}
|
| 245 |
-
if level >= 2:
|
| 246 |
-
expected["pairs"] = pairs
|
| 247 |
-
draw.update(digit_sum_divisor=d, pair_modulus=m)
|
| 248 |
-
return draw, tickets, voided, expected
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
def build_count(level: int, rng: random.Random) -> Built:
|
| 252 |
-
for _ in range(500):
|
| 253 |
-
got = _count_instance(level, rng)
|
| 254 |
-
if got:
|
| 255 |
-
break
|
| 256 |
-
else:
|
| 257 |
-
raise RuntimeError(f"math3_count_items L{level}: no instance in 500 draws")
|
| 258 |
-
draw, tickets, voided, expected = got
|
| 259 |
-
event = rng.choice(EVENTS)
|
| 260 |
-
draw["draw"] = f"{event} raffle {rng.choice((2025, 2026))}"
|
| 261 |
-
files = {"data/tickets.csv": "ticket,number,booth\n" + "".join(f"{t},{x},{bo}\n" for t, x, bo in tickets),
|
| 262 |
-
"data/draw.json": "{\n" + ",\n".join(f' "{k}": {json.dumps(v)}' for k, v in draw.items()) + "\n}\n"}
|
| 263 |
-
if voided:
|
| 264 |
-
files["data/voided.csv"] = "ticket,reason\n" + "".join(
|
| 265 |
-
f"{t},{rng.choice(VOID_REASONS)}\n" for t in sorted(voided))
|
| 266 |
-
head = (f"The {event} raffle sold {len(tickets)} tickets and the committee needs the prize figures. "
|
| 267 |
-
f"/root/data/tickets.csv has one row per ticket: ticket id, six-digit number and selling booth. "
|
| 268 |
-
f"/root/data/draw.json holds this draw's settings.")
|
| 269 |
-
rule = "its number is divisible by at least one of divisors and not by excluded_divisor"
|
| 270 |
-
rank = "kth_smallest (the winning number at position rank in ascending order, counting from 1)"
|
| 271 |
-
if level == 1:
|
| 272 |
-
body = (f" Every ticket carries a different number.\n\nA ticket wins when {rule}.\n\n"
|
| 273 |
-
f"Write /root/results.json with three integer keys: count (the number of winning tickets), {rank} "
|
| 274 |
-
f"and largest (the largest winning number).")
|
| 275 |
-
example = {"count": 31, "kth_smallest": 402115, "largest": 987350}
|
| 276 |
-
else:
|
| 277 |
-
void = " /root/data/voided.csv lists cancelled tickets; leave those tickets out." if voided else ""
|
| 278 |
-
after = " among the tickets that are not voided" if voided else ""
|
| 279 |
-
body = (f"{void}\n\nA ticket wins when {rule}, and its digit sum is divisible by "
|
| 280 |
-
f"digit_sum_divisor. Some numbers were printed on more than one ticket: count each winning number "
|
| 281 |
-
f"once{after}.\n\nWrite /root/results.json with four integer keys: count (distinct winning "
|
| 282 |
-
f"numbers), {rank}, largest (the largest winning number) and pairs (unordered pairs of different "
|
| 283 |
-
f"winning numbers whose sum is divisible by pair_modulus).")
|
| 284 |
-
example = {"count": 31, "kth_smallest": 402115, "largest": 987350, "pairs": 96}
|
| 285 |
-
instruction = head + body + f" For example: {json.dumps(example)}. Values are compared exactly."
|
| 286 |
-
keys = list(expected)
|
| 287 |
-
checks = [("test_is_object", lambda p: isinstance(p, dict)),
|
| 288 |
-
("test_keys", lambda p: set(p) == set(keys) and all(_is_int(p[x]) for x in keys))]
|
| 289 |
-
checks += [(f"test_{key}", lambda p, key=key: p[key] == expected[key]) for key in keys]
|
| 290 |
-
return Built(
|
| 291 |
-
instruction=instruction,
|
| 292 |
-
files=files,
|
| 293 |
-
artifact=Artifact(path="results.json", kind="checks", parse="json", checks=checks,
|
| 294 |
-
render=lambda: json.dumps(expected) + "\n"),
|
| 295 |
-
notes=dict(expected),
|
| 296 |
-
root="/root",
|
| 297 |
-
)
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
# ---------------------------------------------------------------- math3_exam_slots
|
| 301 |
-
|
| 302 |
-
DEPTS = ("CHEM", "MATH", "PHYS", "BIOL", "HIST", "ECON", "PSYC", "ENGL", "COMP", "PHIL", "SOCI", "STAT", "GEOG")
|
| 303 |
-
EXAM_OPENERS = (
|
| 304 |
-
"You are helping the registrar sequence final exams.",
|
| 305 |
-
"The registrar's office needs the final-exam timetable for this term.",
|
| 306 |
-
"Our exams office has to place this term's final exams into slots.",
|
| 307 |
-
)
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
def _exam_terms(slots: list, pair: dict, trip: dict):
|
| 311 |
-
"""slots: [(day, period)] in order; pair/trip keyed by sorted index tuples. Returns terms(order) ->
|
| 312 |
-
(back-to-back + same-day-triple cost, evening-to-morning pair sum)."""
|
| 313 |
-
p2 = {}
|
| 314 |
-
for (x, y), c in pair.items():
|
| 315 |
-
p2[(x, y)] = p2[(y, x)] = c
|
| 316 |
-
t3 = {perm: c for key, c in trip.items() for perm in itertools.permutations(key)}
|
| 317 |
-
same, em = [], []
|
| 318 |
-
for i in range(len(slots) - 1):
|
| 319 |
-
(d1, p1), (d2, q2) = slots[i], slots[i + 1]
|
| 320 |
-
if d1 == d2:
|
| 321 |
-
same.append(i)
|
| 322 |
-
elif p1 == "PM" and q2 == "AM" and d2 == d1 + 1:
|
| 323 |
-
em.append(i)
|
| 324 |
-
days = {}
|
| 325 |
-
for i, (day, _) in enumerate(slots):
|
| 326 |
-
days.setdefault(day, []).append(i)
|
| 327 |
-
triples = [ix for ix in days.values() if len(ix) == 3]
|
| 328 |
-
|
| 329 |
-
def terms(order) -> tuple:
|
| 330 |
-
base = 3 * sum(p2[order[i], order[i + 1]] for i in same)
|
| 331 |
-
base += 10 * sum(t3[order[i], order[j], order[k]] for i, j, k in triples)
|
| 332 |
-
return base, sum(p2[order[i], order[i + 1]] for i in em)
|
| 333 |
-
|
| 334 |
-
return terms
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
def _exam_instance(level: int, rng: random.Random):
|
| 338 |
-
days = {1: (3, 3), 2: (3, 3, 1), 3: (3, 3, 2)}[level]
|
| 339 |
-
periods = ("AM", "MID", "PM")
|
| 340 |
-
slots = [(d + 1, periods[i]) for d, n in enumerate(days) for i in range(n)]
|
| 341 |
-
n = len(slots)
|
| 342 |
-
letter = rng.choice("BEX")
|
| 343 |
-
blocks = [f"{letter}{i:02d}" for i in sorted(rng.sample(range(1, 30), n))]
|
| 344 |
-
courses, used = [], set()
|
| 345 |
-
for b in blocks:
|
| 346 |
-
for _ in range(rng.randint(24, 36)):
|
| 347 |
-
code = f"{rng.choice(DEPTS)}-{rng.randint(1, 4)}{rng.randint(0, 9)}{rng.randint(0, 9)}0"
|
| 348 |
-
if code not in used:
|
| 349 |
-
used.add(code)
|
| 350 |
-
courses.append((code, b, rng.randint(6, 30)))
|
| 351 |
-
size = {b: sum(s for _, bb, s in courses if bb == b) for b in blocks}
|
| 352 |
-
pair = {(i, j): 0 if rng.random() < 0.1 else rng.randint(1, 25) for i, j in
|
| 353 |
-
itertools.combinations(range(n), 2)}
|
| 354 |
-
trip = {(i, j, k): rng.randint(0, min(6, pair[(i, j)], pair[(i, k)], pair[(j, k)])) for i, j, k in
|
| 355 |
-
itertools.combinations(range(n), 3)}
|
| 356 |
-
cutoff, early, large = None, set(), []
|
| 357 |
-
if level >= 2:
|
| 358 |
-
desc = sorted(size.values(), reverse=True)
|
| 359 |
-
n_large = rng.choice((1, 2))
|
| 360 |
-
lo, hi = desc[n_large], desc[n_large - 1]
|
| 361 |
-
cutoff = (hi // 10) * 10
|
| 362 |
-
if cutoff <= lo:
|
| 363 |
-
return None
|
| 364 |
-
early = {1, 2, 3}
|
| 365 |
-
large = [i for i, b in enumerate(blocks) if size[b] >= cutoff]
|
| 366 |
-
em = level >= 3
|
| 367 |
-
terms = _exam_terms(slots, pair, trip)
|
| 368 |
-
late = [i for i in range(n) if i + 1 not in early]
|
| 369 |
-
# one pass: (cost without the README terms, cost with them, feasible under front-loading, schedule)
|
| 370 |
-
table = []
|
| 371 |
-
for o in itertools.permutations(range(n)):
|
| 372 |
-
base, extra = terms(o)
|
| 373 |
-
table.append((base, base + extra if em else base, not any(o[i] in large for i in late), o))
|
| 374 |
-
feasible = [row for row in table if row[2]]
|
| 375 |
-
best = min(row[1] for row in feasible)
|
| 376 |
-
orders = [row[3] for row in feasible if row[1] == best]
|
| 377 |
-
if best == 0:
|
| 378 |
-
return None
|
| 379 |
-
if level >= 2 and min(row[0] for row in table) >= min(row[0] for row in feasible):
|
| 380 |
-
return None # front-loading must cost something
|
| 381 |
-
if em:
|
| 382 |
-
naive = min(row[0] for row in feasible)
|
| 383 |
-
if any(row[1] == best for row in feasible if row[0] == naive):
|
| 384 |
-
return None # some schedule that ignores the evening-to-morning term would still be optimal
|
| 385 |
-
return slots, blocks, courses, size, pair, trip, cutoff, sorted(early), large, best, orders
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
def build_exams(level: int, rng: random.Random) -> Built:
|
| 389 |
-
for _ in range(200):
|
| 390 |
-
got = _exam_instance(level, rng)
|
| 391 |
-
if got:
|
| 392 |
-
break
|
| 393 |
-
else:
|
| 394 |
-
raise RuntimeError(f"math3_exam_slots L{level}: no instance in 200 draws")
|
| 395 |
-
slots, blocks, courses, size, pair, trip, cutoff, early, large, best, orders = got
|
| 396 |
-
n, days = len(blocks), slots[-1][0]
|
| 397 |
-
inst = {"blocks": blocks, "slots": [{"slot": i + 1, "day": d, "period": p} for i, (d, p) in enumerate(slots)],
|
| 398 |
-
"block_size": size}
|
| 399 |
-
readme = ["# Exam sequencing rules, this term", "",
|
| 400 |
-
"- Pair and triple counts are unordered: each group of blocks appears once, ids in ascending order."]
|
| 401 |
-
if level >= 2:
|
| 402 |
-
inst["large_block_cutoff"], inst["early_slots"] = cutoff, early
|
| 403 |
-
readme.append("- Front-loading: a block whose size is at or above `large_block_cutoff` in instance.json must "
|
| 404 |
-
"be placed in one of the `early_slots`.")
|
| 405 |
-
if level >= 3:
|
| 406 |
-
readme.append("- Evening-to-morning: when the PM slot of one day is followed by the AM slot of the next day, "
|
| 407 |
-
"add 1 x the pair count of the two blocks placed in them to the objective.")
|
| 408 |
-
rng.shuffle(courses)
|
| 409 |
-
files = {
|
| 410 |
-
"data/instance.json": json.dumps(inst, indent=1) + "\n",
|
| 411 |
-
"data/pair_counts.csv": "block_a,block_b,students\n" + "".join(
|
| 412 |
-
f"{blocks[i]},{blocks[j]},{c}\n" for (i, j), c in sorted(pair.items())),
|
| 413 |
-
"data/triplet_counts.csv": "block_a,block_b,block_c,students\n" + "".join(
|
| 414 |
-
f"{blocks[i]},{blocks[j]},{blocks[k]},{c}\n" for (i, j, k), c in sorted(trip.items())),
|
| 415 |
-
"data/blockmap.csv": "course,block,students\n" + "".join(f"{c},{b},{s}\n" for c, b, s in courses),
|
| 416 |
-
"data/README.md": "\n".join(readme) + "\n",
|
| 417 |
-
}
|
| 418 |
-
words = {6: "six", 7: "seven", 8: "eight"}[n]
|
| 419 |
-
instruction = (
|
| 420 |
-
f"{rng.choice(EXAM_OPENERS)} The exams form {words} blocks, and {words} slots run over "
|
| 421 |
-
f"{'two' if days == 2 else 'three'} days. Place them so students sit as few close-together exams as "
|
| 422 |
-
f"possible.\n\nInputs in /root/data/:\n"
|
| 423 |
-
f"- instance.json: the blocks, the slots in order (slot, day, period) and each block's size.\n"
|
| 424 |
-
f"- pair_counts.csv and triplet_counts.csv: students taking both blocks of a pair, or all three of a triple.\n"
|
| 425 |
-
f"- blockmap.csv: the courses in each block.\n"
|
| 426 |
-
f"- README.md: this term's scheduling rules. Apply them.\n\n"
|
| 427 |
-
f"Objective, lower is better: for two consecutive slots on the same day, add 3 x the pair count of their "
|
| 428 |
-
f"blocks; for a day with three slots, add 10 x the triplet count of its three blocks.\n\n"
|
| 429 |
-
f"Create /root/output/ and write /root/output/schedule.csv with the header slot,block and one row per slot "
|
| 430 |
-
f"in slot order, for example 1,{rng.choice(blocks)}. Every block appears once. It must follow every rule "
|
| 431 |
-
f"and reach the lowest objective; any optimal schedule is accepted."
|
| 432 |
-
)
|
| 433 |
-
index = {b: i for i, b in enumerate(blocks)}
|
| 434 |
-
terms = _exam_terms(slots, pair, trip)
|
| 435 |
-
|
| 436 |
-
def cost(order) -> int:
|
| 437 |
-
base, extra = terms(order)
|
| 438 |
-
return base + extra if level >= 3 else base
|
| 439 |
-
|
| 440 |
-
large_ids = {blocks[i] for i in large}
|
| 441 |
-
|
| 442 |
-
def order_of(p) -> tuple:
|
| 443 |
-
return tuple(index[r["block"]] for r in p["rows"])
|
| 444 |
-
|
| 445 |
-
checks = [
|
| 446 |
-
("test_header", lambda p: p["header"] == ["slot", "block"]),
|
| 447 |
-
("test_row_count", lambda p: len(p["rows"]) == n),
|
| 448 |
-
("test_slots_in_order", lambda p: [r["slot"] for r in p["rows"]] == [str(i + 1) for i in range(n)]),
|
| 449 |
-
("test_blocks_once", lambda p: sorted(r["block"] for r in p["rows"]) == sorted(blocks)),
|
| 450 |
-
]
|
| 451 |
-
if level >= 2:
|
| 452 |
-
checks.append(("test_front_loading", lambda p: all(
|
| 453 |
-
int(r["slot"]) in early for r in p["rows"] if r["block"] in large_ids)))
|
| 454 |
-
checks.append(("test_objective_optimal", lambda p: cost(order_of(p)) == best))
|
| 455 |
-
want = orders[0]
|
| 456 |
-
schedule = "slot,block\n" + "".join(f"{i + 1},{blocks[x]}\n" for i, x in enumerate(want))
|
| 457 |
-
return Built(
|
| 458 |
-
instruction=instruction,
|
| 459 |
-
files=files,
|
| 460 |
-
artifact=Artifact(path="output/schedule.csv", kind="checks", parse="csv", checks=checks,
|
| 461 |
-
render=lambda: schedule),
|
| 462 |
-
notes={"objective": best, "optimal_schedules": len(orders), "large": sorted(large_ids)},
|
| 463 |
-
root="/root",
|
| 464 |
-
)
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
FAMILIES = [
|
| 468 |
-
Family("math3_route_plan", "math and formal reasoning", "Fastest route under closures", build_route, v3=True),
|
| 469 |
-
Family("math3_count_items", "math and formal reasoning", "Count raffle winners and pairs", build_count, v3=True),
|
| 470 |
-
Family("math3_exam_slots", "math and formal reasoning", "Sequence exam blocks into slots", build_exams, v3=True),
|
| 471 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/media.py
DELETED
|
@@ -1,180 +0,0 @@
|
|
| 1 |
-
"""Media production: fix subtitle timing; extract segments, a trim or a channel from a WAV recording."""
|
| 2 |
-
|
| 3 |
-
import io
|
| 4 |
-
import math
|
| 5 |
-
import random
|
| 6 |
-
import struct
|
| 7 |
-
import wave
|
| 8 |
-
|
| 9 |
-
from .base import Artifact, Built, Family, Field
|
| 10 |
-
|
| 11 |
-
WORDS = (
|
| 12 |
-
"we need to leave before the tide turns and the road floods again so pack light take the map "
|
| 13 |
-
"and do not wait for me if the bridge is out find the ferry at the north dock"
|
| 14 |
-
).split()
|
| 15 |
-
|
| 16 |
-
# ---------------------------------------------------------------- med_srt
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
def _ts(ms: int) -> str:
|
| 20 |
-
h, rem = divmod(ms, 3600000)
|
| 21 |
-
m, rem = divmod(rem, 60000)
|
| 22 |
-
s, ms = divmod(rem, 1000)
|
| 23 |
-
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def build_srt(level: int, rng: random.Random) -> Built:
|
| 27 |
-
n = {1: 12, 2: 25, 3: 45}[level]
|
| 28 |
-
cues, t = [], rng.randint(1000, 5000)
|
| 29 |
-
for i in range(n):
|
| 30 |
-
dur = rng.randint(900, 4500)
|
| 31 |
-
lines = []
|
| 32 |
-
for _ in range(rng.choice([1, 1, 2])):
|
| 33 |
-
lines.append(" ".join(rng.choice(WORDS) for _ in range(rng.randint(2, 7))).capitalize())
|
| 34 |
-
if level == 3 and rng.random() < 0.25:
|
| 35 |
-
lines[0] = f"<i>{lines[0]}</i>"
|
| 36 |
-
cues.append([t, t + dur, lines])
|
| 37 |
-
t = t + dur + rng.randint(-600, 1500)
|
| 38 |
-
t = max(t, cues[-1][0] + 100)
|
| 39 |
-
if level == 1:
|
| 40 |
-
shift_from, shift_ms = 1, rng.choice([2000, 3500, 5000])
|
| 41 |
-
else:
|
| 42 |
-
shift_from = rng.randint(n // 3, 2 * n // 3)
|
| 43 |
-
shift_ms = rng.choice([1250, 800, 2000])
|
| 44 |
-
texts = ["\n".join(lines) for _, _, lines in cues]
|
| 45 |
-
if level == 1:
|
| 46 |
-
# the file as shipped is late; the correct cues are the generated ones
|
| 47 |
-
fixed = [(s, e) for s, e, _ in cues]
|
| 48 |
-
late = [(s + shift_ms, e + shift_ms) for s, e in fixed]
|
| 49 |
-
else:
|
| 50 |
-
late = [(s, e) for s, e, _ in cues]
|
| 51 |
-
fixed = [(s - shift_ms, e - shift_ms) if i + 1 >= shift_from else (s, e) for i, (s, e) in enumerate(late)]
|
| 52 |
-
blocks = [f"{i + 1}\n{_ts(s)} --> {_ts(e)}\n{texts[i]}\n" for i, (s, e) in enumerate(late)]
|
| 53 |
-
text = "\n".join(blocks)
|
| 54 |
-
if level == 3:
|
| 55 |
-
text = "\ufeff" + text.replace("\n", "\r\n")
|
| 56 |
-
secs = f"{shift_ms / 1000:g}"
|
| 57 |
-
if level == 1:
|
| 58 |
-
what = f"Every cue in /app/episode.srt is {secs} s late."
|
| 59 |
-
else:
|
| 60 |
-
what = f"In /app/episode.srt, cues {shift_from} to the end are {secs} s late."
|
| 61 |
-
rest = "" if level == 1 else ", leave the other cues untouched"
|
| 62 |
-
instruction = (
|
| 63 |
-
f"{what} Subtract that from both the start and end times of {'every cue' if level == 1 else 'those cues'}"
|
| 64 |
-
f"{rest}, keep all text as is, and save the corrected subtitles to /app/episode_fixed.srt in the same "
|
| 65 |
-
"SRT format."
|
| 66 |
-
)
|
| 67 |
-
artifact = Artifact(
|
| 68 |
-
path="episode_fixed.srt",
|
| 69 |
-
kind="srt",
|
| 70 |
-
tol_ms=1,
|
| 71 |
-
expected=[(s, e, texts[i]) for i, (s, e) in enumerate(fixed)],
|
| 72 |
-
)
|
| 73 |
-
return Built(instruction=instruction, files={"episode.srt": text}, artifact=artifact)
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
# ---------------------------------------------------------------- med_wav
|
| 77 |
-
|
| 78 |
-
THRESH = 200
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def _segments(samples: list[int], rate: int) -> list[tuple[float, float]]:
|
| 82 |
-
"""(first, last) loud sample time in seconds of each sound segment."""
|
| 83 |
-
gap_max = int(0.05 * rate)
|
| 84 |
-
spans: list[list[int]] = []
|
| 85 |
-
for i, x in enumerate(samples):
|
| 86 |
-
if abs(x) > THRESH:
|
| 87 |
-
if not spans or i - spans[-1][1] - 1 >= gap_max:
|
| 88 |
-
spans.append([i, i])
|
| 89 |
-
else:
|
| 90 |
-
spans[-1][1] = i
|
| 91 |
-
return [(a / rate, b / rate) for a, b in spans]
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
def _wav_bytes(frames: bytes, channels: int, rate: int) -> bytes:
|
| 95 |
-
buf = io.BytesIO()
|
| 96 |
-
with wave.open(buf, "wb") as w:
|
| 97 |
-
w.setnchannels(channels)
|
| 98 |
-
w.setsampwidth(2)
|
| 99 |
-
w.setframerate(rate)
|
| 100 |
-
w.writeframes(frames)
|
| 101 |
-
return buf.getvalue()
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
def _track(rng: random.Random, rate: int, noise: int) -> list[int]:
|
| 105 |
-
out = []
|
| 106 |
-
|
| 107 |
-
def quiet(seconds):
|
| 108 |
-
for _ in range(int(seconds * rate)):
|
| 109 |
-
out.append(rng.randint(-noise, noise) if noise else 0)
|
| 110 |
-
|
| 111 |
-
quiet(rng.uniform(0.1, 0.4))
|
| 112 |
-
for _ in range(rng.randint(3, 7)):
|
| 113 |
-
amp, freq = rng.randint(2000, 20000), rng.uniform(200, 1000)
|
| 114 |
-
for j in range(int(rng.uniform(0.2, 0.8) * rate)):
|
| 115 |
-
v = amp * math.sin(2 * math.pi * freq * j / rate)
|
| 116 |
-
if noise:
|
| 117 |
-
v += rng.randint(-noise, noise)
|
| 118 |
-
out.append(int(max(-32768, min(32767, round(v)))))
|
| 119 |
-
quiet(rng.uniform(0.1, 0.6))
|
| 120 |
-
return out
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
def build_wav(level: int, rng: random.Random) -> Built:
|
| 124 |
-
rate = {1: 8000, 2: 16000, 3: 16000}[level]
|
| 125 |
-
noise = 0 if level == 1 else rng.randint(40, 150)
|
| 126 |
-
left = _track(rng, rate, noise)
|
| 127 |
-
channels = 1
|
| 128 |
-
right = []
|
| 129 |
-
if level == 3:
|
| 130 |
-
right = _track(rng, rate, noise)
|
| 131 |
-
length = max(len(left), len(right))
|
| 132 |
-
left += [0] * (length - len(left))
|
| 133 |
-
right += [0] * (length - len(right))
|
| 134 |
-
channels = 2
|
| 135 |
-
frames = b"".join(struct.pack("<hh", a, b) for a, b in zip(left, right))
|
| 136 |
-
else:
|
| 137 |
-
frames = b"".join(struct.pack("<h", a) for a in left)
|
| 138 |
-
files = {"take.wav": _wav_bytes(frames, channels, rate)}
|
| 139 |
-
if level == 1:
|
| 140 |
-
instruction = (
|
| 141 |
-
f"take.wav in /app is a 16-bit mono recording. A sample is loud when its absolute value is above "
|
| 142 |
-
f"{THRESH}; loud samples separated by fewer than 0.05 s of non-loud samples belong to one sound "
|
| 143 |
-
"segment. Write /app/segments.csv with the header segment,start_s,end_s and one row per segment in "
|
| 144 |
-
"time order, numbered from 1; start_s and end_s are the times in seconds of its first and last loud "
|
| 145 |
-
"sample (sample index / sample rate). Example: 1,0.250,0.900"
|
| 146 |
-
)
|
| 147 |
-
artifact = Artifact(
|
| 148 |
-
path="segments.csv",
|
| 149 |
-
kind="csv",
|
| 150 |
-
key=("segment",),
|
| 151 |
-
fields=[Field("segment", "int"), Field("start_s", "number", tol=0.0005), Field("end_s", "number", tol=0.0005)],
|
| 152 |
-
expected=[
|
| 153 |
-
{"segment": i, "start_s": round(a, 6), "end_s": round(b, 6)}
|
| 154 |
-
for i, (a, b) in enumerate(_segments(left, rate), 1)
|
| 155 |
-
],
|
| 156 |
-
)
|
| 157 |
-
elif level == 2:
|
| 158 |
-
loud = [i for i, x in enumerate(left) if abs(x) > THRESH]
|
| 159 |
-
trimmed = struct.pack(f"<{loud[-1] - loud[0] + 1}h", *left[loud[0] : loud[-1] + 1])
|
| 160 |
-
instruction = (
|
| 161 |
-
f"take.wav in /app is a 16-bit mono recording with quiet background noise before and after the "
|
| 162 |
-
f"sound. A sample is loud when its absolute value is above {THRESH}. Cut the recording from the first "
|
| 163 |
-
"loud sample to the last loud sample, both included, and save it to /app/trimmed.wav as a WAV with "
|
| 164 |
-
"the same sample rate and sample width."
|
| 165 |
-
)
|
| 166 |
-
artifact = Artifact(path="trimmed.wav", kind="wav", expected=_wav_bytes(trimmed, 1, rate))
|
| 167 |
-
else:
|
| 168 |
-
mono = struct.pack(f"<{len(right)}h", *right)
|
| 169 |
-
instruction = (
|
| 170 |
-
"take.wav in /app is a 16-bit stereo recording. Extract channel 2 (the right channel) as a mono WAV "
|
| 171 |
-
"of the same length, sample rate and sample width, and save it to /app/right.wav."
|
| 172 |
-
)
|
| 173 |
-
artifact = Artifact(path="right.wav", kind="wav", expected=_wav_bytes(mono, 1, rate))
|
| 174 |
-
return Built(instruction=instruction, files=files, artifact=artifact)
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
FAMILIES = [
|
| 178 |
-
Family("med_srt", "media and content production", "Fix subtitle timing", build_srt),
|
| 179 |
-
Family("med_wav", "media and content production", "Process a WAV recording", build_wav),
|
| 180 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/media3.py
DELETED
|
@@ -1,557 +0,0 @@
|
|
| 1 |
-
"""Media and content production, v3: silence report on a lecture WAV (/app), subtitle retiming
|
| 2 |
-
through an edit decision list (/root), sprite counting in game keyframes (/root, Pillow + numpy).
|
| 3 |
-
|
| 4 |
-
Every generator computes the expected answer from its own construction and, where a numeric rule
|
| 5 |
-
could disagree with the construction (window levels, template matches), recomputes it from the
|
| 6 |
-
written data and asserts the two agree. A disagreement is a generator bug and raises.
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
import io
|
| 10 |
-
import json
|
| 11 |
-
import math
|
| 12 |
-
import random
|
| 13 |
-
import re
|
| 14 |
-
from array import array
|
| 15 |
-
|
| 16 |
-
from .base import Artifact, Built, Family
|
| 17 |
-
from .media import WORDS, _ts, _wav_bytes
|
| 18 |
-
|
| 19 |
-
DOMAIN = "media and content production"
|
| 20 |
-
|
| 21 |
-
# ---------------------------------------------------------------- med3_silence_report
|
| 22 |
-
|
| 23 |
-
RATE = 8000
|
| 24 |
-
WIN = 400 # samples per 50 ms window at 8 kHz
|
| 25 |
-
WIN_S = 0.05
|
| 26 |
-
QUIET_AMP, NOISY_AMP = 60, 1000 # uniform noise: about -59.5 and -35 dBFS
|
| 27 |
-
THR, NOISY_THR, PAUSE_S = -40.0, -30.0, 2.0
|
| 28 |
-
TIME_TOL, PCT_TOL = 0.02, 0.1
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
def _level_db(window) -> float:
|
| 32 |
-
rms = math.sqrt(sum(v * v for v in window) / len(window))
|
| 33 |
-
return 20 * math.log10(max(rms, 1e-9) / 32768)
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
def _timeline(rng: random.Random, total_s: float) -> list[list]:
|
| 37 |
-
"""[kind, windows] spans: an opening of quiet, then bursts of tone and gaps. Gap lengths avoid
|
| 38 |
-
1.5-2.5 s so the 2.0 s rule is never decided by one window."""
|
| 39 |
-
opening = rng.randint(12, 36) if rng.random() < 0.5 else rng.randint(60, 160)
|
| 40 |
-
spans = [["gap", opening]]
|
| 41 |
-
while sum(n for _, n in spans) < total_s / WIN_S:
|
| 42 |
-
spans.append(["tone", rng.randint(30, 140)])
|
| 43 |
-
spans.append(["gap", rng.randint(50, 100) if rng.random() < 0.35 else rng.randint(4, 30)])
|
| 44 |
-
spans.append(["tone", rng.randint(30, 80)])
|
| 45 |
-
spans.append(["gap", rng.randint(4, 20)])
|
| 46 |
-
return spans
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
def _noisy_span(rng: random.Random, spans: list[list]) -> tuple[float, float] | None:
|
| 50 |
-
"""A 10-20 s span that starts and ends inside bursts and holds at least one long gap."""
|
| 51 |
-
starts, t = [], 0
|
| 52 |
-
for kind, n in spans:
|
| 53 |
-
starts.append(t)
|
| 54 |
-
t += n
|
| 55 |
-
tones = [i for i, (kind, _) in enumerate(spans) if kind == "tone"]
|
| 56 |
-
pairs = []
|
| 57 |
-
for a in tones:
|
| 58 |
-
for b in tones:
|
| 59 |
-
inner = range(a + 1, b)
|
| 60 |
-
length = (starts[b] + spans[b][1] / 2 - starts[a] - spans[a][1] / 2) * WIN_S
|
| 61 |
-
if b > a and 10 <= length <= 20 and any(spans[i][0] == "gap" and spans[i][1] >= 50 for i in inner):
|
| 62 |
-
pairs.append((a, b))
|
| 63 |
-
if not pairs:
|
| 64 |
-
return None
|
| 65 |
-
a, b = rng.choice(pairs)
|
| 66 |
-
for i in range(a + 1, b):
|
| 67 |
-
if spans[i][0] == "gap":
|
| 68 |
-
spans[i][0] = "noisy"
|
| 69 |
-
lo = round(rng.uniform(starts[a] + 4, starts[a] + spans[a][1] - 4) * WIN_S, 2)
|
| 70 |
-
hi = round(rng.uniform(starts[b] + 4, starts[b] + spans[b][1] - 4) * WIN_S, 2)
|
| 71 |
-
return lo, hi
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
def _render_channel(rng: random.Random, spans: list[list]) -> array:
|
| 75 |
-
pools = {kind: [array("h", (rng.randint(-amp, amp) for _ in range(WIN))) for _ in range(24)]
|
| 76 |
-
for kind, amp in (("gap", QUIET_AMP), ("noisy", NOISY_AMP))}
|
| 77 |
-
out = array("h")
|
| 78 |
-
for kind, n in spans:
|
| 79 |
-
if kind == "tone":
|
| 80 |
-
amp, freq = rng.randint(3000, 12000), rng.uniform(150, 600)
|
| 81 |
-
step = 2 * math.pi * freq / RATE
|
| 82 |
-
out.extend(int(round(amp * math.sin(step * j))) for j in range(n * WIN))
|
| 83 |
-
else:
|
| 84 |
-
for _ in range(n):
|
| 85 |
-
out.extend(rng.choice(pools[kind]))
|
| 86 |
-
return out
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def build_silence(level: int, rng: random.Random) -> Built:
|
| 90 |
-
total = {1: rng.uniform(60, 78), 2: rng.uniform(75, 88), 3: rng.uniform(40, 43)}[level]
|
| 91 |
-
seg_range = {1: (4, 8), 2: (4, 9), 3: (3, 7)}[level]
|
| 92 |
-
for _ in range(500):
|
| 93 |
-
spans = _timeline(rng, total)
|
| 94 |
-
span = _noisy_span(rng, spans) if level >= 2 else None
|
| 95 |
-
if level >= 2 and span is None:
|
| 96 |
-
continue
|
| 97 |
-
silent = []
|
| 98 |
-
for kind, n in spans:
|
| 99 |
-
silent += [kind != "tone"] * n
|
| 100 |
-
runs, i = [], 0
|
| 101 |
-
while i < len(silent):
|
| 102 |
-
j = i
|
| 103 |
-
while j < len(silent) and silent[j] == silent[i]:
|
| 104 |
-
j += 1
|
| 105 |
-
if silent[i] and (i == 0 or (j - i) * WIN_S > PAUSE_S):
|
| 106 |
-
runs.append((i, j))
|
| 107 |
-
i = j
|
| 108 |
-
if seg_range[0] <= len(runs) <= seg_range[1]:
|
| 109 |
-
break
|
| 110 |
-
else:
|
| 111 |
-
raise RuntimeError("med3_silence_report: no timeline in range after 500 draws")
|
| 112 |
-
lapel = _render_channel(rng, spans)
|
| 113 |
-
nwin = len(lapel) // WIN
|
| 114 |
-
if len(lapel) != nwin * WIN or nwin != len(silent):
|
| 115 |
-
raise AssertionError("med3_silence_report: samples do not fill whole windows of the timeline")
|
| 116 |
-
lo, hi = span if span else (math.inf, math.inf)
|
| 117 |
-
for w in range(nwin): # the stated rule applied to the written samples must give the built mask
|
| 118 |
-
limit = NOISY_THR if lo <= w * WIN_S < hi else THR
|
| 119 |
-
if (_level_db(lapel[w * WIN:(w + 1) * WIN]) < limit) != silent[w]:
|
| 120 |
-
raise AssertionError(f"med3_silence_report: window {w} disagrees with the timeline")
|
| 121 |
-
channels, frames = 1, lapel
|
| 122 |
-
if level == 3: # channel 2: the room mic, 60 Hz hum near -22 dBFS plus faint noise
|
| 123 |
-
hum, step = rng.randint(3500, 3900), 2 * math.pi * 60 / RATE
|
| 124 |
-
frames = array("h", bytes(4 * len(lapel)))
|
| 125 |
-
frames[0::2] = lapel
|
| 126 |
-
frames[1::2] = array("h", (int(round(hum * math.sin(step * j))) + rng.randint(-40, 40)
|
| 127 |
-
for j in range(len(lapel))))
|
| 128 |
-
channels = 2
|
| 129 |
-
files = {"data/lecture.wav": _wav_bytes(frames.tobytes(), channels, RATE)}
|
| 130 |
-
if level >= 2:
|
| 131 |
-
notes = (f"# Recording notes\n\nFrom {lo:.2f} s to {hi:.2f} s the class moved to the workshop, where the "
|
| 132 |
-
"air handling is loud. For windows starting in that span (start inclusive, end exclusive) use "
|
| 133 |
-
"-30 dBFS instead of -40 dBFS.\n")
|
| 134 |
-
if level == 3:
|
| 135 |
-
notes += ("\nThe file is stereo. Channel 1 is the instructor's lapel microphone. Channel 2 is a room "
|
| 136 |
-
"microphone that carries mains hum the whole time, so it never goes quiet: judge silence on "
|
| 137 |
-
"channel 1 only.\n")
|
| 138 |
-
files["data/notes.md"] = notes
|
| 139 |
-
original = round(nwin * WIN_S, 3)
|
| 140 |
-
segs = [{"start": round(a * WIN_S, 3), "end": round(b * WIN_S, 3), "duration": round((b - a) * WIN_S, 3)}
|
| 141 |
-
for a, b in runs]
|
| 142 |
-
removed = round(sum(s["duration"] for s in segs), 3)
|
| 143 |
-
report = {"original_duration_seconds": original, "compressed_duration_seconds": round(original - removed, 3),
|
| 144 |
-
"removed_duration_seconds": removed, "compression_percentage": round(removed / original * 100, 2),
|
| 145 |
-
"segments_removed": segs}
|
| 146 |
-
notes_line = " Recording notes in /app/data/notes.md override these rules where they differ." if level >= 2 else ""
|
| 147 |
-
instruction = (
|
| 148 |
-
"A lecture recording for the course site, /app/data/lecture.wav (16-bit PCM), opens with dead air, and "
|
| 149 |
-
f"the instructor pauses between topics. Both should be cut.{notes_line}\n\n"
|
| 150 |
-
"1. Split the audio into consecutive 50 ms windows from 0 s.\n"
|
| 151 |
-
"2. A window's level is 20 * log10(rms / 32768) dBFS, rms being the root mean square of its samples. "
|
| 152 |
-
"Below -40 dBFS it is silent.\n"
|
| 153 |
-
"3. A silent run is a maximal stretch of consecutive silent windows (start of its first window to end "
|
| 154 |
-
"of its last).\n"
|
| 155 |
-
"4. Remove the run at the very start of the file, whatever its length, and every other run longer than "
|
| 156 |
-
"2.0 s.\n\n"
|
| 157 |
-
"Write /app/compression_report.json with the keys original_duration_seconds, "
|
| 158 |
-
"compressed_duration_seconds, removed_duration_seconds, compression_percentage (removed / original * "
|
| 159 |
-
"100) and segments_removed: a list in time order of objects like "
|
| 160 |
-
'{"start": 0.0, "end": 6.3, "duration": 6.3}. Times are checked within 0.02 s, the percentage within 0.1.'
|
| 161 |
-
)
|
| 162 |
-
|
| 163 |
-
def near(got, want, tol=TIME_TOL) -> bool:
|
| 164 |
-
return isinstance(got, (int, float)) and not isinstance(got, bool) and abs(got - want) <= tol + 1e-9
|
| 165 |
-
|
| 166 |
-
def seg_ok(p) -> bool:
|
| 167 |
-
got = p["segments_removed"]
|
| 168 |
-
return all(near(g[k], w[k]) for g, w in zip(got, segs) for k in ("start", "end", "duration"))
|
| 169 |
-
|
| 170 |
-
keys = set(report)
|
| 171 |
-
checks = [
|
| 172 |
-
("test_valid_json", lambda p: isinstance(p, dict)),
|
| 173 |
-
("test_keys", lambda p: set(p) == keys and isinstance(p["segments_removed"], list)
|
| 174 |
-
and all(isinstance(s, dict) and set(s) == {"start", "end", "duration"} for s in p["segments_removed"])),
|
| 175 |
-
("test_original_duration", lambda p: near(p["original_duration_seconds"], original)),
|
| 176 |
-
("test_segment_count", lambda p: len(p["segments_removed"]) == len(segs)),
|
| 177 |
-
("test_segments", seg_ok),
|
| 178 |
-
("test_removed_duration", lambda p: near(p["removed_duration_seconds"], removed)),
|
| 179 |
-
("test_compressed_duration", lambda p: near(p["compressed_duration_seconds"], original - removed)),
|
| 180 |
-
("test_consistency", lambda p: near(p["original_duration_seconds"],
|
| 181 |
-
p["compressed_duration_seconds"] + p["removed_duration_seconds"])),
|
| 182 |
-
("test_compression_percentage", lambda p: near(p["compression_percentage"],
|
| 183 |
-
report["compression_percentage"], PCT_TOL)),
|
| 184 |
-
]
|
| 185 |
-
return Built(
|
| 186 |
-
instruction=instruction,
|
| 187 |
-
files=files,
|
| 188 |
-
artifact=Artifact(path="compression_report.json", kind="checks", parse="json", checks=checks,
|
| 189 |
-
render=lambda: json.dumps(report, indent=2) + "\n"),
|
| 190 |
-
notes={"segments": len(segs), "noisy_span": span},
|
| 191 |
-
root="/app",
|
| 192 |
-
)
|
| 193 |
-
|
| 194 |
-
# ---------------------------------------------------------------- med3_subtitle_retime
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
def _edl_ts(ms: int) -> str:
|
| 198 |
-
return _ts(ms).replace(",", ".")
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
def _cue_text(rng: random.Random, italics: bool) -> str:
|
| 202 |
-
lines = [" ".join(rng.choice(WORDS) for _ in range(rng.randint(2, 7))).capitalize()
|
| 203 |
-
for _ in range(rng.choice([1, 1, 2]))]
|
| 204 |
-
if italics and rng.random() < 0.25:
|
| 205 |
-
lines[0] = f"<i>{lines[0]}</i>"
|
| 206 |
-
return "\n".join(lines)
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
def _union(cuts: list[tuple[int, int]]) -> list[list[int]]:
|
| 210 |
-
merged: list[list[int]] = []
|
| 211 |
-
for s, e in sorted(cuts):
|
| 212 |
-
if merged and s <= merged[-1][1]:
|
| 213 |
-
merged[-1][1] = max(merged[-1][1], e)
|
| 214 |
-
else:
|
| 215 |
-
merged.append([s, e])
|
| 216 |
-
return merged
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
def _shift(t: int, union: list[list[int]]) -> int:
|
| 220 |
-
"""t minus the removed footage before it; a time inside a cut lands on the cut point."""
|
| 221 |
-
out = t
|
| 222 |
-
for s, e in union:
|
| 223 |
-
if t > s:
|
| 224 |
-
out -= min(t, e) - s
|
| 225 |
-
return out
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
def _draw_cuts(rng: random.Random, k: int, span: tuple[int, int], overlap: bool) -> list[tuple[int, int]]:
|
| 229 |
-
lo, hi = span
|
| 230 |
-
for _ in range(1000):
|
| 231 |
-
cuts = []
|
| 232 |
-
for _ in range(k):
|
| 233 |
-
s = rng.randint(lo, hi - 16000)
|
| 234 |
-
cuts.append((s, s + rng.randint(2000, 14000)))
|
| 235 |
-
cuts.sort()
|
| 236 |
-
pairs = list(zip(cuts, cuts[1:]))
|
| 237 |
-
touching = any(e1 - 1000 <= s2 <= e1 + 500 for (_, e1), (s2, _) in pairs) # neither clear nor overlapping
|
| 238 |
-
overlapping = any(s2 < e1 - 1000 for (_, e1), (s2, _) in pairs)
|
| 239 |
-
if not touching and overlapping == overlap:
|
| 240 |
-
return cuts
|
| 241 |
-
raise RuntimeError("med3_subtitle_retime: no cut layout after 1000 draws")
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
def _gap_cut_cues(rng: random.Random, n_cues: int, n_cuts: int) -> tuple[list, list[tuple[int, int]]]:
|
| 245 |
-
"""L1: cues with a long silent gap after n_cuts of them, and one cut inside each gap, so no cue
|
| 246 |
-
touches removed footage and every cue only shifts by the cuts before it."""
|
| 247 |
-
while True:
|
| 248 |
-
picks = sorted(rng.sample(range(4, n_cues - 4), n_cuts))
|
| 249 |
-
if all(b - a >= 8 for a, b in zip(picks, picks[1:])):
|
| 250 |
-
break
|
| 251 |
-
cues, cuts, t = [], [], rng.randint(1000, 5000)
|
| 252 |
-
for i in range(n_cues):
|
| 253 |
-
dur = rng.randint(900, 4500)
|
| 254 |
-
cues.append((t, t + dur, _cue_text(rng, False)))
|
| 255 |
-
t += dur
|
| 256 |
-
if i in picks:
|
| 257 |
-
lead, length = rng.randint(150, 600), rng.randint(2500, 12000)
|
| 258 |
-
cuts.append((t + lead, t + lead + length))
|
| 259 |
-
t += lead + length + rng.randint(150, 600)
|
| 260 |
-
else:
|
| 261 |
-
t += rng.randint(100, 1500)
|
| 262 |
-
return cues, cuts
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
def build_retime(level: int, rng: random.Random) -> Built:
|
| 266 |
-
from ..core.grading import parse_srt # grading imports the families package, so not at module level
|
| 267 |
-
|
| 268 |
-
n_cues, n_cuts = {1: (46, 2), 2: (46, 3), 3: (80, 7)}[level]
|
| 269 |
-
min_len = 500 if level == 3 else 1
|
| 270 |
-
ids = [f"C{i}" for i in range(1, n_cuts + 1)]
|
| 271 |
-
reverted = None
|
| 272 |
-
if level == 1:
|
| 273 |
-
cues, cuts = _gap_cut_cues(rng, n_cues, n_cuts)
|
| 274 |
-
union = _union(cuts)
|
| 275 |
-
out = [(_shift(s, union), _shift(e, union), text) for s, e, text in cues]
|
| 276 |
-
if any(s < b and a < e for s, e, _ in cues for a, b in union):
|
| 277 |
-
raise AssertionError("med3_subtitle_retime: an L1 cut overlaps a cue")
|
| 278 |
-
else:
|
| 279 |
-
for _ in range(500):
|
| 280 |
-
cues, t = [], rng.randint(1000, 5000)
|
| 281 |
-
for _ in range(n_cues):
|
| 282 |
-
dur = rng.randint(900, 4500)
|
| 283 |
-
cues.append((t, t + dur, _cue_text(rng, level == 3)))
|
| 284 |
-
t += dur + rng.randint(100, 1500)
|
| 285 |
-
cuts = _draw_cuts(rng, n_cuts, (cues[0][0], cues[-1][1]), overlap=level == 3)
|
| 286 |
-
reverted = rng.choice(ids[1:-1]) if level == 3 else None
|
| 287 |
-
active = [c for cid, c in zip(ids, cuts) if cid != reverted]
|
| 288 |
-
union = _union(active)
|
| 289 |
-
out = [(_shift(s, union), _shift(e, union), text) for s, e, text in cues]
|
| 290 |
-
inside = sum(1 for s, e, _ in cues if any(a <= s and e <= b for a, b in union))
|
| 291 |
-
straddle = sum(1 for s, e, _ in cues if any(s < a < e or s < b < e for a, b in union))
|
| 292 |
-
near_min = any(abs((e - s) - 500) <= 5 for s, e, _ in out) if level == 3 else False
|
| 293 |
-
short = sum(1 for s, e, _ in out if 0 < e - s < 500)
|
| 294 |
-
sliver = any(0 < e - s < 20 for s, e, _ in out) # a kept 5 ms cue would hinge on the 1 ms tolerance
|
| 295 |
-
merged = len(union) < len(active) # L3: an overlapping pair survives the reverted cut
|
| 296 |
-
if inside >= 1 and straddle >= 2 and not near_min and not sliver and (level < 3 or (short >= 1 and merged)):
|
| 297 |
-
break
|
| 298 |
-
else:
|
| 299 |
-
raise RuntimeError("med3_subtitle_retime: no instance after 500 draws")
|
| 300 |
-
want = [(s, e, text) for s, e, text in out if e - s >= min_len]
|
| 301 |
-
srt = "\n".join(f"{i}\n{_ts(s)} --> {_ts(e)}\n{text}\n" for i, (s, e, text) in enumerate(cues, 1))
|
| 302 |
-
if level == 3:
|
| 303 |
-
srt = "\ufeff" + srt.replace("\n", "\r\n")
|
| 304 |
-
if level == 1:
|
| 305 |
-
rows = [(cid, s, e, "dead air") for cid, (s, e) in zip(ids, cuts)]
|
| 306 |
-
else:
|
| 307 |
-
rows = [(cid, s, e, rng.choice(("retake", "dead air", "off topic", "legal", "pacing")))
|
| 308 |
-
for cid, (s, e) in zip(ids, cuts)]
|
| 309 |
-
if level == 3:
|
| 310 |
-
rng.shuffle(rows)
|
| 311 |
-
edl = "cut_id,start,end,reason\n" + "".join(f"{c},{_edl_ts(s)},{_edl_ts(e)},{r}\n" for c, s, e, r in rows)
|
| 312 |
-
files = {"episode.srt": srt, "edl.csv": edl}
|
| 313 |
-
output = (
|
| 314 |
-
"Write the result as an SRT file at /root/output/episode.srt with HH:MM:SS,mmm times, for example:\n"
|
| 315 |
-
"1\n00:00:01,250 --> 00:00:03,900\nPack light and take the map\n\n"
|
| 316 |
-
"Times are checked within 1 ms and text must match exactly."
|
| 317 |
-
)
|
| 318 |
-
if level == 1:
|
| 319 |
-
instruction = (
|
| 320 |
-
"Our editor removed stretches of dead air from an episode, and every subtitle after a removed stretch "
|
| 321 |
-
"now runs late. The subtitles are /root/episode.srt. The removed stretches are listed in "
|
| 322 |
-
"/root/edl.csv with the columns cut_id, start, end, reason; start and end are HH:MM:SS.mmm times on "
|
| 323 |
-
"the original timeline. Every cut lies in a silent gap between two cues, so no cue overlaps removed "
|
| 324 |
-
"footage.\n\n"
|
| 325 |
-
"1. A cue moves earlier by the total length (end - start) of all the cuts before it. Cues before the "
|
| 326 |
-
"first cut keep their times.\n"
|
| 327 |
-
"2. Shift a cue's start and end by the same amount.\n"
|
| 328 |
-
"3. Keep every cue, its number and its text exactly as they are.\n\n" + output
|
| 329 |
-
)
|
| 330 |
-
elif level == 2:
|
| 331 |
-
instruction = (
|
| 332 |
-
"Our editor cut sections out of an episode, and the subtitles now drift after each cut. The subtitles "
|
| 333 |
-
"are /root/episode.srt. The cuts are in /root/edl.csv (cut_id, start, end, reason); start and end are "
|
| 334 |
-
"HH:MM:SS.mmm times on the original timeline, and everything between them was removed.\n\n"
|
| 335 |
-
"1. A time t moves earlier by the removed footage before it: for every cut that starts before t, "
|
| 336 |
-
"subtract min(t, end) - start. A time inside a cut lands on the point where the cut was made.\n"
|
| 337 |
-
"2. Apply this to the start and end of every cue, so a cue that straddles a cut gets shorter.\n"
|
| 338 |
-
"3. Drop a cue whose start and end land on the same time.\n"
|
| 339 |
-
"4. Keep each cue's text exactly, line breaks included, and renumber the cues from 1.\n\n" + output
|
| 340 |
-
)
|
| 341 |
-
else:
|
| 342 |
-
files["edit_notes.md"] = (f"# Edit notes\n\n{reverted} was reverted in the final cut: that footage stays "
|
| 343 |
-
"in. Ignore its row.\n\nAfter retiming, drop any cue shorter than 500 ms. Nobody "
|
| 344 |
-
"can read it.\n")
|
| 345 |
-
instruction = (
|
| 346 |
-
"Our editor cut sections out of an episode, and the subtitles now drift after each cut. The subtitles "
|
| 347 |
-
"are /root/episode.srt. The cuts are in /root/edl.csv (cut_id, start, end, reason); start and end are "
|
| 348 |
-
"HH:MM:SS.mmm times on the original timeline, and everything between them was removed. The editor "
|
| 349 |
-
"left notes in /root/edit_notes.md; follow them.\n\n"
|
| 350 |
-
"1. A time t moves earlier by the total length of removed footage before t. A time inside a cut lands "
|
| 351 |
-
"on the point where the cut was made.\n"
|
| 352 |
-
"2. Apply this to the start and end of every cue, so a cue that straddles a cut gets shorter.\n"
|
| 353 |
-
"3. Drop a cue whose start and end land on the same time.\n"
|
| 354 |
-
"4. Keep each cue's text exactly, line breaks included, and renumber the cues from 1.\n\n" + output
|
| 355 |
-
)
|
| 356 |
-
|
| 357 |
-
def norm(text: str) -> list[str]:
|
| 358 |
-
return [" ".join(line.split()) for line in text.strip().split("\n")]
|
| 359 |
-
|
| 360 |
-
def numbering(text: str) -> bool:
|
| 361 |
-
blocks = re.split(r"\n\s*\n", text.strip())
|
| 362 |
-
return [b.strip().split("\n")[0].strip() for b in blocks] == [str(i) for i in range(1, len(blocks) + 1)]
|
| 363 |
-
|
| 364 |
-
def times(text: str) -> bool:
|
| 365 |
-
got = parse_srt(text)
|
| 366 |
-
return len(got) == len(want) and all(abs(g[0] - w[0]) <= 1 and abs(g[1] - w[1]) <= 1
|
| 367 |
-
for g, w in zip(got, want))
|
| 368 |
-
|
| 369 |
-
def texts(text: str) -> bool:
|
| 370 |
-
got = parse_srt(text)
|
| 371 |
-
return len(got) == len(want) and all(norm(g[2]) == norm(w[2]) for g, w in zip(got, want))
|
| 372 |
-
|
| 373 |
-
checks = [
|
| 374 |
-
("test_parses", lambda p: isinstance(parse_srt(p), list)),
|
| 375 |
-
("test_cue_count", lambda p: len(parse_srt(p)) == len(want)),
|
| 376 |
-
("test_numbering", numbering),
|
| 377 |
-
("test_times", times),
|
| 378 |
-
("test_text", texts),
|
| 379 |
-
]
|
| 380 |
-
rendered = "\n".join(f"{i}\n{_ts(s)} --> {_ts(e)}\n{text}\n" for i, (s, e, text) in enumerate(want, 1))
|
| 381 |
-
return Built(
|
| 382 |
-
instruction=instruction,
|
| 383 |
-
files=files,
|
| 384 |
-
artifact=Artifact(path="output/episode.srt", kind="checks", parse="text", checks=checks,
|
| 385 |
-
render=lambda: rendered),
|
| 386 |
-
notes={"cues": len(want), "dropped": len(cues) - len(want), "reverted": reverted},
|
| 387 |
-
root="/root",
|
| 388 |
-
)
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
# ---------------------------------------------------------------- med3_sprite_count
|
| 392 |
-
|
| 393 |
-
FRAME_W, FRAME_H = 256, 144
|
| 394 |
-
SPRITES = {"coin": (16, 12), "enemy": (16, 16), "turtle": (24, 16)} # (height, width)
|
| 395 |
-
MAX_DIFF = 10.0
|
| 396 |
-
NOISE = 3
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
def _gray(rgb):
|
| 400 |
-
"""Pillow's mode "L" conversion, the same integer formula the instruction's step 1 runs."""
|
| 401 |
-
from PIL import Image
|
| 402 |
-
|
| 403 |
-
return __import__("numpy").asarray(Image.fromarray(rgb).convert("L"), dtype="float32")
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
def _sprite(nrng, h: int, w: int):
|
| 407 |
-
import numpy as np
|
| 408 |
-
|
| 409 |
-
while True:
|
| 410 |
-
palette = nrng.integers(0, 256, size=(4, 3), dtype=np.uint8)
|
| 411 |
-
g = np.sort(palette @ np.array([0.299, 0.587, 0.114]))
|
| 412 |
-
if np.min(np.diff(g)) >= 40: # four clearly different gray levels
|
| 413 |
-
break
|
| 414 |
-
idx = nrng.integers(0, 4, size=(h // 2, w // 2)).repeat(2, axis=0).repeat(2, axis=1) # 2x2 pixel art
|
| 415 |
-
art = palette[idx]
|
| 416 |
-
if np.array_equal(art, art[:, ::-1]):
|
| 417 |
-
return _sprite(nrng, h, w)
|
| 418 |
-
return art
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
def _png(rgb) -> bytes:
|
| 422 |
-
from PIL import Image
|
| 423 |
-
|
| 424 |
-
buf = io.BytesIO()
|
| 425 |
-
Image.fromarray(rgb).save(buf, format="PNG")
|
| 426 |
-
return buf.getvalue()
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
def _count(frame, variants) -> int:
|
| 430 |
-
"""The instruction's rule: windows fully inside the frame, mean abs diff below 10, one hit per object.
|
| 431 |
-
Sums |frame - sprite pixel| one sprite pixel at a time over every window position (same numbers as a
|
| 432 |
-
sliding window, without the windows x sprite temporary)."""
|
| 433 |
-
import numpy as np
|
| 434 |
-
|
| 435 |
-
h, w = variants[0].shape
|
| 436 |
-
ny, nx = frame.shape[0] - h + 1, frame.shape[1] - w + 1
|
| 437 |
-
hits = np.zeros((ny, nx), dtype=bool)
|
| 438 |
-
for t in variants:
|
| 439 |
-
total = np.zeros((ny, nx), dtype=np.float32)
|
| 440 |
-
for dy in range(h):
|
| 441 |
-
for dx in range(w):
|
| 442 |
-
total += np.abs(frame[dy:dy + ny, dx:dx + nx] - t[dy, dx])
|
| 443 |
-
hits |= total / (h * w) < MAX_DIFF
|
| 444 |
-
found: list[tuple[int, int]] = []
|
| 445 |
-
for y, x in zip(*np.nonzero(hits)):
|
| 446 |
-
if all(abs(y - fy) >= h or abs(x - fx) >= w for fy, fx in found):
|
| 447 |
-
found.append((y, x))
|
| 448 |
-
return len(found)
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
def _place(rng: random.Random, taken: list, h: int, w: int, x_range: tuple[int, int]):
|
| 452 |
-
for _ in range(200):
|
| 453 |
-
y, x = rng.randint(0, FRAME_H - h), rng.randint(*x_range)
|
| 454 |
-
if all(y + h + 2 <= ty or ty + th + 2 <= y or x + w + 2 <= tx or tx + tw + 2 <= x for ty, tx, th, tw in taken):
|
| 455 |
-
taken.append((y, x, h, w))
|
| 456 |
-
return y, x
|
| 457 |
-
return None
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
def build_sprites(level: int, rng: random.Random) -> Built:
|
| 461 |
-
import numpy as np
|
| 462 |
-
|
| 463 |
-
nrng = np.random.default_rng(rng.getrandbits(64))
|
| 464 |
-
n_frames = {1: 6, 2: 8, 3: 9}[level] # the oracle at L3 takes ~4 s on a loaded 8-core host; 20 s is the cap
|
| 465 |
-
noisy, mirrored = level >= 2, level == 3
|
| 466 |
-
art = {name: _sprite(nrng, h, w) for name, (h, w) in SPRITES.items()}
|
| 467 |
-
gray_art = {name: _gray(a) for name, a in art.items()}
|
| 468 |
-
files = {f"sprites/{name}.png": _png(a) for name, a in art.items()}
|
| 469 |
-
counts = []
|
| 470 |
-
for f in range(1, n_frames + 1):
|
| 471 |
-
frame = np.empty((FRAME_H, FRAME_W, 3), dtype=np.uint8)
|
| 472 |
-
frame[:] = nrng.integers(0, 256, size=3, dtype=np.uint8)
|
| 473 |
-
for _ in range(25): # background blocks of random colours, so colour counting fails
|
| 474 |
-
y, x = rng.randint(0, FRAME_H - 8), rng.randint(0, FRAME_W - 8)
|
| 475 |
-
frame[y:y + rng.randint(8, 60), x:x + rng.randint(8, 60)] = nrng.integers(0, 256, 3, dtype=np.uint8)
|
| 476 |
-
taken, want = [], {name: 0 for name in SPRITES}
|
| 477 |
-
for _ in range(rng.randint(3, 9)):
|
| 478 |
-
name = rng.choice(list(SPRITES))
|
| 479 |
-
h, w = SPRITES[name]
|
| 480 |
-
spot = _place(rng, taken, h, w, (0, FRAME_W - w))
|
| 481 |
-
if spot is None:
|
| 482 |
-
continue
|
| 483 |
-
a = art[name][:, ::-1] if mirrored and rng.random() < 0.3 else art[name]
|
| 484 |
-
frame[spot[0]:spot[0] + h, spot[1]:spot[1] + w] = a
|
| 485 |
-
want[name] += 1
|
| 486 |
-
for _ in range(rng.choice((0, 1, 1, 2))): # decoys cut by the left or right border
|
| 487 |
-
name = rng.choice(list(SPRITES))
|
| 488 |
-
h, w = SPRITES[name]
|
| 489 |
-
cut = rng.randint(3, w - 3)
|
| 490 |
-
left = rng.random() < 0.5
|
| 491 |
-
x_range = (-cut, -cut) if left else (FRAME_W - w + cut, FRAME_W - w + cut)
|
| 492 |
-
spot = _place(rng, taken, h, w, x_range)
|
| 493 |
-
if spot is None:
|
| 494 |
-
continue
|
| 495 |
-
y, x = spot
|
| 496 |
-
lo, hi = max(x, 0), min(x + w, FRAME_W)
|
| 497 |
-
frame[y:y + h, lo:hi] = art[name][:, lo - x:hi - x]
|
| 498 |
-
if noisy:
|
| 499 |
-
jitter = nrng.integers(-NOISE, NOISE + 1, size=frame.shape)
|
| 500 |
-
frame = np.clip(frame.astype(np.int16) + jitter, 0, 255).astype(np.uint8)
|
| 501 |
-
g = _gray(frame)
|
| 502 |
-
for name in SPRITES: # the stated rule on the written frame must find exactly what was placed
|
| 503 |
-
t = gray_art[name]
|
| 504 |
-
got = _count(g, [t, t[:, ::-1]] if mirrored else [t])
|
| 505 |
-
if got != want[name]:
|
| 506 |
-
raise AssertionError(f"med3_sprite_count: frame {f} {name}: rule finds {got}, placed {want[name]}")
|
| 507 |
-
files[f"frames/frame_{f:03d}.png"] = _png(frame)
|
| 508 |
-
counts.append((f"frame_{f:03d}.png", want["coin"], want["enemy"], want["turtle"]))
|
| 509 |
-
if level >= 2:
|
| 510 |
-
notes = ("# Notes\n\nThe frames were re-encoded, so pixel values can differ by a few levels from the "
|
| 511 |
-
"sprites.\n")
|
| 512 |
-
if mirrored:
|
| 513 |
-
notes += "\nA sprite drawn mirrored left-to-right is the same object and counts.\n"
|
| 514 |
-
files["notes.md"] = notes
|
| 515 |
-
notes_line = " Read /root/notes.md before you start." if level >= 2 else ""
|
| 516 |
-
instruction = (
|
| 517 |
-
"You are building ground truth for a game-footage object detector. Keyframes are in /root/frames/ as "
|
| 518 |
-
"frame_001.png, frame_002.png and so on; reference sprites are /root/sprites/coin.png, enemy.png and "
|
| 519 |
-
"turtle.png. Every object in a frame is a copy of one sprite at its original size, never rotated or "
|
| 520 |
-
f"scaled, and objects never overlap.{notes_line}\n\n"
|
| 521 |
-
"1. Convert frames and sprites to grayscale (Pillow mode \"L\").\n"
|
| 522 |
-
"2. A sprite occurs at a position when the mean absolute difference between the sprite and the frame "
|
| 523 |
-
"window of the same size there is below 10 gray levels.\n"
|
| 524 |
-
"3. Count each object once, even if neighbouring positions also pass.\n"
|
| 525 |
-
"4. An object cut off by the frame border does not count.\n\n"
|
| 526 |
-
"Write /root/counting_results.csv with the header frame_id,coins,enemies,turtles and one row per "
|
| 527 |
-
"keyframe in frame-number order; frame_id is the file name, e.g. frame_001.png,2,1,0. Every count must "
|
| 528 |
-
"match exactly."
|
| 529 |
-
)
|
| 530 |
-
header = ["frame_id", "coins", "enemies", "turtles"]
|
| 531 |
-
|
| 532 |
-
def column(i: int):
|
| 533 |
-
return lambda p: [r[header[i]] for r in p["rows"]] == [str(c[i]) for c in counts]
|
| 534 |
-
|
| 535 |
-
checks = [
|
| 536 |
-
("test_header", lambda p: p["header"] == header),
|
| 537 |
-
("test_row_count", lambda p: len(p["rows"]) == len(counts)),
|
| 538 |
-
("test_frame_ids", column(0)),
|
| 539 |
-
("test_coins", column(1)),
|
| 540 |
-
("test_enemies", column(2)),
|
| 541 |
-
("test_turtles", column(3)),
|
| 542 |
-
]
|
| 543 |
-
rendered = ",".join(header) + "\n" + "".join(",".join(map(str, c)) + "\n" for c in counts)
|
| 544 |
-
return Built(
|
| 545 |
-
instruction=instruction,
|
| 546 |
-
files=files,
|
| 547 |
-
artifact=Artifact(path="counting_results.csv", kind="checks", parse="csv", checks=checks,
|
| 548 |
-
render=lambda: rendered),
|
| 549 |
-
notes={"totals": [sum(c[i] for c in counts) for i in (1, 2, 3)]},
|
| 550 |
-
root="/root",
|
| 551 |
-
)
|
| 552 |
-
|
| 553 |
-
FAMILIES = [
|
| 554 |
-
Family("med3_silence_report", DOMAIN, "Report silent segments in a lecture recording", build_silence, v3=True),
|
| 555 |
-
Family("med3_subtitle_retime", DOMAIN, "Retime subtitles through an edit decision list", build_retime, v3=True),
|
| 556 |
-
Family("med3_sprite_count", DOMAIN, "Count sprites in game keyframes", build_sprites, v3=True),
|
| 557 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/office.py
DELETED
|
@@ -1,234 +0,0 @@
|
|
| 1 |
-
"""Office work: reconcile invoices against payments; find a meeting slot across time zones."""
|
| 2 |
-
|
| 3 |
-
import datetime as dt
|
| 4 |
-
import random
|
| 5 |
-
|
| 6 |
-
from .base import Artifact, Built, Family, Field, money
|
| 7 |
-
|
| 8 |
-
CUSTOMERS = ["Arden Foods", "Blue Kettle", "Cobalt Labs", "Dune Freight", "Elm & Oak", "Fable Print"]
|
| 9 |
-
|
| 10 |
-
# ---------------------------------------------------------------- off_recon
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
def _cents(x: float) -> int:
|
| 14 |
-
return int(round(x * 100))
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def build_recon(level: int, rng: random.Random) -> Built:
|
| 18 |
-
n_inv = {1: 8, 2: 15, 3: 25}[level]
|
| 19 |
-
while True:
|
| 20 |
-
ids = [1001 + i for i in range(n_inv)]
|
| 21 |
-
amount = {i: _cents(rng.uniform(120, 4800)) for i in ids}
|
| 22 |
-
day0 = dt.date(2026, 9, 1)
|
| 23 |
-
inv_date = {i: day0 + dt.timedelta(days=rng.randint(0, 20)) for i in ids}
|
| 24 |
-
credits = []
|
| 25 |
-
if level >= 2:
|
| 26 |
-
for i in rng.sample(ids, max(2, n_inv // 6)):
|
| 27 |
-
credits.append((f"CN-{len(credits) + 1:03d}", i, _cents(rng.uniform(20, amount[i] / 100 * 0.3))))
|
| 28 |
-
voided = rng.choice(ids) if level == 3 else None
|
| 29 |
-
payable = [i for i in ids if i != voided]
|
| 30 |
-
# Plan payments: each names 1 (or 2-3 at level >= 2) invoices; amounts cover them fully or partly.
|
| 31 |
-
payments, pool = [], payable[:]
|
| 32 |
-
rng.shuffle(pool)
|
| 33 |
-
while pool:
|
| 34 |
-
k = 1 if level == 1 else rng.choice([1, 1, 2, 3])
|
| 35 |
-
named, pool = pool[:k], pool[k:]
|
| 36 |
-
if rng.random() < 0.2:
|
| 37 |
-
continue # these invoices get nothing
|
| 38 |
-
due = sum(amount[i] for i in named)
|
| 39 |
-
pay = due if rng.random() < 0.55 else _cents(due / 100 * rng.uniform(0.3, 0.95))
|
| 40 |
-
paid_on = max(inv_date[i] for i in named) + dt.timedelta(days=rng.randint(3, 25))
|
| 41 |
-
payments.append([named, pay, paid_on])
|
| 42 |
-
moved = None
|
| 43 |
-
if level == 3 and len(payments) >= 3:
|
| 44 |
-
p = rng.randrange(len(payments))
|
| 45 |
-
targets = [i for i in payable if i not in payments[p][0]]
|
| 46 |
-
moved = (p, rng.choice(targets))
|
| 47 |
-
# Compute balances.
|
| 48 |
-
bal = {i: amount[i] for i in payable}
|
| 49 |
-
for _, i, c in credits:
|
| 50 |
-
if i in bal:
|
| 51 |
-
bal[i] = max(0, bal[i] - c)
|
| 52 |
-
for idx in sorted(range(len(payments)), key=lambda j: (payments[j][2], j)):
|
| 53 |
-
named, pay, _ = payments[idx]
|
| 54 |
-
order = [moved[1]] if moved and moved[0] == idx else named
|
| 55 |
-
left = pay
|
| 56 |
-
for i in order:
|
| 57 |
-
take = min(left, bal[i])
|
| 58 |
-
bal[i] -= take
|
| 59 |
-
left -= take
|
| 60 |
-
unpaid = sorted(f"INV-{i}" for i, b in bal.items() if b > 0)
|
| 61 |
-
if 2 <= len(unpaid) < len(payable):
|
| 62 |
-
break
|
| 63 |
-
|
| 64 |
-
def ref(i: int) -> str:
|
| 65 |
-
if level < 3:
|
| 66 |
-
return f"INV-{i}"
|
| 67 |
-
return rng.choice([f"INV-{i}", f"inv {i}", f"#{i}", f"invoice {i}"])
|
| 68 |
-
|
| 69 |
-
pay_rows = []
|
| 70 |
-
for idx, (named, pay, d) in enumerate(payments):
|
| 71 |
-
memo = rng.choice(["Payment for ", "Remit ", "Re: ", ""]) + " ".join(ref(i) for i in named)
|
| 72 |
-
pay_rows.append((d, f"P-{idx + 1:04d}", pay, memo))
|
| 73 |
-
pay_rows.sort(key=lambda r: (r[0], r[1]))
|
| 74 |
-
files = {
|
| 75 |
-
"invoices.csv": "invoice,customer,date,amount\n"
|
| 76 |
-
+ "".join(
|
| 77 |
-
f"INV-{i},{rng.choice(CUSTOMERS)},{inv_date[i].isoformat()},{money(amount[i] / 100)}\n" for i in ids
|
| 78 |
-
),
|
| 79 |
-
"payments.csv": "date,payment,amount,memo\n"
|
| 80 |
-
+ "".join(f"{d.isoformat()},{pid},{money(a / 100)},\"{m}\"\n" for d, pid, a, m in pay_rows),
|
| 81 |
-
}
|
| 82 |
-
rules = (
|
| 83 |
-
"Process payments in date order, then by payment ID. Each payment's memo names one or more invoices by number. Apply the payment to them in the order named, "
|
| 84 |
-
"paying each invoice's remaining balance in full before moving to the next; anything left over is "
|
| 85 |
-
"unapplied credit and is ignored."
|
| 86 |
-
)
|
| 87 |
-
if credits:
|
| 88 |
-
files["credit_notes.csv"] = "credit_note,invoice,amount\n" + "".join(
|
| 89 |
-
f"{cid},INV-{i},{money(c / 100)}\n" for cid, i, c in credits
|
| 90 |
-
)
|
| 91 |
-
rules += " Credit notes reduce their invoice's balance and are applied before any payment."
|
| 92 |
-
if level == 3:
|
| 93 |
-
memo = [f"INV-{voided} was voided: it is not owed and must not appear in your output."]
|
| 94 |
-
if moved:
|
| 95 |
-
pid = f"P-{moved[0] + 1:04d}"
|
| 96 |
-
memo.append(f"{pid} was keyed against the wrong invoice. Apply all of it to INV-{moved[1]} instead of what its memo says.")
|
| 97 |
-
files["controller_memo.txt"] = "\n".join(memo) + "\n"
|
| 98 |
-
rules += " controller_memo.txt has corrections that override the files."
|
| 99 |
-
instruction = (
|
| 100 |
-
"Reconcile accounts receivable from /app/invoices.csv and /app/payments.csv. " + rules + " "
|
| 101 |
-
"Write /app/balances.csv with the header invoice,balance and one row per invoice (voided ones "
|
| 102 |
-
"excluded) giving the balance still owed in dollars, e.g. INV-1001,0.00"
|
| 103 |
-
)
|
| 104 |
-
return Built(
|
| 105 |
-
instruction=instruction,
|
| 106 |
-
files=files,
|
| 107 |
-
artifact=Artifact(
|
| 108 |
-
path="balances.csv",
|
| 109 |
-
kind="csv",
|
| 110 |
-
key=("invoice",),
|
| 111 |
-
fields=[Field("invoice", "text"), Field("balance", "number", tol=0.005)],
|
| 112 |
-
expected=[{"invoice": f"INV-{i}", "balance": bal[i] / 100} for i in payable],
|
| 113 |
-
),
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
# ---------------------------------------------------------------- off_sched
|
| 118 |
-
|
| 119 |
-
PEOPLE = ["ana", "ben", "chen", "dara", "eli"]
|
| 120 |
-
OFFSETS = [-7, -5, -4, 0, 1, 2, 3, 5.5]
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
def _fmt_off(h: float) -> str:
|
| 124 |
-
sign = "+" if h >= 0 else "-"
|
| 125 |
-
hh, mm = int(abs(h)), int(round((abs(h) % 1) * 60))
|
| 126 |
-
return f"UTC{sign}{hh:02d}:{mm:02d}"
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
def build_sched(level: int, rng: random.Random) -> Built:
|
| 130 |
-
n_people, n_days, dur = {1: (3, 2, 30), 2: (4, 3, 45), 3: (5, 3, 60)}[level]
|
| 131 |
-
days = [dt.date(2026, 11, 2) + dt.timedelta(days=i) for i in range(n_days)]
|
| 132 |
-
step = dt.timedelta(minutes=15)
|
| 133 |
-
while True:
|
| 134 |
-
names = PEOPLE[:n_people]
|
| 135 |
-
base = rng.choice(OFFSETS)
|
| 136 |
-
offs = {}
|
| 137 |
-
for n in names:
|
| 138 |
-
close = [o for o in OFFSETS if abs(o - base) <= 4]
|
| 139 |
-
offs[n] = rng.choice(close)
|
| 140 |
-
busy = {n: [] for n in names}
|
| 141 |
-
for n in names:
|
| 142 |
-
for d in days:
|
| 143 |
-
for _ in range(rng.randint(1, 4)):
|
| 144 |
-
start = dt.datetime.combine(d, dt.time(9)) + step * rng.randint(0, 28)
|
| 145 |
-
busy[n].append((start, start + step * rng.randint(2, 8)))
|
| 146 |
-
lunch = level == 3
|
| 147 |
-
ooo = {}
|
| 148 |
-
if level == 3:
|
| 149 |
-
ooo[rng.choice(names)] = rng.choice(days[:-1])
|
| 150 |
-
|
| 151 |
-
def free(n: str, t_utc: dt.datetime) -> bool:
|
| 152 |
-
off = dt.timedelta(hours=offs[n])
|
| 153 |
-
s, e = t_utc + off, t_utc + off + dt.timedelta(minutes=dur)
|
| 154 |
-
day = s.date()
|
| 155 |
-
if ooo.get(n) == day:
|
| 156 |
-
return False
|
| 157 |
-
if s < dt.datetime.combine(day, dt.time(9)) or e > dt.datetime.combine(day, dt.time(17)):
|
| 158 |
-
return False
|
| 159 |
-
blocks = list(busy[n])
|
| 160 |
-
if lunch:
|
| 161 |
-
blocks.append((dt.datetime.combine(day, dt.time(12)), dt.datetime.combine(day, dt.time(13))))
|
| 162 |
-
return all(e <= b0 or s >= b1 for b0, b1 in blocks)
|
| 163 |
-
|
| 164 |
-
valid = []
|
| 165 |
-
t = dt.datetime.combine(days[0], dt.time(0))
|
| 166 |
-
end = dt.datetime.combine(days[-1], dt.time(23, 45))
|
| 167 |
-
while t <= end:
|
| 168 |
-
if all(free(n, t) for n in names):
|
| 169 |
-
valid.append(t)
|
| 170 |
-
t += step
|
| 171 |
-
if 2 <= len(valid):
|
| 172 |
-
break
|
| 173 |
-
files = {}
|
| 174 |
-
for n in names:
|
| 175 |
-
lines = [f"timezone: {_fmt_off(offs[n])}", "working hours: 09:00-17:00 local"]
|
| 176 |
-
if lunch:
|
| 177 |
-
lines.append("lunch: 12:00-13:00 local every day (not available)")
|
| 178 |
-
if n in ooo:
|
| 179 |
-
lines.append(f"out of office: {ooo[n].isoformat()} (whole local day)")
|
| 180 |
-
lines.append("busy (local time):")
|
| 181 |
-
for b0, b1 in sorted(busy[n]):
|
| 182 |
-
lines.append(f" {b0:%Y-%m-%d} {b0:%H:%M}-{b1:%H:%M}")
|
| 183 |
-
files[f"calendars/{n}.txt"] = "\n".join(lines) + "\n"
|
| 184 |
-
instruction = (
|
| 185 |
-
f"Find a {dur}-minute meeting for everyone in /app/calendars/, one file per person with their time zone, "
|
| 186 |
-
"working hours and busy blocks in local time. A start works when, for every person, the whole meeting "
|
| 187 |
-
"falls inside their working hours on one local day and overlaps none of their busy blocks (a block "
|
| 188 |
-
"ending at 10:00 does not clash with a meeting starting at 10:00). Consider quarter-hour UTC starts "
|
| 189 |
-
f"from {days[0]} 00:00 to {days[-1]} 23:45. Create /app/meeting.ics with one VEVENT at the earliest "
|
| 190 |
-
"such slot. DTSTART and DTEND must be UTC (YYYYMMDDTHHMMSSZ)."
|
| 191 |
-
)
|
| 192 |
-
want_start, want_end = valid[0], valid[0] + dt.timedelta(minutes=dur)
|
| 193 |
-
|
| 194 |
-
def verify(app: str) -> bool:
|
| 195 |
-
from ..core.grading import read_artifact
|
| 196 |
-
|
| 197 |
-
data = read_artifact(app, "meeting.ics")
|
| 198 |
-
if data is None:
|
| 199 |
-
return False
|
| 200 |
-
text = data.decode("utf-8", errors="replace").replace("\r\n", "\n")
|
| 201 |
-
if "BEGIN:VEVENT" not in text or "END:VEVENT" not in text:
|
| 202 |
-
return False
|
| 203 |
-
block = text.split("BEGIN:VEVENT", 1)[1].split("END:VEVENT", 1)[0]
|
| 204 |
-
got = {}
|
| 205 |
-
for line in block.split("\n"):
|
| 206 |
-
name, _, value = line.partition(":")
|
| 207 |
-
if name.strip() in ("DTSTART", "DTEND"):
|
| 208 |
-
got[name.strip()] = value.strip()
|
| 209 |
-
try:
|
| 210 |
-
start = dt.datetime.strptime(got["DTSTART"], "%Y%m%dT%H%M%SZ")
|
| 211 |
-
end = dt.datetime.strptime(got["DTEND"], "%Y%m%dT%H%M%SZ")
|
| 212 |
-
except (KeyError, ValueError):
|
| 213 |
-
return False
|
| 214 |
-
return start == want_start and end == want_end
|
| 215 |
-
|
| 216 |
-
def render() -> str:
|
| 217 |
-
return (
|
| 218 |
-
"BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//terminal-desk//EN\nBEGIN:VEVENT\n"
|
| 219 |
-
f"UID:meeting-{want_start:%Y%m%dT%H%M%S}@terminal-desk\nDTSTAMP:20261101T000000Z\n"
|
| 220 |
-
f"DTSTART:{want_start:%Y%m%dT%H%M%SZ}\nDTEND:{want_end:%Y%m%dT%H%M%SZ}\n"
|
| 221 |
-
"SUMMARY:Team meeting\nEND:VEVENT\nEND:VCALENDAR\n"
|
| 222 |
-
)
|
| 223 |
-
|
| 224 |
-
return Built(
|
| 225 |
-
instruction=instruction,
|
| 226 |
-
files=files,
|
| 227 |
-
artifact=Artifact(path="meeting.ics", kind="custom", verify=verify, render=render),
|
| 228 |
-
)
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
FAMILIES = [
|
| 232 |
-
Family("off_recon", "office and white-collar work", "Reconcile receivables", build_recon),
|
| 233 |
-
Family("off_sched", "office and white-collar work", "Schedule across time zones", build_sched),
|
| 234 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/office3.py
DELETED
|
@@ -1,505 +0,0 @@
|
|
| 1 |
-
"""Office v3: receivables reconciliation, a meeting slot across time zones, and a PDF-vs-workbook diff.
|
| 2 |
-
|
| 3 |
-
off3_ar_recon and off3_meeting_slot are stdlib csv/json tasks reshaped from v2's off_recon and off_sched.
|
| 4 |
-
off3_pdf_xlsx_diff is the domain's one library family (pdfplumber + openpyxl), modeled on SkillsBench
|
| 5 |
-
pdf-excel-diff. Every generator computes the expected answer itself; the oracles in terminal_desk/oracles/
|
| 6 |
-
only prove the files carry it.
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
import datetime as dt
|
| 10 |
-
import io
|
| 11 |
-
import json
|
| 12 |
-
import random
|
| 13 |
-
|
| 14 |
-
from .base import Artifact, Built, Family, money
|
| 15 |
-
|
| 16 |
-
DOMAIN = "office and white-collar work"
|
| 17 |
-
CUSTOMERS = ["Arden Foods", "Blue Kettle", "Cobalt Labs", "Dune Freight", "Elm & Oak", "Fable Print", "Gull Marine"]
|
| 18 |
-
|
| 19 |
-
# ---------------------------------------------------------------- off3_ar_recon
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def _cents(x: float) -> int:
|
| 23 |
-
return int(round(x * 100))
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def _apply(bal: dict, order: list, pay: int) -> None:
|
| 27 |
-
"""Pay each named invoice's remaining balance in full before the next; the excess is ignored."""
|
| 28 |
-
left = pay
|
| 29 |
-
for i in order:
|
| 30 |
-
take = min(left, bal[i])
|
| 31 |
-
bal[i] -= take
|
| 32 |
-
left -= take
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
def _plan_payments(level: int, rng: random.Random, payable: list, amount: dict, day0: dt.date) -> list:
|
| 36 |
-
"""Payments as [named invoices, cents, date], sorted by date (ties keep plan order)."""
|
| 37 |
-
payments, pool = [], payable[:]
|
| 38 |
-
rng.shuffle(pool)
|
| 39 |
-
while pool:
|
| 40 |
-
k = 1 if level == 1 else rng.choice([1, 1, 2, 3])
|
| 41 |
-
named, pool = pool[:k], pool[k:]
|
| 42 |
-
due = sum(amount[i] for i in named)
|
| 43 |
-
r = rng.random()
|
| 44 |
-
if r < 0.15:
|
| 45 |
-
continue # nothing paid yet
|
| 46 |
-
if r < 0.5:
|
| 47 |
-
pays = [due]
|
| 48 |
-
elif r < 0.65:
|
| 49 |
-
pays = [due + _cents(rng.uniform(5, 300))] # overpaid
|
| 50 |
-
elif r < 0.8 and level == 1:
|
| 51 |
-
pays = [_cents(due / 100 * rng.uniform(0.3, 0.6)), _cents(due / 100 * rng.uniform(0.2, 0.5))]
|
| 52 |
-
else:
|
| 53 |
-
pays = [_cents(due / 100 * rng.uniform(0.2, 0.9))]
|
| 54 |
-
for p in pays:
|
| 55 |
-
payments.append([named, p, day0 + dt.timedelta(days=rng.randint(0, 40))])
|
| 56 |
-
payments.sort(key=lambda p: p[2])
|
| 57 |
-
return payments
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
def _balances(amount: dict, payable: list, credits: list, payments: list, moved) -> dict:
|
| 61 |
-
bal = {i: amount[i] for i in payable}
|
| 62 |
-
for _, i, c in credits:
|
| 63 |
-
if i in bal:
|
| 64 |
-
bal[i] = max(0, bal[i] - c)
|
| 65 |
-
for j, (named, pay, _) in enumerate(payments):
|
| 66 |
-
_apply(bal, [moved[1]] if moved and moved[0] == j else named, pay)
|
| 67 |
-
return bal
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
def _status(amount: int, bal: int) -> str:
|
| 71 |
-
return "paid" if bal == 0 else "open" if bal == amount else "partial"
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
def build_ar_recon(level: int, rng: random.Random) -> Built:
|
| 75 |
-
n_inv = {1: 90, 2: 120, 3: 150}[level]
|
| 76 |
-
base = rng.randint(1001, 7000)
|
| 77 |
-
ids = [base + i for i in range(n_inv)]
|
| 78 |
-
amount = {i: _cents(rng.uniform(120, 2400)) for i in ids}
|
| 79 |
-
customer = {i: rng.choice(CUSTOMERS) for i in ids}
|
| 80 |
-
voided = rng.choice(ids) if level == 3 else None
|
| 81 |
-
payable = [i for i in ids if i != voided]
|
| 82 |
-
credits = []
|
| 83 |
-
if level >= 2:
|
| 84 |
-
for i in sorted(rng.sample(ids, n_inv // 8)):
|
| 85 |
-
credits.append((f"CN-{len(credits) + 1:03d}", i, _cents(rng.uniform(10, amount[i] / 100 * 0.4))))
|
| 86 |
-
while True:
|
| 87 |
-
payments = _plan_payments(level, rng, payable, amount, dt.date(2026, 9, 1))
|
| 88 |
-
moved = None
|
| 89 |
-
if level == 3:
|
| 90 |
-
keys = [(p[1], p[2]) for p in payments]
|
| 91 |
-
idx = rng.choice([j for j, p in enumerate(payments) if keys.count((p[1], p[2])) == 1])
|
| 92 |
-
moved = (idx, rng.choice([i for i in payable if i not in payments[idx][0]]))
|
| 93 |
-
bal = _balances(amount, payable, credits, payments, moved)
|
| 94 |
-
status = {i: _status(amount[i], bal[i]) for i in payable}
|
| 95 |
-
# every rule of the level must change the answer, so a script that skips one fails
|
| 96 |
-
naive = []
|
| 97 |
-
if level == 1:
|
| 98 |
-
paid = {i: sum(p for named, p, _ in payments if named == [i]) for i in payable}
|
| 99 |
-
naive.append({i: amount[i] - paid[i] for i in payable}) # no floor at 0
|
| 100 |
-
else:
|
| 101 |
-
naive.append(_balances(amount, payable, credits, [[n[::-1], p, d] for n, p, d in payments], moved))
|
| 102 |
-
naive.append(_balances(amount, payable, [], payments, moved))
|
| 103 |
-
if level == 3:
|
| 104 |
-
naive.append(_balances(amount, payable, credits, payments, None))
|
| 105 |
-
# from L2 a credited invoice nobody paid is partial, not open
|
| 106 |
-
paid_any = {i for named, _, _ in payments for i in named} | ({moved[1]} if moved else set())
|
| 107 |
-
credit_only = [i for _, i, _ in credits if i in status and i not in paid_any and status[i] == "partial"]
|
| 108 |
-
if (all(v != bal for v in naive) and set(status.values()) == {"paid", "open", "partial"}
|
| 109 |
-
and (level == 1 or credit_only)):
|
| 110 |
-
break
|
| 111 |
-
want = [(f"INV-{i}", customer[i], bal[i], status[i]) for i in payable]
|
| 112 |
-
|
| 113 |
-
def ref(i: int) -> str:
|
| 114 |
-
return rng.choice([f"INV-{i}", f"inv {i}", f"#{i}"]) if level == 3 else f"INV-{i}"
|
| 115 |
-
|
| 116 |
-
files = {"invoices.csv": "invoice,customer,amount\n"
|
| 117 |
-
+ "".join(f"INV-{i},{customer[i]},{money(amount[i] / 100)}\n" for i in ids)}
|
| 118 |
-
if level == 1:
|
| 119 |
-
files["payments.csv"] = "date,invoice,amount\n" + "".join(
|
| 120 |
-
f"{d.isoformat()},INV-{named[0]},{money(p / 100)}\n" for named, p, d in payments)
|
| 121 |
-
else:
|
| 122 |
-
files["payments.csv"] = "date,amount,memo\n" + "".join(
|
| 123 |
-
f"{d.isoformat()},{money(p / 100)},{' '.join(ref(i) for i in named)}\n" for named, p, d in payments)
|
| 124 |
-
files["credit_notes.csv"] = "credit_note,invoice,amount\n" + "".join(
|
| 125 |
-
f"{cid},INV-{i},{money(c / 100)}\n" for cid, i, c in credits)
|
| 126 |
-
if level == 3:
|
| 127 |
-
_, p, d = payments[moved[0]]
|
| 128 |
-
files["controller_memo.md"] = (
|
| 129 |
-
"# Controller memo\n\nCorrections for this month's receivables close:\n\n"
|
| 130 |
-
f"1. INV-{voided} was voided. It is not owed and must not appear in the balances.\n"
|
| 131 |
-
f"2. The payment of {money(p / 100)} received on {d.isoformat()} was keyed against the wrong invoice. "
|
| 132 |
-
f"Apply all of it to INV-{moved[1]} instead of what its memo says.\n")
|
| 133 |
-
opener = rng.choice([
|
| 134 |
-
"You are closing the month for the receivables team.",
|
| 135 |
-
"Finance needs the open balance of every customer invoice.",
|
| 136 |
-
"Our accounts receivable ledger needs reconciling before the month closes.",
|
| 137 |
-
])
|
| 138 |
-
if level == 1:
|
| 139 |
-
rule = (
|
| 140 |
-
"/root/invoices.csv lists each invoice with its customer and amount in dollars. /root/payments.csv lists "
|
| 141 |
-
"every payment received, one row per payment, with the invoice it pays. An invoice's balance is its "
|
| 142 |
-
"amount minus all payments against it; it can receive several payments or none. If the payments add up "
|
| 143 |
-
"to more than the amount, the balance is 0.00, never negative, and the excess is ignored.")
|
| 144 |
-
else:
|
| 145 |
-
rule = (
|
| 146 |
-
"/root/invoices.csv lists invoices with customer and amount in dollars. /root/payments.csv lists "
|
| 147 |
-
"payments in the order received; each memo names one or more invoices. First apply the credit notes in "
|
| 148 |
-
"/root/credit_notes.csv, each reducing its invoice's balance (not below 0). Then take the payments top "
|
| 149 |
-
"to bottom: each pays the invoices its memo names, in that order, clearing one invoice's balance before "
|
| 150 |
-
"the next. Leftover money is ignored.")
|
| 151 |
-
if level == 3:
|
| 152 |
-
rule += (" Memos write invoice numbers as INV-1042, inv 1042 or #1042. "
|
| 153 |
-
"/root/controller_memo.md holds corrections that override the files.")
|
| 154 |
-
instruction = (
|
| 155 |
-
f"{opener}\n\n{rule}\n\n"
|
| 156 |
-
"Write /root/balances.csv with the header invoice,customer,balance,status and one row per invoice in "
|
| 157 |
-
"invoice order. balance is in dollars with 2 decimals; status is paid when the balance is 0.00, open when "
|
| 158 |
-
"it equals the full amount, partial otherwise. Example row: INV-1001,Arden Foods,0.00,paid. Balances are "
|
| 159 |
-
"checked to within 0.005."
|
| 160 |
-
)
|
| 161 |
-
|
| 162 |
-
def column(p, name):
|
| 163 |
-
return [r[name] for r in p["rows"]]
|
| 164 |
-
|
| 165 |
-
checks = [
|
| 166 |
-
("test_header", lambda p: p["header"] == ["invoice", "customer", "balance", "status"]),
|
| 167 |
-
("test_row_count", lambda p: len(p["rows"]) == len(want)),
|
| 168 |
-
("test_invoice_ids", lambda p: column(p, "invoice") == [w[0] for w in want]),
|
| 169 |
-
("test_customers", lambda p: column(p, "customer") == [w[1] for w in want]),
|
| 170 |
-
("test_balances", lambda p: len(p["rows"]) == len(want) and all(
|
| 171 |
-
abs(float(b) - w[2] / 100) <= 0.005 + 1e-9 for b, w in zip(column(p, "balance"), want))),
|
| 172 |
-
("test_status", lambda p: column(p, "status") == [w[3] for w in want]),
|
| 173 |
-
]
|
| 174 |
-
return Built(
|
| 175 |
-
instruction=instruction,
|
| 176 |
-
files=files,
|
| 177 |
-
artifact=Artifact(path="balances.csv", kind="checks", parse="csv", checks=checks,
|
| 178 |
-
render=lambda: "invoice,customer,balance,status\n"
|
| 179 |
-
+ "".join(f"{k},{c},{money(b / 100)},{st}\n" for k, c, b, st in want)),
|
| 180 |
-
root="/root",
|
| 181 |
-
)
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
# ---------------------------------------------------------------- off3_meeting_slot
|
| 185 |
-
|
| 186 |
-
PEOPLE = ["ana", "ben", "chen", "dara", "eli"]
|
| 187 |
-
OFFSETS = {1: [-5, -4, 0, 1, 2, 3], 2: [-4, -3, 0, 1, 2, 3, 5.5], 3: [-4, -3, 0, 1, 2, 3, 5.5]}
|
| 188 |
-
STEP = dt.timedelta(minutes=15)
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
def _fmt_off(h: float) -> str:
|
| 192 |
-
sign = "+" if h >= 0 else "-"
|
| 193 |
-
return f"UTC{sign}{int(abs(h)):02d}:{int(round(abs(h) % 1 * 60)):02d}"
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
def _local_hour(t: dt.datetime, off: float) -> float:
|
| 197 |
-
s = t + dt.timedelta(hours=off)
|
| 198 |
-
return s.hour + s.minute / 60
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
def _slots(days, offs, busy_local, dur, ooo, lunch):
|
| 202 |
-
"""Quarter-hour UTC starts where everyone is inside 09:00-17:00 local on one day and free."""
|
| 203 |
-
out = []
|
| 204 |
-
t, end = dt.datetime.combine(days[0], dt.time(0)), dt.datetime.combine(days[-1], dt.time(23, 45))
|
| 205 |
-
length = dt.timedelta(minutes=dur)
|
| 206 |
-
while t <= end:
|
| 207 |
-
ok = True
|
| 208 |
-
for n, off in offs.items():
|
| 209 |
-
s = t + dt.timedelta(hours=off)
|
| 210 |
-
e, day = s + length, s.date()
|
| 211 |
-
blocks = list(busy_local[n])
|
| 212 |
-
if n in lunch:
|
| 213 |
-
blocks.append((dt.datetime.combine(day, lunch[n][0]), dt.datetime.combine(day, lunch[n][1])))
|
| 214 |
-
if (ooo.get(n) == day or s < dt.datetime.combine(day, dt.time(9))
|
| 215 |
-
or e > dt.datetime.combine(day, dt.time(17)) or any(s < b1 and e > b0 for b0, b1 in blocks)):
|
| 216 |
-
ok = False
|
| 217 |
-
break
|
| 218 |
-
if ok:
|
| 219 |
-
out.append(t)
|
| 220 |
-
t += STEP
|
| 221 |
-
return out
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
def build_meeting_slot(level: int, rng: random.Random) -> Built:
|
| 225 |
-
n_people, per_day = {1: (3, (5, 7)), 2: (4, (4, 6)), 3: (5, (4, 5))}[level]
|
| 226 |
-
dur = 30 # fixed: the oracle runs on every level and the length lives only in the instruction
|
| 227 |
-
days = [dt.date(2026, 11, 2) + dt.timedelta(days=i) for i in range(5)]
|
| 228 |
-
names = PEOPLE[:n_people]
|
| 229 |
-
while True:
|
| 230 |
-
offs = {}
|
| 231 |
-
for n in names:
|
| 232 |
-
offs[n] = rng.choice(OFFSETS[level])
|
| 233 |
-
if max(offs.values()) - min(offs.values()) > 4.5 or len(set(offs.values())) < 2:
|
| 234 |
-
continue
|
| 235 |
-
busy = {n: [] for n in names}
|
| 236 |
-
for n in names:
|
| 237 |
-
for d in days:
|
| 238 |
-
for _ in range(rng.randint(*per_day)):
|
| 239 |
-
s = dt.datetime.combine(d, dt.time(8)) + STEP * rng.randint(0, 36)
|
| 240 |
-
busy[n].append((s, s + STEP * rng.randint(2, 6)))
|
| 241 |
-
busy[n].sort()
|
| 242 |
-
ooo, lunch = {}, {}
|
| 243 |
-
if level == 3: # place both notes where they move the answer: out of office on the day of the
|
| 244 |
-
first = _slots(days, offs, busy, dur, {}, {}) # earliest slot, lunch over the next one
|
| 245 |
-
if not first:
|
| 246 |
-
continue
|
| 247 |
-
who = rng.choice(names)
|
| 248 |
-
ooo[who] = (first[0] + dt.timedelta(hours=offs[who])).date()
|
| 249 |
-
second = _slots(days, offs, busy, dur, ooo, {})
|
| 250 |
-
noon = [n for n in names if second and 11.5 < _local_hour(second[0], offs[n]) < 13]
|
| 251 |
-
if not noon:
|
| 252 |
-
continue
|
| 253 |
-
lunch[rng.choice(noon)] = (dt.time(12), dt.time(13))
|
| 254 |
-
valid = _slots(days, offs, busy, dur, ooo, lunch)
|
| 255 |
-
if not valid:
|
| 256 |
-
continue
|
| 257 |
-
free = {n: [] for n in names}
|
| 258 |
-
flipped = busy # offsets read with the wrong sign; at L1 that also moves the UTC busy blocks
|
| 259 |
-
if level == 1:
|
| 260 |
-
flipped = {n: [(b0 - dt.timedelta(hours=2 * offs[n]), b1 - dt.timedelta(hours=2 * offs[n]))
|
| 261 |
-
for b0, b1 in v] for n, v in busy.items()}
|
| 262 |
-
naive = [_slots(days, offs, free, dur, ooo, lunch),
|
| 263 |
-
_slots(days, {n: -o for n, o in offs.items()}, flipped, dur, ooo, lunch)]
|
| 264 |
-
if level >= 2:
|
| 265 |
-
as_utc = {n: [(b0 + dt.timedelta(hours=offs[n]), b1 + dt.timedelta(hours=offs[n])) for b0, b1 in v]
|
| 266 |
-
for n, v in busy.items()} # busy read as UTC where it is local
|
| 267 |
-
naive.append(_slots(days, offs, as_utc, dur, ooo, lunch))
|
| 268 |
-
if level == 3:
|
| 269 |
-
naive.append(_slots(days, offs, busy, dur, {}, lunch))
|
| 270 |
-
naive.append(_slots(days, offs, busy, dur, ooo, {}))
|
| 271 |
-
if all(not v or v[0] != valid[0] for v in naive) and valid[0].date() != days[0]:
|
| 272 |
-
break
|
| 273 |
-
start, end = valid[0], valid[0] + dt.timedelta(minutes=dur)
|
| 274 |
-
|
| 275 |
-
rows = []
|
| 276 |
-
for n in names:
|
| 277 |
-
for b0, b1 in busy[n]:
|
| 278 |
-
if level == 1:
|
| 279 |
-
b0, b1 = b0 - dt.timedelta(hours=offs[n]), b1 - dt.timedelta(hours=offs[n])
|
| 280 |
-
assert b0.date() == b1.date(), (n, b0, b1)
|
| 281 |
-
rows.append((b0, n, b1))
|
| 282 |
-
rows.sort()
|
| 283 |
-
zone = "utc" if level == 1 else "local"
|
| 284 |
-
files = {
|
| 285 |
-
"people.csv": "person,utc_offset\n" + "".join(f"{n},{_fmt_off(offs[n])}\n" for n in names),
|
| 286 |
-
"busy.csv": f"person,date,start_{zone},end_{zone}\n"
|
| 287 |
-
+ "".join(f"{n},{b0:%Y-%m-%d},{b0:%H:%M},{b1:%H:%M}\n" for b0, n, b1 in rows),
|
| 288 |
-
}
|
| 289 |
-
if level == 3:
|
| 290 |
-
(o_name, o_day), = ooo.items()
|
| 291 |
-
(l_name, _), = lunch.items()
|
| 292 |
-
files["calendar_notes.md"] = (
|
| 293 |
-
"# Calendar notes\n\n"
|
| 294 |
-
f"- {o_name} is out of office for the whole local day {o_day.isoformat()}.\n"
|
| 295 |
-
f"- {l_name} takes lunch 12:00-13:00 local time every day; treat it as busy.\n")
|
| 296 |
-
opener = rng.choice([
|
| 297 |
-
f"You are scheduling a {dur}-minute review for a distributed team and need the earliest time that works.",
|
| 298 |
-
f"The team lead asked you to book a {dur}-minute sync at the first time everyone can make it.",
|
| 299 |
-
])
|
| 300 |
-
where = "in UTC" if level == 1 else "in that person's local time"
|
| 301 |
-
notes = " /root/calendar_notes.md has extra constraints from the team." if level == 3 else ""
|
| 302 |
-
instruction = (
|
| 303 |
-
f"{opener}\n\n/root/people.csv gives each person's UTC offset (UTC+05:30 means local = UTC + 5h30m). "
|
| 304 |
-
f"/root/busy.csv lists everyone's busy blocks, one per row, {where}.{notes}\n\n"
|
| 305 |
-
"A start time works when, for every person, the whole meeting falls inside 09:00-17:00 of one local day "
|
| 306 |
-
"and overlaps none of their busy blocks. A block ending at 10:00 does not clash with a meeting starting "
|
| 307 |
-
"at 10:00. Try starts on the quarter hour in UTC from 2026-11-02 00:00 to 2026-11-06 23:45 and take "
|
| 308 |
-
"the earliest that works.\n\n"
|
| 309 |
-
"Write /root/meeting.json as a JSON object with start_utc and end_utc in this format: "
|
| 310 |
-
'{"start_utc": "2026-12-01T14:15", "end_utc": "2026-12-01T14:45"}.'
|
| 311 |
-
)
|
| 312 |
-
|
| 313 |
-
def ts(v) -> dt.datetime:
|
| 314 |
-
got = dt.datetime.fromisoformat(v.strip().removesuffix("Z"))
|
| 315 |
-
if got.tzinfo is not None:
|
| 316 |
-
raise ValueError("naive UTC expected")
|
| 317 |
-
return got
|
| 318 |
-
|
| 319 |
-
checks = [
|
| 320 |
-
("test_is_object", lambda p: isinstance(p, dict)),
|
| 321 |
-
("test_keys", lambda p: set(p) == {"start_utc", "end_utc"}),
|
| 322 |
-
("test_start_utc", lambda p: ts(p["start_utc"]) == start),
|
| 323 |
-
("test_end_utc", lambda p: ts(p["end_utc"]) == end),
|
| 324 |
-
]
|
| 325 |
-
return Built(
|
| 326 |
-
instruction=instruction,
|
| 327 |
-
files=files,
|
| 328 |
-
artifact=Artifact(path="meeting.json", kind="checks", parse="json", checks=checks,
|
| 329 |
-
render=lambda: json.dumps({"start_utc": f"{start:%Y-%m-%dT%H:%M}",
|
| 330 |
-
"end_utc": f"{end:%Y-%m-%dT%H:%M}"}) + "\n"),
|
| 331 |
-
root="/root",
|
| 332 |
-
)
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
# ---------------------------------------------------------------- off3_pdf_xlsx_diff
|
| 336 |
-
|
| 337 |
-
FIRST = ["Ava", "Ben", "Cara", "Dev", "Ena", "Femi", "Gus", "Hana", "Ivo", "Jun", "Kai", "Lena", "Milo", "Nia",
|
| 338 |
-
"Omar", "Pia", "Quin", "Rosa", "Sami", "Tess", "Uma", "Vik", "Wren", "Yara", "Zeke"]
|
| 339 |
-
LAST = ["Abara", "Brandt", "Costa", "Diaz", "Eklund", "Fischer", "Gallo", "Haddad", "Ito", "Jansen", "Kowal",
|
| 340 |
-
"Lindqvist", "Moreau", "Novak", "Okafor", "Petrov", "Quist", "Rossi", "Sato", "Tanaka", "Ueda", "Varga"]
|
| 341 |
-
DEPTS = ["Sales", "Finance", "Legal", "Support", "Operations", "IT", "HR", "Marketing", "Research"]
|
| 342 |
-
TITLES = ["Analyst", "Senior Analyst", "Engineer", "Senior Engineer", "Account Manager", "Manager", "Coordinator",
|
| 343 |
-
"Specialist", "Director", "Associate"]
|
| 344 |
-
COLS = ["ID", "Name", "Department", "Title", "Salary", "Years", "Score"]
|
| 345 |
-
NUMERIC = ("Salary", "Years", "Score")
|
| 346 |
-
NOTE = "Text cells were pasted from the HR system and some carry trailing spaces; those are not changes."
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
def _pdf_bytes(rows: list[list[str]], heading: str) -> bytes:
|
| 350 |
-
from reportlab.lib import colors
|
| 351 |
-
from reportlab.lib.pagesizes import letter
|
| 352 |
-
from reportlab.lib.styles import getSampleStyleSheet
|
| 353 |
-
from reportlab.platypus import Paragraph, SimpleDocTemplate, Table, TableStyle
|
| 354 |
-
|
| 355 |
-
buf = io.BytesIO()
|
| 356 |
-
doc = SimpleDocTemplate(buf, pagesize=letter, invariant=1, title=heading)
|
| 357 |
-
table = Table([COLS] + rows, repeatRows=1) # the ruled grid keeps pdfplumber's cells whole
|
| 358 |
-
table.setStyle(TableStyle([("GRID", (0, 0), (-1, -1), 0.5, colors.black),
|
| 359 |
-
("FONTNAME", (0, 0), (-1, -1), "Helvetica"), ("FONTSIZE", (0, 0), (-1, -1), 8)]))
|
| 360 |
-
doc.build([Paragraph(heading, getSampleStyleSheet()["Heading2"]), table])
|
| 361 |
-
return buf.getvalue()
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
def _xlsx_bytes(rows: list[list], note: str | None) -> bytes:
|
| 365 |
-
import openpyxl
|
| 366 |
-
|
| 367 |
-
wb = openpyxl.Workbook()
|
| 368 |
-
ws = wb.active
|
| 369 |
-
ws.title = "Employees"
|
| 370 |
-
ws.append(COLS)
|
| 371 |
-
for r in rows:
|
| 372 |
-
ws.append(r)
|
| 373 |
-
if note:
|
| 374 |
-
wb.create_sheet("Notes").append([note])
|
| 375 |
-
buf = io.BytesIO()
|
| 376 |
-
wb.save(buf)
|
| 377 |
-
return buf.getvalue()
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
def _changed(field: str, v, rng: random.Random):
|
| 381 |
-
if field == "Salary":
|
| 382 |
-
return v + rng.choice([-1, 1, 1, 1]) * 10 * rng.randint(100, 900)
|
| 383 |
-
if field == "Years":
|
| 384 |
-
return v + rng.randint(1, 3)
|
| 385 |
-
if field == "Score":
|
| 386 |
-
steps = [k for k in range(-10, 11) if k and 20 <= round(v * 10) + k <= 50]
|
| 387 |
-
return (round(v * 10) + rng.choice(steps)) / 10
|
| 388 |
-
if field == "Department":
|
| 389 |
-
return rng.choice([d for d in DEPTS if d != v])
|
| 390 |
-
if field == "Title":
|
| 391 |
-
return rng.choice([t for t in TITLES if t != v])
|
| 392 |
-
return f"{v.split()[0]} {rng.choice([n for n in LAST if n != v.split()[1]])}"
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
def build_pdf_xlsx_diff(level: int, rng: random.Random) -> Built:
|
| 396 |
-
n, n_del, n_hire, n_mod, n_two = {1: (40, (2, 3), (1, 2), (3, 5), 0), 2: (70, (3, 5), (1, 3), (5, 8), 0),
|
| 397 |
-
3: (100, (5, 7), (2, 3), (7, 10), 2)}[level]
|
| 398 |
-
n_del, n_hire, n_mod = rng.randint(*n_del), rng.randint(*n_hire), rng.randint(*n_mod)
|
| 399 |
-
staff = {}
|
| 400 |
-
for k in sorted(rng.sample(range(1, 1000), n + n_hire)):
|
| 401 |
-
staff[f"EMP{k:05d}"] = {"Name": f"{rng.choice(FIRST)} {rng.choice(LAST)}", "Department": rng.choice(DEPTS),
|
| 402 |
-
"Title": rng.choice(TITLES), "Salary": 10 * rng.randint(4200, 14500),
|
| 403 |
-
"Years": rng.randint(0, 30), "Score": rng.randint(20, 50) / 10}
|
| 404 |
-
hires = set(rng.sample(sorted(staff), n_hire)) # in the workbook only, never reported
|
| 405 |
-
old_ids = [i for i in sorted(staff) if i not in hires]
|
| 406 |
-
deleted = sorted(rng.sample(old_ids, n_del))
|
| 407 |
-
kept = [i for i in old_ids if i not in deleted]
|
| 408 |
-
current = {i: dict(staff[i]) for i in sorted(staff) if i not in deleted}
|
| 409 |
-
mods = []
|
| 410 |
-
for j, i in enumerate(rng.sample(kept, n_mod)):
|
| 411 |
-
for f in rng.sample(COLS[1:], 2 if j < n_two else 1):
|
| 412 |
-
current[i][f] = _changed(f, staff[i][f], rng)
|
| 413 |
-
mods.append((i, f, staff[i][f], current[i][f]))
|
| 414 |
-
mods.sort(key=lambda m: (m[0], COLS.index(m[1])))
|
| 415 |
-
unchanged = [i for i in kept if i not in {m[0] for m in mods}]
|
| 416 |
-
spaced = set()
|
| 417 |
-
if level == 3: # a fifth of the names carry a trailing space, at least one on an unchanged employee
|
| 418 |
-
spaced = {rng.choice(unchanged)} | set(rng.sample(sorted(current), len(current) // 5))
|
| 419 |
-
xlsx_rows = [[i] + [current[i][c] + " " if c == "Name" and i in spaced else current[i][c] for c in COLS[1:]]
|
| 420 |
-
for i in sorted(current)]
|
| 421 |
-
if level >= 2:
|
| 422 |
-
rng.shuffle(xlsx_rows)
|
| 423 |
-
|
| 424 |
-
def pdf_cell(c, v):
|
| 425 |
-
if c == "Salary":
|
| 426 |
-
return f"${v:,}" if level >= 2 else str(v)
|
| 427 |
-
return f"{v:.1f}" if c == "Score" else str(v)
|
| 428 |
-
|
| 429 |
-
backup = dt.date(2026, 3, 31) + dt.timedelta(days=rng.randint(0, 90))
|
| 430 |
-
files = {
|
| 431 |
-
"employees_backup.pdf": _pdf_bytes([[i] + [pdf_cell(c, staff[i][c]) for c in COLS[1:]] for i in old_ids],
|
| 432 |
-
f"Employee records backup, {backup.isoformat()}"),
|
| 433 |
-
"employees_current.xlsx": _xlsx_bytes(xlsx_rows, NOTE if level == 3 else None),
|
| 434 |
-
}
|
| 435 |
-
opener = rng.choice([
|
| 436 |
-
"You are helping HR find undocumented changes to the employee database.",
|
| 437 |
-
"Payroll needs an audit of every edit made to the employee records since the last backup.",
|
| 438 |
-
])
|
| 439 |
-
notes = "; read its Notes sheet as well" if level == 3 else ""
|
| 440 |
-
money_note = ", even though the PDF prints salaries like $52,300" if level >= 2 else ""
|
| 441 |
-
instruction = (
|
| 442 |
-
f"{opener} The old records are a PDF table, /root/employees_backup.pdf (columns {', '.join(COLS)}). "
|
| 443 |
-
f"The current records are in /root/employees_current.xlsx, sheet Employees{notes}.\n\n"
|
| 444 |
-
"1. Match employees by ID (EMP plus 5 digits).\n"
|
| 445 |
-
"2. IDs in the PDF but missing from the workbook are deleted. Employees hired after the backup appear only "
|
| 446 |
-
"in the workbook; do not report them.\n"
|
| 447 |
-
"3. For an ID in both, each field whose value changed is one entry with the old (PDF) and new (workbook) "
|
| 448 |
-
"value.\n\n"
|
| 449 |
-
f"Salary, Years and Score are numbers: compare them as numbers and write JSON numbers{money_note}. "
|
| 450 |
-
"The other fields are strings.\n\n"
|
| 451 |
-
"Write /root/diff_report.json like "
|
| 452 |
-
'{"deleted_employees": ["EMP00002"], "modified_employees": [{"id": "EMP00003", "field": "Salary", '
|
| 453 |
-
'"old_value": 50020, "new_value": 55010}]}, with deleted_employees sorted by ID.'
|
| 454 |
-
)
|
| 455 |
-
want = {(i, f): (a, b) for i, f, a, b in mods}
|
| 456 |
-
|
| 457 |
-
def entries(p) -> list:
|
| 458 |
-
ms = p["modified_employees"]
|
| 459 |
-
if not isinstance(ms, list) or not all(isinstance(m, dict) and set(m) == {"id", "field", "old_value",
|
| 460 |
-
"new_value"} for m in ms):
|
| 461 |
-
raise ValueError("modified_employees must be a list of {id, field, old_value, new_value}")
|
| 462 |
-
return ms
|
| 463 |
-
|
| 464 |
-
def is_num(v) -> bool:
|
| 465 |
-
return isinstance(v, (int, float)) and not isinstance(v, bool)
|
| 466 |
-
|
| 467 |
-
def numbers_match(p) -> bool:
|
| 468 |
-
got = [m for m in entries(p) if m["field"] in NUMERIC]
|
| 469 |
-
return all(is_num(m["old_value"]) and is_num(m["new_value"])
|
| 470 |
-
and abs(m["old_value"] - want[m["id"], m["field"]][0]) <= 1e-6
|
| 471 |
-
and abs(m["new_value"] - want[m["id"], m["field"]][1]) <= 1e-6 for m in got)
|
| 472 |
-
|
| 473 |
-
def text_matches(p) -> bool:
|
| 474 |
-
got = [m for m in entries(p) if m["field"] not in NUMERIC]
|
| 475 |
-
return all(isinstance(m["old_value"], str) and isinstance(m["new_value"], str)
|
| 476 |
-
and (m["old_value"].strip(), m["new_value"].strip()) == want[m["id"], m["field"]] for m in got)
|
| 477 |
-
|
| 478 |
-
checks = [
|
| 479 |
-
("test_is_object", lambda p: isinstance(p, dict)),
|
| 480 |
-
("test_keys", lambda p: set(p) == {"deleted_employees", "modified_employees"}),
|
| 481 |
-
("test_deleted_employees", lambda p: p["deleted_employees"] == deleted),
|
| 482 |
-
("test_modified_count", lambda p: len(entries(p)) == len(mods)),
|
| 483 |
-
("test_modified_fields", lambda p: sorted((m["id"], m["field"]) for m in entries(p)) == sorted(want)),
|
| 484 |
-
("test_numeric_values", numbers_match),
|
| 485 |
-
("test_text_values", text_matches),
|
| 486 |
-
]
|
| 487 |
-
|
| 488 |
-
def render() -> str:
|
| 489 |
-
return json.dumps({"deleted_employees": deleted,
|
| 490 |
-
"modified_employees": [{"id": i, "field": f, "old_value": a, "new_value": b}
|
| 491 |
-
for i, f, a, b in mods]}, indent=1) + "\n"
|
| 492 |
-
|
| 493 |
-
return Built(
|
| 494 |
-
instruction=instruction,
|
| 495 |
-
files=files,
|
| 496 |
-
artifact=Artifact(path="diff_report.json", kind="checks", parse="json", checks=checks, render=render),
|
| 497 |
-
root="/root",
|
| 498 |
-
)
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
FAMILIES = [
|
| 502 |
-
Family("off3_ar_recon", DOMAIN, "Reconcile receivables to balances", build_ar_recon, v3=True),
|
| 503 |
-
Family("off3_meeting_slot", DOMAIN, "Earliest meeting slot across time zones", build_meeting_slot, v3=True),
|
| 504 |
-
Family("off3_pdf_xlsx_diff", DOMAIN, "Diff a PDF backup against a workbook", build_pdf_xlsx_diff, v3=True),
|
| 505 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/science.py
DELETED
|
@@ -1,250 +0,0 @@
|
|
| 1 |
-
"""Natural science: fit first-order kinetics; reaction stoichiometry with a limiting reagent."""
|
| 2 |
-
|
| 3 |
-
import math
|
| 4 |
-
import random
|
| 5 |
-
import re
|
| 6 |
-
|
| 7 |
-
from .base import Artifact, Built, Family, Field
|
| 8 |
-
|
| 9 |
-
R_GAS = 8.314
|
| 10 |
-
|
| 11 |
-
# ---------------------------------------------------------------- sci_kinetics
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
def _fit_k(points: list[tuple[float, float]]) -> float:
|
| 15 |
-
"""-slope of least-squares ln(C) against t."""
|
| 16 |
-
xs = [t for t, _ in points]
|
| 17 |
-
ys = [math.log(c) for _, c in points]
|
| 18 |
-
n = len(xs)
|
| 19 |
-
mx, my = sum(xs) / n, sum(ys) / n
|
| 20 |
-
sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
|
| 21 |
-
sxx = sum((x - mx) ** 2 for x in xs)
|
| 22 |
-
return -sxy / sxx
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
def _run(rng: random.Random, k: float, n: int) -> list[tuple[int, float]]:
|
| 26 |
-
c0 = rng.uniform(0.5, 2.0)
|
| 27 |
-
span = rng.uniform(2.0, 3.5) * math.log(2) / k
|
| 28 |
-
pts = []
|
| 29 |
-
for i in range(n):
|
| 30 |
-
t = round(span * i / (n - 1))
|
| 31 |
-
c = c0 * math.exp(-k * t) * (1 + rng.gauss(0, 0.01))
|
| 32 |
-
pts.append((t, c))
|
| 33 |
-
return pts
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
def build_kinetics(level: int, rng: random.Random) -> Built:
|
| 37 |
-
if level < 3:
|
| 38 |
-
k = rng.uniform(0.002, 0.02)
|
| 39 |
-
pts = _run(rng, k, 12 if level == 1 else 14)
|
| 40 |
-
if level == 1:
|
| 41 |
-
data = [(t, round(c, 4)) for t, c in pts]
|
| 42 |
-
files = {"run.csv": "time_s,conc_M\n" + "".join(f"{t},{c:.4f}\n" for t, c in data)}
|
| 43 |
-
used = [(float(t), c) for t, c in data]
|
| 44 |
-
extra = "run.csv has time in seconds and concentration in mol/L."
|
| 45 |
-
else:
|
| 46 |
-
data = [(round(t / 60, 3), round(c * 1000, 2)) for t, c in pts]
|
| 47 |
-
bad = rng.randrange(2, len(data) - 1)
|
| 48 |
-
t_bad, c_bad = data[bad]
|
| 49 |
-
data[bad] = (t_bad, round(c_bad * rng.choice([0.55, 1.6]), 2))
|
| 50 |
-
files = {
|
| 51 |
-
"run.csv": "time_min,conc_mM\n" + "".join(f"{t:.3f},{c:.2f}\n" for t, c in data),
|
| 52 |
-
"lab_notes.txt": f"The sample at t = {t_bad:.3f} min was a bad injection; exclude it from the fit.\n",
|
| 53 |
-
}
|
| 54 |
-
used = [(t * 60, c / 1000) for i, (t, c) in enumerate(data) if i != bad]
|
| 55 |
-
extra = "Mind the units in run.csv, and read lab_notes.txt."
|
| 56 |
-
kfit = _fit_k(used)
|
| 57 |
-
instruction = (
|
| 58 |
-
"/app/run.csv follows a first-order decay over time. Find the rate constant k as minus the slope of "
|
| 59 |
-
"an ordinary least-squares line of ln(concentration) against time in seconds, and the half-life "
|
| 60 |
-
"ln(2)/k. " + extra + " "
|
| 61 |
-
'Write /app/fit.json with the keys k_per_s (1/s) and half_life_s (seconds), '
|
| 62 |
-
'for example {"k_per_s": 0.005, "half_life_s": 138.6}.'
|
| 63 |
-
)
|
| 64 |
-
return Built(
|
| 65 |
-
instruction=instruction,
|
| 66 |
-
files=files,
|
| 67 |
-
artifact=Artifact(
|
| 68 |
-
path="fit.json",
|
| 69 |
-
kind="json",
|
| 70 |
-
expected={"k_per_s": kfit, "half_life_s": math.log(2) / kfit},
|
| 71 |
-
fields=[
|
| 72 |
-
Field("k_per_s", "number", "rate constant in 1/s", rel=0.005),
|
| 73 |
-
Field("half_life_s", "number", "half-life in seconds", rel=0.005),
|
| 74 |
-
],
|
| 75 |
-
),
|
| 76 |
-
)
|
| 77 |
-
t1 = rng.randint(288, 300)
|
| 78 |
-
t2 = t1 + rng.randint(15, 25)
|
| 79 |
-
ea = rng.uniform(40, 90) * 1000
|
| 80 |
-
k1 = rng.uniform(0.001, 0.006)
|
| 81 |
-
k2 = k1 * math.exp(-ea / R_GAS * (1 / t2 - 1 / t1))
|
| 82 |
-
files, fits = {}, []
|
| 83 |
-
for temp, k in ((t1, k1), (t2, k2)):
|
| 84 |
-
data = [(t, round(c, 4)) for t, c in _run(rng, k, 12)]
|
| 85 |
-
files[f"run_{temp}K.csv"] = "time_s,conc_M\n" + "".join(f"{t},{c:.4f}\n" for t, c in data)
|
| 86 |
-
fits.append(_fit_k([(float(t), c) for t, c in data]))
|
| 87 |
-
ea_fit = R_GAS * math.log(fits[1] / fits[0]) / (1 / t1 - 1 / t2) / 1000
|
| 88 |
-
instruction = (
|
| 89 |
-
f"/app/run_{t1}K.csv and /app/run_{t2}K.csv are the same first-order decay at two temperatures. "
|
| 90 |
-
"For each run, k is minus the slope of an ordinary least-squares line of ln(concentration) against "
|
| 91 |
-
"time in seconds. Then find the activation energy from the Arrhenius equation using the two k values "
|
| 92 |
-
f"and R = {R_GAS} J/(mol K). Write /app/fit.json with the keys k_low_per_s and k_high_per_s (1/s, for "
|
| 93 |
-
"the colder and the warmer run) and ea_kj_per_mol (kJ/mol), "
|
| 94 |
-
'for example {"k_low_per_s": 0.002, "k_high_per_s": 0.006, "ea_kj_per_mol": 60.0}.'
|
| 95 |
-
)
|
| 96 |
-
return Built(
|
| 97 |
-
instruction=instruction,
|
| 98 |
-
files=files,
|
| 99 |
-
artifact=Artifact(
|
| 100 |
-
path="fit.json",
|
| 101 |
-
kind="json",
|
| 102 |
-
expected={"k_low_per_s": fits[0], "k_high_per_s": fits[1], "ea_kj_per_mol": ea_fit},
|
| 103 |
-
fields=[
|
| 104 |
-
Field("k_low_per_s", "number", f"k at {t1} K in 1/s", rel=0.005),
|
| 105 |
-
Field("k_high_per_s", "number", f"k at {t2} K in 1/s", rel=0.005),
|
| 106 |
-
Field("ea_kj_per_mol", "number", "activation energy in kJ/mol", rel=0.01),
|
| 107 |
-
],
|
| 108 |
-
),
|
| 109 |
-
)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
# ---------------------------------------------------------------- sci_stoich
|
| 113 |
-
|
| 114 |
-
MASSES = {
|
| 115 |
-
"H": 1.008, "C": 12.011, "N": 14.007, "O": 15.999, "Na": 22.990, "Mg": 24.305, "Al": 26.982,
|
| 116 |
-
"P": 30.974, "S": 32.06, "Cl": 35.45, "K": 39.098, "Ca": 40.078, "Fe": 55.845, "Cu": 63.546,
|
| 117 |
-
"Ag": 107.868, "Ba": 137.327,
|
| 118 |
-
}
|
| 119 |
-
|
| 120 |
-
# (equation, product index among products)
|
| 121 |
-
REACTIONS = {
|
| 122 |
-
1: [
|
| 123 |
-
"2 H2 + O2 -> 2 H2O",
|
| 124 |
-
"C3H8 + 5 O2 -> 3 CO2 + 4 H2O",
|
| 125 |
-
"2 Na + Cl2 -> 2 NaCl",
|
| 126 |
-
"Fe2O3 + 3 CO -> 2 Fe + 3 CO2",
|
| 127 |
-
"2 NaOH + H2SO4 -> Na2SO4 + 2 H2O",
|
| 128 |
-
"AgNO3 + NaCl -> AgCl + NaNO3",
|
| 129 |
-
],
|
| 130 |
-
2: [
|
| 131 |
-
"Ca(OH)2 + 2 HCl -> CaCl2 + 2 H2O",
|
| 132 |
-
"2 Al + 3 CuSO4 -> Al2(SO4)3 + 3 Cu",
|
| 133 |
-
"Mg(OH)2 + 2 HNO3 -> Mg(NO3)2 + 2 H2O",
|
| 134 |
-
"3 Ba(NO3)2 + 2 Na3PO4 -> Ba3(PO4)2 + 6 NaNO3",
|
| 135 |
-
],
|
| 136 |
-
3: [
|
| 137 |
-
"CuSO4*5H2O + 2 NaOH -> Cu(OH)2 + Na2SO4 + 5 H2O",
|
| 138 |
-
"FeSO4*7H2O + 2 KOH -> Fe(OH)2 + K2SO4 + 7 H2O",
|
| 139 |
-
"BaCl2*2H2O + Na2SO4 -> BaSO4 + 2 NaCl + 2 H2O",
|
| 140 |
-
"3 Ca(OH)2 + 2 H3PO4 -> Ca3(PO4)2 + 6 H2O",
|
| 141 |
-
],
|
| 142 |
-
}
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
def molar_mass(formula: str) -> float:
|
| 146 |
-
total = 0.0
|
| 147 |
-
for part in formula.split("*"):
|
| 148 |
-
m = re.match(r"^(\d+)(.*)$", part)
|
| 149 |
-
mult, body = (int(m.group(1)), m.group(2)) if m else (1, part)
|
| 150 |
-
total += mult * _group_mass(body)
|
| 151 |
-
return total
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
def _group_mass(s: str) -> float:
|
| 155 |
-
stack = [0.0]
|
| 156 |
-
i = 0
|
| 157 |
-
while i < len(s):
|
| 158 |
-
ch = s[i]
|
| 159 |
-
if ch == "(":
|
| 160 |
-
stack.append(0.0)
|
| 161 |
-
i += 1
|
| 162 |
-
elif ch == ")":
|
| 163 |
-
i += 1
|
| 164 |
-
j = i
|
| 165 |
-
while j < len(s) and s[j].isdigit():
|
| 166 |
-
j += 1
|
| 167 |
-
n = int(s[i:j] or 1)
|
| 168 |
-
inner = stack.pop()
|
| 169 |
-
stack[-1] += inner * n
|
| 170 |
-
i = j
|
| 171 |
-
else:
|
| 172 |
-
m = re.match(r"([A-Z][a-z]?)(\d*)", s[i:])
|
| 173 |
-
stack[-1] += MASSES[m.group(1)] * int(m.group(2) or 1)
|
| 174 |
-
i += len(m.group(0))
|
| 175 |
-
return stack[0]
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
def _side(text: str) -> list[tuple[int, str]]:
|
| 179 |
-
out = []
|
| 180 |
-
for term in text.split(" + "):
|
| 181 |
-
m = re.match(r"^(\d+) (.+)$", term.strip())
|
| 182 |
-
out.append((int(m.group(1)), m.group(2)) if m else (1, term.strip()))
|
| 183 |
-
return out
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
def build_stoich(level: int, rng: random.Random) -> Built:
|
| 187 |
-
eq = rng.choice(REACTIONS[level])
|
| 188 |
-
left, right = eq.split(" -> ")
|
| 189 |
-
reactants, products = _side(left), _side(right)
|
| 190 |
-
(ca, fa), (cb, fb) = reactants
|
| 191 |
-
cp, fp = rng.choice([p for p in products if p[1] not in ("H2O",)] or products)
|
| 192 |
-
while True:
|
| 193 |
-
mass_a = round(rng.uniform(5, 60), 2)
|
| 194 |
-
eq_a = mass_a / molar_mass(fa) / ca
|
| 195 |
-
ratio = rng.choice([rng.uniform(1.15, 1.6), rng.uniform(0.6, 0.87)])
|
| 196 |
-
mass_b = round(eq_a * ratio * cb * molar_mass(fb), 2)
|
| 197 |
-
purity = {}
|
| 198 |
-
if level == 3:
|
| 199 |
-
who = rng.choice([fa, fb])
|
| 200 |
-
purity[who] = round(rng.uniform(85, 97), 1)
|
| 201 |
-
yield_pct = round(rng.uniform(70, 95), 1) if level >= 2 else 100.0
|
| 202 |
-
|
| 203 |
-
def equivalents(f, coef, mass):
|
| 204 |
-
pure = mass * purity.get(f, 100.0) / 100
|
| 205 |
-
return pure / molar_mass(f) / coef
|
| 206 |
-
|
| 207 |
-
ea, eb = equivalents(fa, ca, mass_a), equivalents(fb, cb, mass_b)
|
| 208 |
-
limiting = fa if ea < eb else fb
|
| 209 |
-
if abs(ea / eb - 1) >= 0.08:
|
| 210 |
-
break
|
| 211 |
-
grams = min(ea, eb) * cp * molar_mass(fp) * yield_pct / 100
|
| 212 |
-
lines = [f"Balanced equation: {eq}", f"Starting masses: {mass_a} g {fa}, {mass_b} g {fb}"]
|
| 213 |
-
if purity:
|
| 214 |
-
(who, pct), = purity.items()
|
| 215 |
-
lines.append(f"The {who} sample is {pct}% pure by mass; the rest is inert.")
|
| 216 |
-
if level >= 2:
|
| 217 |
-
lines.append(f"The isolated yield was {yield_pct}% of the theoretical yield.")
|
| 218 |
-
if level == 3 and any("*" in f for _, f in reactants):
|
| 219 |
-
lines.append("A formula like CuSO4*5H2O is a hydrate: the water molecules count toward its molar mass.")
|
| 220 |
-
files = {
|
| 221 |
-
"reaction.txt": "\n".join(lines) + "\n",
|
| 222 |
-
"atomic_masses.txt": "".join(f"{el} {m}\n" for el, m in MASSES.items()),
|
| 223 |
-
}
|
| 224 |
-
instruction = (
|
| 225 |
-
f"/app/reaction.txt describes one batch. Using only the atomic masses in /app/atomic_masses.txt, find "
|
| 226 |
-
f"the limiting reagent, the molar mass of {fp}, and the grams of {fp} isolated. Write "
|
| 227 |
-
"/app/batch_report.json with the keys limiting_reagent (its formula as written in the equation), "
|
| 228 |
-
f'product_molar_mass (g/mol) and product_grams, for example {{"limiting_reagent": "{fa}", '
|
| 229 |
-
'"product_molar_mass": 100.09, "product_grams": 12.5}.'
|
| 230 |
-
)
|
| 231 |
-
return Built(
|
| 232 |
-
instruction=instruction,
|
| 233 |
-
files=files,
|
| 234 |
-
artifact=Artifact(
|
| 235 |
-
path="batch_report.json",
|
| 236 |
-
kind="json",
|
| 237 |
-
expected={"limiting_reagent": limiting, "product_molar_mass": molar_mass(fp), "product_grams": grams},
|
| 238 |
-
fields=[
|
| 239 |
-
Field("limiting_reagent", "text", "formula of the limiting reagent, written as in the equation"),
|
| 240 |
-
Field("product_molar_mass", "number", f"molar mass of {fp} in g/mol", tol=0.01),
|
| 241 |
-
Field("product_grams", "number", f"grams of {fp} isolated", rel=0.003),
|
| 242 |
-
],
|
| 243 |
-
),
|
| 244 |
-
)
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
FAMILIES = [
|
| 248 |
-
Family("sci_kinetics", "natural science", "Fit first-order kinetics", build_kinetics),
|
| 249 |
-
Family("sci_stoich", "natural science", "Limiting reagent and yield", build_stoich),
|
| 250 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/science3.py
DELETED
|
@@ -1,452 +0,0 @@
|
|
| 1 |
-
"""Natural science, v3: kinetics fit, stoichiometry batch, light-curve period. All stdlib.
|
| 2 |
-
|
| 3 |
-
sci3_kinetics_fit and sci3_stoich_batch reshape v2's sci_kinetics and sci_stoich (the board's first natural-science
|
| 4 |
-
solves): same arithmetic and rule shape, with a SkillsBench-length instruction, /root output, inputs whose `head` is
|
| 5 |
-
cheap and whose `cat` is not, and kind="checks". sci3_lightcurve_period is new (exoplanet-detection-period shape):
|
| 6 |
-
detrend a spotted star's light curve and find the transit period with a box search over a stated grid.
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
import json
|
| 10 |
-
import math
|
| 11 |
-
import random
|
| 12 |
-
|
| 13 |
-
from .base import Artifact, Built, Family
|
| 14 |
-
from .science import MASSES, R_GAS, _fit_k, _side, molar_mass
|
| 15 |
-
|
| 16 |
-
ROOT = "/root"
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
def _ols(xs: list[float], ys: list[float]) -> tuple[float, float]:
|
| 20 |
-
"""(slope, R squared) of the least-squares line of ys on xs."""
|
| 21 |
-
n = len(xs)
|
| 22 |
-
mx, my = sum(xs) / n, sum(ys) / n
|
| 23 |
-
sxx = sum((x - mx) ** 2 for x in xs)
|
| 24 |
-
syy = sum((y - my) ** 2 for y in ys)
|
| 25 |
-
sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
|
| 26 |
-
return sxy / sxx, sxy * sxy / (sxx * syy)
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def _rel(got, want: float, rel: float) -> bool:
|
| 30 |
-
return not isinstance(got, bool) and abs(float(got) - want) <= rel * abs(want) + 1e-12
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
# ---------------------------------------------------------------- sci3_kinetics_fit
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
def _conc(order: int, c0: float, k: float, t: float) -> float:
|
| 37 |
-
return c0 * math.exp(-k * t) if order == 1 else c0 / (1 + k * c0 * t)
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
def _fit(order: int, pts: list[tuple[float, float]]) -> tuple[float, float]:
|
| 41 |
-
"""(k, R squared) for one order on (t_s, c_M) points: v2's _fit_k for first order, 1/C slope for second."""
|
| 42 |
-
ts = [t for t, _ in pts]
|
| 43 |
-
if order == 1:
|
| 44 |
-
return _fit_k(pts), _ols(ts, [math.log(c) for _, c in pts])[1]
|
| 45 |
-
return _ols(ts, [1 / c for _, c in pts])
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def _kin_run(rng: random.Random, order: int, n: int, milli: bool, bad: bool):
|
| 49 |
-
"""One sampler run: (csv text, cleaned (t_s, c_M) points, bad sample id or None, points with the bad row)."""
|
| 50 |
-
dt = rng.choice([5, 6, 8, 10, 12, 15, 20, 24, 30])
|
| 51 |
-
c0 = rng.uniform(20, 80) / 1000 if milli else rng.uniform(0.5, 2.0)
|
| 52 |
-
t_half = n * dt / rng.uniform(2.5, 3.8)
|
| 53 |
-
k = math.log(2) / t_half if order == 1 else 1 / (t_half * c0)
|
| 54 |
-
lod = rng.randint(3, 6)
|
| 55 |
-
conc = [_conc(order, c0, k, i * dt) * (1 + rng.gauss(0, 0.01)) for i in range(n - lod)]
|
| 56 |
-
bad_i = rng.randrange(int(0.6 * len(conc)), len(conc) - 1) if bad else None
|
| 57 |
-
if bad: # a double or half injection late in the run, where it moves the slope most
|
| 58 |
-
conc[bad_i] *= rng.choice([0.4, 2.5])
|
| 59 |
-
lines = ["sample,time_min,conc_mM" if milli else "sample,time_s,conc_M"]
|
| 60 |
-
pts, every = [], []
|
| 61 |
-
for i in range(n):
|
| 62 |
-
tt = f"{i * dt / 60:.3f}" if milli else str(i * dt)
|
| 63 |
-
if i >= len(conc):
|
| 64 |
-
lines.append(f"S{i + 1:03d},{tt},<LOD")
|
| 65 |
-
continue
|
| 66 |
-
cc = f"{conc[i] * 1000:.2f}" if milli else f"{conc[i]:.4f}"
|
| 67 |
-
lines.append(f"S{i + 1:03d},{tt},{cc}")
|
| 68 |
-
point = (float(tt) * 60, float(cc) / 1000) if milli else (float(tt), float(cc))
|
| 69 |
-
every.append(point)
|
| 70 |
-
if i != bad_i:
|
| 71 |
-
pts.append(point)
|
| 72 |
-
return "\n".join(lines) + "\n", pts, (f"S{bad_i + 1:03d}" if bad else None), every
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
def _kin_flagged(rng: random.Random, n: int):
|
| 76 |
-
"""L1 run: first order in seconds and mol/L. Below the detection limit the sampler writes the limit itself and
|
| 77 |
-
flags the row, so a fit that ignores the flag silently flattens. Returns (csv text, kept points, all points)."""
|
| 78 |
-
dt = rng.choice([5, 6, 8, 10, 12, 15, 20, 24, 30])
|
| 79 |
-
c0 = rng.uniform(0.5, 2.0)
|
| 80 |
-
below = rng.randint(10, 16)
|
| 81 |
-
k = math.log(2) * rng.uniform(2.5, 3.8) / ((n - below) * dt)
|
| 82 |
-
limit = round(c0 * math.exp(-k * (n - below - 0.5) * dt), 4)
|
| 83 |
-
lines, pts, every = ["sample,time_s,conc_M,flag"], [], []
|
| 84 |
-
for i in range(n):
|
| 85 |
-
c = c0 * math.exp(-k * i * dt) * (1 + rng.gauss(0, 0.01))
|
| 86 |
-
low = c < limit
|
| 87 |
-
cc = f"{limit:.4f}" if low else f"{c:.4f}"
|
| 88 |
-
lines.append(f"S{i + 1:03d},{i * dt},{cc},{'<LOD' if low else 'ok'}")
|
| 89 |
-
every.append((float(i * dt), float(cc)))
|
| 90 |
-
if not low:
|
| 91 |
-
pts.append(every[-1])
|
| 92 |
-
return "\n".join(lines) + "\n", pts, every
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
def _order_clear(order: int, pts) -> bool:
|
| 96 |
-
"""The true order wins the R squared comparison by a margin no rounding can flip."""
|
| 97 |
-
return _fit(order, pts)[1] - _fit(3 - order, pts)[1] > 0.003
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
def _notes(rng: random.Random, bad: list[tuple[str, str]]) -> str:
|
| 101 |
-
filler = [
|
| 102 |
-
"Thermostat bath checked against the reference thermometer before the first run.",
|
| 103 |
-
"Stock solution prepared fresh this morning; no precipitate seen.",
|
| 104 |
-
"Sampler needle flushed between runs.",
|
| 105 |
-
"Absorbance cell cleaned and blanked at the start of the shift.",
|
| 106 |
-
]
|
| 107 |
-
lines = rng.sample(filler, 2) + [
|
| 108 |
-
f"Sample {sid} in {fname} was a bad injection; exclude it from the fit." for sid, fname in bad
|
| 109 |
-
]
|
| 110 |
-
rng.shuffle(lines)
|
| 111 |
-
return "\n".join(f"- {line}" for line in lines) + "\n"
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
def build_kinetics(level: int, rng: random.Random) -> Built:
|
| 115 |
-
opener = rng.choice([
|
| 116 |
-
"You are analysing the decomposition of a reactant at constant temperature.",
|
| 117 |
-
"A kinetics lab is studying how fast a reactant decomposes at constant temperature.",
|
| 118 |
-
])
|
| 119 |
-
out = f"{ROOT}/kinetics_report.json"
|
| 120 |
-
if level == 1:
|
| 121 |
-
while True: # the flagged rows must move k past twice the tolerance when they are kept
|
| 122 |
-
text, pts, every = _kin_flagged(rng, rng.randint(110, 125))
|
| 123 |
-
k = _fit_k(pts)
|
| 124 |
-
if _order_clear(1, pts) and abs(_fit_k(every) / k - 1) > 0.01:
|
| 125 |
-
break
|
| 126 |
-
want = {"k_per_s": k, "half_life_s": math.log(2) / k}
|
| 127 |
-
files = {"data/run.csv": text}
|
| 128 |
-
instruction = (
|
| 129 |
-
f"{opener} An automatic sampler logged one row per sample to {ROOT}/data/run.csv, with the columns "
|
| 130 |
-
"sample, time_s (seconds since mixing), conc_M (concentration in mol/L) and flag. The reaction is "
|
| 131 |
-
"first order. Near the end of the run the concentration fell below the detection limit: on those rows "
|
| 132 |
-
"the sampler wrote the limit itself in conc_M and <LOD in flag. They are not measurements; drop them."
|
| 133 |
-
"\n\n"
|
| 134 |
-
"Fit k as minus the slope of an ordinary least-squares line of ln(concentration) against time in "
|
| 135 |
-
"seconds, using every remaining row. The half-life is ln(2)/k.\n\n"
|
| 136 |
-
f"Write {out} as a JSON object with exactly two keys, k_per_s (1/s) and half_life_s (seconds), for "
|
| 137 |
-
'example:\n\n{"k_per_s": 0.001234, "half_life_s": 561.7}\n\n'
|
| 138 |
-
"Each value is checked to within 0.5% (relative), so keep at least 4 significant figures."
|
| 139 |
-
)
|
| 140 |
-
elif level == 2:
|
| 141 |
-
order = rng.choice([1, 2])
|
| 142 |
-
while True:
|
| 143 |
-
text, pts, bad_id, every = _kin_run(rng, order, rng.randint(140, 160), True, True)
|
| 144 |
-
k = _fit(order, pts)[0]
|
| 145 |
-
if _order_clear(order, pts) and abs(_fit(order, every)[0] / k - 1) > 0.01:
|
| 146 |
-
break
|
| 147 |
-
half = math.log(2) / k if order == 1 else 1 / (k * pts[0][1])
|
| 148 |
-
want = {"order": order, "k": k, "half_life_s": half}
|
| 149 |
-
files = {"data/run.csv": text, "data/lab_notes.txt": _notes(rng, [(bad_id, "run.csv")])}
|
| 150 |
-
instruction = (
|
| 151 |
-
f"{opener} An automatic sampler logged {ROOT}/data/run.csv (columns sample, time_min, conc_mM). Rows "
|
| 152 |
-
"below the detection limit say <LOD instead of a number; drop them. The analyst's notes are in "
|
| 153 |
-
f"{ROOT}/data/lab_notes.txt; apply them.\n\n"
|
| 154 |
-
"The reaction is first or second order. Work in seconds and mol/L. Fit ln(C) and 1/C against t by "
|
| 155 |
-
"ordinary least squares; the order is the one whose line has the higher R^2. First order: k = -slope "
|
| 156 |
-
"(1/s), half-life ln(2)/k. Second order: k = slope (L/(mol s)), half-life 1/(k C0), with C0 the "
|
| 157 |
-
"concentration of the first kept row.\n\n"
|
| 158 |
-
f"Write {out} with the keys order (1 or 2), k and half_life_s (seconds), for example "
|
| 159 |
-
'{"order": 1, "k": 0.001234, "half_life_s": 561.7}. k and half_life_s are checked to within 0.5% '
|
| 160 |
-
"(relative)."
|
| 161 |
-
)
|
| 162 |
-
else:
|
| 163 |
-
t_low = rng.randint(288, 300)
|
| 164 |
-
t_high = t_low + rng.randint(12, 25)
|
| 165 |
-
names = (f"run_{t_low}K.csv", f"run_{t_high}K.csv")
|
| 166 |
-
order = rng.choice([1, 2])
|
| 167 |
-
while True:
|
| 168 |
-
bad_run = rng.randrange(2)
|
| 169 |
-
runs = [_kin_run(rng, order, rng.randint(100, 120), True, j == bad_run) for j in range(2)]
|
| 170 |
-
ks = [_fit(order, r[1])[0] for r in runs]
|
| 171 |
-
ea = R_GAS * math.log(ks[1] / ks[0]) / (1 / t_low - 1 / t_high) / 1000
|
| 172 |
-
dirty = _fit(order, runs[bad_run][3])[0]
|
| 173 |
-
if (all(_order_clear(order, r[1]) for r in runs) and 25 < ea < 110
|
| 174 |
-
and abs(dirty / ks[bad_run] - 1) > 0.01):
|
| 175 |
-
break
|
| 176 |
-
want = {"order": order, "k_low": ks[0], "k_high": ks[1], "ea_kj_per_mol": ea}
|
| 177 |
-
files = {f"data/{names[j]}": runs[j][0] for j in range(2)}
|
| 178 |
-
files["data/lab_notes.txt"] = _notes(rng, [(runs[bad_run][2], names[bad_run])])
|
| 179 |
-
instruction = (
|
| 180 |
-
f"The same decomposition was run at {t_low} K and {t_high} K. An automatic sampler logged "
|
| 181 |
-
f"{ROOT}/data/{names[0]} and {ROOT}/data/{names[1]} (columns sample, time_min, conc_mM). Drop rows "
|
| 182 |
-
f"that say <LOD, and apply the analyst's notes in {ROOT}/data/lab_notes.txt.\n\n"
|
| 183 |
-
"Both runs have the same order, first or second. Work in seconds and mol/L, fit ln(C) and 1/C "
|
| 184 |
-
"against t by ordinary least squares, and take the order with the higher R^2. First order: "
|
| 185 |
-
"k = -slope (1/s). Second order: k = slope (L/(mol s)). Then Ea = R ln(k_high/k_low) / "
|
| 186 |
-
"(1/T_low - 1/T_high) with R = 8.314 J/(mol K).\n\n"
|
| 187 |
-
f"Write {out} with the keys order (1 or 2), k_low, k_high and ea_kj_per_mol, for example "
|
| 188 |
-
'{"order": 2, "k_low": 0.0123, "k_high": 0.0456, "ea_kj_per_mol": 61.2}. k is checked to within '
|
| 189 |
-
"0.5% and Ea to within 1% (relative)."
|
| 190 |
-
)
|
| 191 |
-
checks = [
|
| 192 |
-
("test_is_object", lambda p: isinstance(p, dict)),
|
| 193 |
-
("test_keys", lambda p: set(p) == set(want)),
|
| 194 |
-
]
|
| 195 |
-
if "order" in want:
|
| 196 |
-
checks.append(("test_order", lambda p: p["order"] == want["order"] and not isinstance(p["order"], bool)))
|
| 197 |
-
for key, value in want.items():
|
| 198 |
-
if key != "order":
|
| 199 |
-
rel = 0.01 if key == "ea_kj_per_mol" else 0.005
|
| 200 |
-
checks.append((f"test_{key}", lambda p, key=key, value=value, rel=rel: _rel(p[key], value, rel)))
|
| 201 |
-
return Built(
|
| 202 |
-
instruction=instruction,
|
| 203 |
-
files=files,
|
| 204 |
-
artifact=Artifact(path="kinetics_report.json", kind="checks", parse="json", checks=checks,
|
| 205 |
-
render=lambda: json.dumps(want, indent=1) + "\n"),
|
| 206 |
-
root=ROOT,
|
| 207 |
-
)
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
# ---------------------------------------------------------------- sci3_stoich_batch
|
| 211 |
-
|
| 212 |
-
# Two-reactant reactions: plain formulas for L1-L2, hydrates for L3 (v2's REACTIONS, minus the gases).
|
| 213 |
-
PLAIN = [
|
| 214 |
-
"2 NaOH + H2SO4 -> Na2SO4 + 2 H2O",
|
| 215 |
-
"AgNO3 + NaCl -> AgCl + NaNO3",
|
| 216 |
-
"AgNO3 + KCl -> AgCl + KNO3",
|
| 217 |
-
"BaCl2 + Na2SO4 -> BaSO4 + 2 NaCl",
|
| 218 |
-
"CaCl2 + Na2CO3 -> CaCO3 + 2 NaCl",
|
| 219 |
-
"2 KOH + H2SO4 -> K2SO4 + 2 H2O",
|
| 220 |
-
]
|
| 221 |
-
HYDRATES = [
|
| 222 |
-
"CuSO4*5H2O + 2 NaOH -> Cu(OH)2 + Na2SO4 + 5 H2O",
|
| 223 |
-
"FeSO4*7H2O + 2 KOH -> Fe(OH)2 + K2SO4 + 7 H2O",
|
| 224 |
-
"BaCl2*2H2O + Na2SO4 -> BaSO4 + 2 NaCl + 2 H2O",
|
| 225 |
-
"MgSO4*7H2O + 2 NaOH -> Mg(OH)2 + Na2SO4 + 7 H2O",
|
| 226 |
-
]
|
| 227 |
-
SHELF = [ # other stockroom formulas, so the inventory is a real lookup
|
| 228 |
-
"NaCl", "KCl", "NaOH", "KOH", "HCl", "HNO3", "H2SO4", "Na2CO3", "NaHCO3", "CaCO3", "CaCl2", "MgCl2",
|
| 229 |
-
"KNO3", "NaNO3", "Na2SO4", "K2SO4", "MgSO4", "CuSO4", "AgNO3", "BaCl2", "Na3PO4", "H3PO4", "Ca(OH)2",
|
| 230 |
-
"Mg(OH)2", "Ba(NO3)2", "Ba(OH)2", "Al", "Cu", "Fe", "Mg", "Na2S2O3", "CuSO4*5H2O", "FeSO4*7H2O",
|
| 231 |
-
"MgSO4*7H2O", "BaCl2*2H2O", "NH4Cl", "(NH4)2SO4", "CaSO4*2H2O", "Na2HPO4", "KHCO3",
|
| 232 |
-
]
|
| 233 |
-
def _lot(rng: random.Random, used: set) -> str:
|
| 234 |
-
while True:
|
| 235 |
-
lot = f"{rng.choice('ABCDEFGHJK')}{rng.randrange(100, 1000)}"
|
| 236 |
-
if lot not in used:
|
| 237 |
-
used.add(lot)
|
| 238 |
-
return lot
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
def _date(rng: random.Random, lo: int = 0, hi: int = 600) -> str:
|
| 242 |
-
day = rng.randrange(lo, hi) # days after 2025-01-01, 30-day months, days capped at 28 so every date is real
|
| 243 |
-
return f"{2025 + day // 360}-{day % 360 // 30 + 1:02d}-{min(day % 30 + 1, 28):02d}"
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
def build_stoich(level: int, rng: random.Random) -> Built:
|
| 247 |
-
eq = rng.choice(HYDRATES if level == 3 else PLAIN)
|
| 248 |
-
left, right = eq.split(" -> ")
|
| 249 |
-
(ca, fa), (cb, fb) = _side(left)
|
| 250 |
-
cp, fp = rng.choice([p for p in _side(right) if p[1] != "H2O"])
|
| 251 |
-
n_rows = {1: 100, 2: 110, 3: 220}[level] # L1-L2: cat ~1,700 tokens, so a dump still leaves room to finish
|
| 252 |
-
dated = level == 3 # certified dates and re-assayed lots only at L3
|
| 253 |
-
while True:
|
| 254 |
-
used: set = set()
|
| 255 |
-
lots = {fa: _lot(rng, used), fb: _lot(rng, used)}
|
| 256 |
-
purity = {f: round(rng.uniform(88, 99.9), 1) for f in (fa, fb)}
|
| 257 |
-
stale = {}
|
| 258 |
-
if dated: # one batch lot was re-certified: an older row with a different purity stays in the table
|
| 259 |
-
who = rng.choice([fa, fb])
|
| 260 |
-
stale[who] = round(min(99.9, purity[who] + rng.choice([-1, 1]) * rng.uniform(3, 8)), 1)
|
| 261 |
-
mass_a = round(rng.uniform(8, 60), 2)
|
| 262 |
-
eq_a = mass_a * purity[fa] / 100 / molar_mass(fa) / ca
|
| 263 |
-
ratio = rng.choice([rng.uniform(1.15, 1.6), rng.uniform(0.6, 0.87)])
|
| 264 |
-
mass_b = round(eq_a * ratio * cb * molar_mass(fb) / (purity[fb] / 100), 2)
|
| 265 |
-
|
| 266 |
-
def report(pur):
|
| 267 |
-
ea_, eb_ = (m * pur[f] / 100 / molar_mass(f) / c for m, f, c in ((mass_a, fa, ca), (mass_b, fb, cb)))
|
| 268 |
-
return (fa if ea_ < eb_ else fb), min(ea_, eb_) * cp * molar_mass(fp), ea_ / eb_
|
| 269 |
-
|
| 270 |
-
limiting, theo, r = report(purity)
|
| 271 |
-
if abs(r - 1) < 0.08:
|
| 272 |
-
continue
|
| 273 |
-
iso = round(theo * rng.uniform(0.62, 0.95), 2)
|
| 274 |
-
if stale:
|
| 275 |
-
lim2, theo2, _ = report(dict(purity, **stale))
|
| 276 |
-
if lim2 == limiting and abs(theo2 / theo - 1) < 0.01:
|
| 277 |
-
continue # the stale row must change the answer
|
| 278 |
-
break
|
| 279 |
-
pct = iso / theo * 100
|
| 280 |
-
|
| 281 |
-
def extra(): # the fourth column: certified date at L3, shelf position at L1-L2
|
| 282 |
-
return _date(rng, 0, 600) if dated else f"{rng.choice('ABCDEF')}{rng.randint(1, 9)}"
|
| 283 |
-
|
| 284 |
-
# inventory: the batch lots plus shelf stock, shuffled; at L3 a few unrelated lots are re-certified too
|
| 285 |
-
rows = [(lots[f], f, purity[f], _date(rng, 300, 600) if dated else extra()) for f in (fa, fb)]
|
| 286 |
-
for f, p in stale.items():
|
| 287 |
-
rows.append((lots[f], f, p, _date(rng, 0, 290)))
|
| 288 |
-
while len(rows) < n_rows:
|
| 289 |
-
lot, f = _lot(rng, used), rng.choice(SHELF)
|
| 290 |
-
rows.append((lot, f, round(rng.uniform(85, 99.9), 1), extra()))
|
| 291 |
-
if dated and rng.random() < 0.08:
|
| 292 |
-
rows.append((lot, f, round(rng.uniform(85, 99.9), 1), extra()))
|
| 293 |
-
rng.shuffle(rows)
|
| 294 |
-
header = "lot,formula,purity_pct," + ("certified" if dated else "shelf")
|
| 295 |
-
reagents = header + "\n" + "".join(f"{a},{b},{c},{d}\n" for a, b, c, d in rows)
|
| 296 |
-
atomic = "element,mass\n" + "".join(f"{el},{m}\n" for el, m in MASSES.items())
|
| 297 |
-
charges = [(mass_a, fa), (mass_b, fb)]
|
| 298 |
-
rng.shuffle(charges)
|
| 299 |
-
batch = (f"Batch B-{rng.randrange(1000, 10000)}\nReaction: {eq}\n"
|
| 300 |
-
+ "".join(f"Charged: {m:.2f} g {f} from lot {lots[f]}\n" for m, f in charges)
|
| 301 |
-
+ f"Isolated: {iso:.2f} g {fp} (dried)\n")
|
| 302 |
-
files = {"data/batch.txt": batch, "data/reagents.csv": reagents, "data/atomic_masses.csv": atomic}
|
| 303 |
-
if dated:
|
| 304 |
-
files["data/README.md"] = (
|
| 305 |
-
"# Stockroom inventory notes\n\nLots are re-assayed from time to time and the new assay is added as a "
|
| 306 |
-
"new row, so a lot can appear more than once in reagents.csv. Use the row with the latest certified "
|
| 307 |
-
"date; older rows are superseded.\n\nA formula written like CuSO4*5H2O is a hydrate: the water "
|
| 308 |
-
"molecules are part of the solid and count toward its molar mass.\n")
|
| 309 |
-
out = f"{ROOT}/batch_report.json"
|
| 310 |
-
example = rng.choice([f for f in SHELF if f not in eq and "*" not in f and "(" not in f])
|
| 311 |
-
opener = rng.choice([
|
| 312 |
-
"You are checking a production batch for a small chemistry lab.",
|
| 313 |
-
"A process chemist asks you to audit one pilot-plant batch.",
|
| 314 |
-
])
|
| 315 |
-
table = (f"{ROOT}/data/reagents.csv is the stockroom inventory ({header.replace(',', ', ')}) and "
|
| 316 |
-
f"{ROOT}/data/atomic_masses.csv the atomic masses.")
|
| 317 |
-
if level == 1: # the v2 shape: the batch and both lots are named right here
|
| 318 |
-
charged = " and ".join(f"{m:.2f} g of {f} from lot {lots[f]}" for m, f in charges)
|
| 319 |
-
intro = (f"{opener} The batch ran {eq}, charging {charged}; {iso:.2f} g of {fp} was isolated "
|
| 320 |
-
f"(record: {ROOT}/data/batch.txt). {table}")
|
| 321 |
-
else:
|
| 322 |
-
intro = (f"{opener} {ROOT}/data/batch.txt is the batch record: the balanced equation, grams charged per "
|
| 323 |
-
f"reagent lot and grams of product isolated. {table}"
|
| 324 |
-
+ (f" Apply the notes in {ROOT}/data/README.md." if dated else ""))
|
| 325 |
-
instruction = (
|
| 326 |
-
f"{intro}\n\n"
|
| 327 |
-
"Only the pure part of a charge reacts: grams x purity_pct / 100. The limiting reagent has the fewest "
|
| 328 |
-
"moles divided by its coefficient. The theoretical yield is the grams of product that amount makes; "
|
| 329 |
-
"percent yield = isolated / theoretical x 100.\n\n"
|
| 330 |
-
f"Write {out} with the keys limiting_reagent (formula as in the equation), product_molar_mass (g/mol), "
|
| 331 |
-
f'theoretical_yield_g and percent_yield, for example {{"limiting_reagent": "{example}", '
|
| 332 |
-
'"product_molar_mass": 158.11, "theoretical_yield_g": 25.41, "percent_yield": 88.6}. Molar mass must be '
|
| 333 |
-
"within 0.01 and the others within 0.3% (relative)."
|
| 334 |
-
)
|
| 335 |
-
want = {"limiting_reagent": limiting, "product_molar_mass": molar_mass(fp), "theoretical_yield_g": theo,
|
| 336 |
-
"percent_yield": pct}
|
| 337 |
-
checks = [
|
| 338 |
-
("test_is_object", lambda p: isinstance(p, dict)),
|
| 339 |
-
("test_keys", lambda p: set(p) == set(want)),
|
| 340 |
-
("test_limiting_reagent", lambda p: isinstance(p["limiting_reagent"], str)
|
| 341 |
-
and p["limiting_reagent"].strip() == limiting),
|
| 342 |
-
("test_product_molar_mass", lambda p: not isinstance(p["product_molar_mass"], bool)
|
| 343 |
-
and abs(float(p["product_molar_mass"]) - want["product_molar_mass"]) <= 0.01 + 1e-9),
|
| 344 |
-
("test_theoretical_yield_g", lambda p: _rel(p["theoretical_yield_g"], theo, 0.003)),
|
| 345 |
-
("test_percent_yield", lambda p: _rel(p["percent_yield"], pct, 0.003)),
|
| 346 |
-
]
|
| 347 |
-
return Built(
|
| 348 |
-
instruction=instruction,
|
| 349 |
-
files=files,
|
| 350 |
-
artifact=Artifact(path="batch_report.json", kind="checks", parse="json", checks=checks,
|
| 351 |
-
render=lambda: json.dumps(want, indent=1) + "\n"),
|
| 352 |
-
root=ROOT,
|
| 353 |
-
)
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
# ---------------------------------------------------------------- sci3_lightcurve_period
|
| 357 |
-
|
| 358 |
-
CADENCE_D = 20 / 1440
|
| 359 |
-
QUALITY_BAD = (1, 4, 32, 128, 1024)
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
def _in_transit(t: float, period: float, t0: float, dur: float) -> bool:
|
| 363 |
-
return abs((t - t0 + period / 2) % period - period / 2) < dur / 2
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
def build_lightcurve(level: int, rng: random.Random) -> Built:
|
| 367 |
-
days = 40.0 if level == 3 else 27.0
|
| 368 |
-
start = round(rng.uniform(60000, 61000), 2)
|
| 369 |
-
period = round(rng.uniform(1.5, 4.2), 5)
|
| 370 |
-
dur = rng.choice([0.08, 0.09, 0.10, 0.11, 0.12])
|
| 371 |
-
depth = rng.uniform(0.005, 0.009)
|
| 372 |
-
t0 = start + rng.uniform(0, period)
|
| 373 |
-
prot, amp, phase = rng.uniform(3.5, 9.0), rng.uniform(0.005, 0.015), rng.uniform(0, 2 * math.pi)
|
| 374 |
-
second = None
|
| 375 |
-
if level == 3: # a shallower, shorter planet whose box signal stays well below the target's
|
| 376 |
-
while True:
|
| 377 |
-
p2 = round(rng.uniform(1.1, 4.8), 5)
|
| 378 |
-
ratio = max(p2, period) / min(p2, period)
|
| 379 |
-
if min(abs(ratio - m) for m in (1, 1.5, 2, 2.5, 3, 4)) > 0.12:
|
| 380 |
-
break
|
| 381 |
-
second = (p2, start + rng.uniform(0, p2), 0.05, 0.35 * depth)
|
| 382 |
-
dump = None
|
| 383 |
-
if level >= 2: # momentum dump: quality 0 but corrupted by a ramp
|
| 384 |
-
a = round(start + rng.uniform(0.2, 0.8) * days, 3)
|
| 385 |
-
dump = (a, round(a + 0.5, 3), rng.choice([-1, 1]) * rng.uniform(0.01, 0.02))
|
| 386 |
-
lines = ["# time_mjd flux quality"]
|
| 387 |
-
for i in range(int(days / CADENCE_D)):
|
| 388 |
-
t = start + i * CADENCE_D
|
| 389 |
-
x = 2 * math.pi * (t - start) / prot + phase
|
| 390 |
-
f = 1 + amp * math.sin(x) + 0.3 * amp * math.sin(2 * x + 1.0)
|
| 391 |
-
if _in_transit(t, period, t0, dur):
|
| 392 |
-
f -= depth
|
| 393 |
-
if second and _in_transit(t, second[0], second[1], second[2]):
|
| 394 |
-
f -= second[3]
|
| 395 |
-
f += rng.gauss(0, 0.0009)
|
| 396 |
-
q = 0
|
| 397 |
-
if rng.random() < 0.03:
|
| 398 |
-
q = rng.choice(QUALITY_BAD)
|
| 399 |
-
f *= 1 + rng.choice([-1, 1]) * rng.uniform(0.02, 0.08)
|
| 400 |
-
if dump and dump[0] <= t <= dump[1]:
|
| 401 |
-
f *= 1 + dump[2] * (t - dump[0]) / 0.5
|
| 402 |
-
lines.append(f"{t:.5f} {f:.6f} {q}")
|
| 403 |
-
files = {"data/lc.txt": "\n".join(lines) + "\n"}
|
| 404 |
-
if dump:
|
| 405 |
-
files["data/README.md"] = (
|
| 406 |
-
"# Light curve notes\n\nBetween MJD {:.3f} and {:.3f} the spacecraft fired its thrusters (momentum "
|
| 407 |
-
"dump). Those points carry quality 0 but are corrupted: discard every point in that interval before "
|
| 408 |
-
"searching.\n".format(dump[0], dump[1]))
|
| 409 |
-
out = f"{ROOT}/period.txt"
|
| 410 |
-
hours = round(dur * 24, 2)
|
| 411 |
-
example = "2.44535" if abs(period - 2.44535) > 0.05 else "3.81726" # never near the answer
|
| 412 |
-
notes = f" Read {ROOT}/data/README.md for other data to discard." if dump else ""
|
| 413 |
-
two = " The data may hold two transit signals; report the deeper one." if second else ""
|
| 414 |
-
instruction = (
|
| 415 |
-
f"{ROOT}/data/lc.txt is a space-telescope light curve: a comment line, then rows of time (MJD), "
|
| 416 |
-
"normalized flux and a quality flag (0 means good), one every 20 minutes. The star is spotted, so its "
|
| 417 |
-
"brightness swings by about one percent as it rotates every few days. Hidden under that is a planet "
|
| 418 |
-
f"whose transit dims the star by about 0.5-0.9% for {hours} hours ({dur:.2f} d) once per orbit.\n\n"
|
| 419 |
-
f"1. Drop every point with a nonzero quality flag.{notes}\n"
|
| 420 |
-
"2. Remove the stellar variability, for example by dividing by a running median about 0.75 d wide.\n"
|
| 421 |
-
"3. Search trial periods from 1.000 to 5.000 d in steps of 0.001 d for the periodic box-shaped dip of "
|
| 422 |
-
f"that duration. The rotation period is not the answer.{two}\n\n"
|
| 423 |
-
f"Write the period in days to {out} as one number with exactly 5 decimals, for example {example}. It is "
|
| 424 |
-
"accepted within 0.2% of the true period."
|
| 425 |
-
)
|
| 426 |
-
|
| 427 |
-
def single(text):
|
| 428 |
-
return len(text.split()) == 1 and float(text.strip()) > 0
|
| 429 |
-
|
| 430 |
-
checks = [
|
| 431 |
-
("test_single_number", single),
|
| 432 |
-
("test_five_decimals", lambda s: len(s.strip().partition(".")[2]) == 5 and s.strip().count(".") == 1),
|
| 433 |
-
("test_period_value", lambda s: abs(float(s.strip()) - period) <= 0.002 * period),
|
| 434 |
-
]
|
| 435 |
-
return Built(
|
| 436 |
-
instruction=instruction,
|
| 437 |
-
files=files,
|
| 438 |
-
artifact=Artifact(path="period.txt", kind="checks", parse="text", checks=checks,
|
| 439 |
-
render=lambda: f"{period:.5f}\n"),
|
| 440 |
-
root=ROOT,
|
| 441 |
-
notes={"period": period, "second": second},
|
| 442 |
-
)
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
FAMILIES = [
|
| 446 |
-
Family("sci3_kinetics_fit", "natural science", "Kinetics order, rate constant and half-life",
|
| 447 |
-
build_kinetics, v3=True),
|
| 448 |
-
Family("sci3_stoich_batch", "natural science", "Batch limiting reagent and yield from a stockroom table",
|
| 449 |
-
build_stoich, v3=True),
|
| 450 |
-
Family("sci3_lightcurve_period", "natural science", "Transit period from a spotted star's light curve",
|
| 451 |
-
build_lightcurve, v3=True),
|
| 452 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/security.py
DELETED
|
@@ -1,224 +0,0 @@
|
|
| 1 |
-
"""Cybersecurity: find brute-forced SSH logins; evaluate first-match firewall rules."""
|
| 2 |
-
|
| 3 |
-
import datetime as dt
|
| 4 |
-
import ipaddress
|
| 5 |
-
import random
|
| 6 |
-
|
| 7 |
-
from .base import Artifact, Built, Family, Field
|
| 8 |
-
|
| 9 |
-
USERS = ["alice", "bob", "carol", "deploy", "backup", "root", "admin", "git"]
|
| 10 |
-
|
| 11 |
-
# ---------------------------------------------------------------- sec_auth
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
def _ip(rng: random.Random, v6: bool = False) -> str:
|
| 15 |
-
if v6:
|
| 16 |
-
return f"2001:db8:{rng.randint(1, 0xffff):x}::{rng.randint(1, 0xffff):x}"
|
| 17 |
-
net = rng.choice(["198.51.100", "203.0.113", "192.0.2"])
|
| 18 |
-
return f"{net}.{rng.randint(2, 254)}"
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
def build_auth(level: int, rng: random.Random) -> Built:
|
| 22 |
-
k = {1: 5, 2: 4, 3: 4}[level]
|
| 23 |
-
while True:
|
| 24 |
-
day = dt.datetime(2026, 11, 3, 0, 0, 0)
|
| 25 |
-
events = [] # (time, ip, kind, user)
|
| 26 |
-
actors = []
|
| 27 |
-
n_actors = {1: 8, 2: 14, 3: 20}[level]
|
| 28 |
-
used = set()
|
| 29 |
-
allow_nets = ["198.51.100.0/26"] if level == 3 else []
|
| 30 |
-
for _ in range(n_actors):
|
| 31 |
-
v6 = level >= 2 and rng.random() < 0.25
|
| 32 |
-
ip = _ip(rng, v6)
|
| 33 |
-
if ip in used:
|
| 34 |
-
continue
|
| 35 |
-
used.add(ip)
|
| 36 |
-
role = rng.choice(["brute_win", "brute_fail", "legit", "legit_typo"])
|
| 37 |
-
t = day + dt.timedelta(seconds=rng.randint(0, 80000))
|
| 38 |
-
if role.startswith("brute"):
|
| 39 |
-
fails = rng.randint(k - 2, k + 8)
|
| 40 |
-
for _ in range(fails):
|
| 41 |
-
user = rng.choice(USERS)
|
| 42 |
-
invalid = level >= 2 and user in ("admin", "git") and rng.random() < 0.7
|
| 43 |
-
events.append((t, ip, "fail_invalid" if invalid else "fail", user))
|
| 44 |
-
t += dt.timedelta(seconds=rng.randint(1, 20))
|
| 45 |
-
if role == "brute_win":
|
| 46 |
-
events.append((t, ip, "accept", rng.choice(["root", "deploy", "backup"])))
|
| 47 |
-
t += dt.timedelta(seconds=rng.randint(30, 600))
|
| 48 |
-
if rng.random() < 0.5:
|
| 49 |
-
events.append((t, ip, "fail", "root"))
|
| 50 |
-
else:
|
| 51 |
-
user = rng.choice(USERS[:4])
|
| 52 |
-
if role == "legit_typo":
|
| 53 |
-
for _ in range(rng.randint(1, k - 1)):
|
| 54 |
-
events.append((t, ip, "fail", user))
|
| 55 |
-
t += dt.timedelta(seconds=rng.randint(3, 30))
|
| 56 |
-
events.append((t, ip, "accept", user))
|
| 57 |
-
actors.append(ip)
|
| 58 |
-
if level == 3:
|
| 59 |
-
scanner = f"198.51.100.{rng.randint(2, 60)}"
|
| 60 |
-
if scanner not in used:
|
| 61 |
-
t = day + dt.timedelta(seconds=rng.randint(0, 80000))
|
| 62 |
-
for _ in range(k + 3):
|
| 63 |
-
events.append((t, scanner, "fail", "root"))
|
| 64 |
-
t += dt.timedelta(seconds=2)
|
| 65 |
-
events.append((t, scanner, "accept", "audit"))
|
| 66 |
-
events.sort()
|
| 67 |
-
fails, breach = {}, {}
|
| 68 |
-
for t, ip, kind, user in events:
|
| 69 |
-
if kind.startswith("fail"):
|
| 70 |
-
if ip not in breach:
|
| 71 |
-
fails[ip] = fails.get(ip, 0) + 1
|
| 72 |
-
elif ip not in breach and fails.get(ip, 0) >= k:
|
| 73 |
-
breach[ip] = t
|
| 74 |
-
elif kind == "accept" and ip not in breach:
|
| 75 |
-
fails[ip] = fails.get(ip, 0)
|
| 76 |
-
breach.setdefault(ip, None)
|
| 77 |
-
hits = {
|
| 78 |
-
ip: t
|
| 79 |
-
for ip, t in breach.items()
|
| 80 |
-
if t is not None and not any(ipaddress.ip_address(ip) in ipaddress.ip_network(n) for n in allow_nets)
|
| 81 |
-
}
|
| 82 |
-
if 1 <= len(hits) <= 5:
|
| 83 |
-
break
|
| 84 |
-
def line(t, ip, kind, user, pid):
|
| 85 |
-
port = rng.randint(30000, 65000)
|
| 86 |
-
stamp = f"{t:%b} {t.day:2d} {t:%H:%M:%S}"
|
| 87 |
-
if kind == "fail":
|
| 88 |
-
msg = f"Failed password for {user} from {ip} port {port} ssh2"
|
| 89 |
-
elif kind == "fail_invalid":
|
| 90 |
-
msg = f"Failed password for invalid user {user} from {ip} port {port} ssh2"
|
| 91 |
-
else:
|
| 92 |
-
method = "publickey" if level >= 2 and rng.random() < 0.4 else "password"
|
| 93 |
-
msg = f"Accepted {method} for {user} from {ip} port {port} ssh2"
|
| 94 |
-
return f"{stamp} bastion sshd[{pid}]: {msg}"
|
| 95 |
-
|
| 96 |
-
out = []
|
| 97 |
-
for t, ip, kind, user in events:
|
| 98 |
-
pid = rng.randint(1000, 60000)
|
| 99 |
-
out.append((t, line(t, ip, kind, user, pid)))
|
| 100 |
-
if rng.random() < 0.3:
|
| 101 |
-
stamp = f"{t:%b} {t.day:2d} {t:%H:%M:%S}"
|
| 102 |
-
out.append((t, f"{stamp} bastion sshd[{pid}]: Connection closed by {ip} port {rng.randint(30000, 65000)} [preauth]"))
|
| 103 |
-
files = {}
|
| 104 |
-
if level == 3:
|
| 105 |
-
cut = len(out) // 2
|
| 106 |
-
files["auth.log.1"] = "\n".join(s for _, s in out[:cut]) + "\n"
|
| 107 |
-
files["auth.log"] = "\n".join(s for _, s in out[cut:]) + "\n"
|
| 108 |
-
files["allowlist.txt"] = (
|
| 109 |
-
"Internal audit scanners. Their activity is expected; never report them:\n"
|
| 110 |
-
+ "".join(f" {n}\n" for n in allow_nets)
|
| 111 |
-
)
|
| 112 |
-
where = "auth.log.1 (older) and auth.log (newer) in /app hold one day of sshd logs; never block a source in allowlist.txt."
|
| 113 |
-
else:
|
| 114 |
-
files["auth.log"] = "\n".join(s for _, s in out) + "\n"
|
| 115 |
-
where = "auth.log in /app holds one day of sshd logs."
|
| 116 |
-
instruction = (
|
| 117 |
-
f"{where} Block every source IP that logged at least {k} failed password attempts (for any user, valid "
|
| 118 |
-
"or not) before its first accepted login (password or key); lines after that login do not count. "
|
| 119 |
-
"Write the IPs to /app/blocked.txt, one per line, nothing else."
|
| 120 |
-
)
|
| 121 |
-
artifact = Artifact(path="blocked.txt", kind="lines", expected=sorted(hits))
|
| 122 |
-
return Built(instruction=instruction, files=files, artifact=artifact)
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
# ---------------------------------------------------------------- sec_fw
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
def _port_spec(rng: random.Random) -> tuple[str, set | None]:
|
| 129 |
-
kind = rng.random()
|
| 130 |
-
if kind < 0.45:
|
| 131 |
-
p = rng.choice([22, 53, 80, 443, 3306, 5432, 6379, 8080])
|
| 132 |
-
return str(p), {p}
|
| 133 |
-
if kind < 0.7:
|
| 134 |
-
ps = rng.sample([22, 25, 80, 443, 8080, 8443], 2)
|
| 135 |
-
return ",".join(map(str, ps)), set(ps)
|
| 136 |
-
if kind < 0.9:
|
| 137 |
-
lo = rng.choice([1000, 3000, 8000])
|
| 138 |
-
hi = lo + rng.choice([99, 999])
|
| 139 |
-
return f"{lo}-{hi}", set(range(lo, hi + 1))
|
| 140 |
-
return "any", None
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
NETS = ["10.0.0.0/8", "10.20.0.0/16", "10.20.5.0/24", "192.168.0.0/16", "192.168.10.0/24", "172.16.0.0/12", "any"]
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
def build_fw(level: int, rng: random.Random) -> Built:
|
| 147 |
-
n_rules, n_conn = {1: 5, 2: 9, 3: 14}[level], {1: 15, 2: 40, 3: 70}[level]
|
| 148 |
-
while True:
|
| 149 |
-
rules = []
|
| 150 |
-
for _ in range(n_rules):
|
| 151 |
-
action = rng.choice(["allow", "allow", "deny"])
|
| 152 |
-
proto = rng.choice(["tcp", "tcp", "udp", "any"])
|
| 153 |
-
net = rng.choice(NETS if level >= 2 else ["10.0.0.0/8", "192.168.0.0/16", "any"])
|
| 154 |
-
spec, ports = _port_spec(rng)
|
| 155 |
-
disabled = level == 3 and rng.random() < 0.2
|
| 156 |
-
rules.append((action, proto, net, spec, ports, disabled))
|
| 157 |
-
conns = []
|
| 158 |
-
for i in range(n_conn):
|
| 159 |
-
src = rng.choice(
|
| 160 |
-
[
|
| 161 |
-
f"10.{rng.choice([20, rng.randint(0, 255)])}.{rng.choice([5, rng.randint(0, 255)])}.{rng.randint(1, 254)}",
|
| 162 |
-
f"192.168.{rng.choice([10, rng.randint(0, 255)])}.{rng.randint(1, 254)}",
|
| 163 |
-
f"172.{rng.randint(10, 40)}.{rng.randint(0, 255)}.{rng.randint(1, 254)}",
|
| 164 |
-
f"203.0.113.{rng.randint(1, 254)}",
|
| 165 |
-
]
|
| 166 |
-
)
|
| 167 |
-
proto = rng.choice(["tcp", "tcp", "udp"])
|
| 168 |
-
port = rng.choice([22, 22, 53, 80, 443, 3306, 5432, 8080, 8443, 1080, 3100, 8050, 25])
|
| 169 |
-
conns.append((f"c{i + 1:03d}", src, proto, port))
|
| 170 |
-
|
| 171 |
-
def match(rule, src, proto, port):
|
| 172 |
-
action, rproto, net, _, ports, disabled = rule
|
| 173 |
-
if disabled:
|
| 174 |
-
return False
|
| 175 |
-
if rproto != "any" and rproto != proto:
|
| 176 |
-
return False
|
| 177 |
-
if net != "any" and ipaddress.ip_address(src) not in ipaddress.ip_network(net):
|
| 178 |
-
return False
|
| 179 |
-
return ports is None or port in ports
|
| 180 |
-
|
| 181 |
-
hit_count = {i: 0 for i in range(n_rules + 1)}
|
| 182 |
-
allowed, denied_ssh, verdicts = 0, [], []
|
| 183 |
-
for cid, src, proto, port in conns:
|
| 184 |
-
num = next((i + 1 for i, r in enumerate(rules) if match(r, src, proto, port)), 0)
|
| 185 |
-
hit_count[num] += 1
|
| 186 |
-
verdict = rules[num - 1][0] if num else "deny"
|
| 187 |
-
verdicts.append({"id": cid, "verdict": verdict, "rule": num})
|
| 188 |
-
if verdict == "allow":
|
| 189 |
-
allowed += 1
|
| 190 |
-
elif port == 22:
|
| 191 |
-
denied_ssh.append(cid)
|
| 192 |
-
ranked = sorted(hit_count.items(), key=lambda kv: -kv[1])
|
| 193 |
-
if ranked[0][1] > ranked[1][1] and 0 < allowed < n_conn and denied_ssh:
|
| 194 |
-
break
|
| 195 |
-
lines = ["# first matching rule wins; a connection no rule matches is denied (default deny)"]
|
| 196 |
-
for i, (action, proto, net, spec, _, disabled) in enumerate(rules, start=1):
|
| 197 |
-
text = f"{i} {action} proto={proto} src={net} port={spec}"
|
| 198 |
-
lines.append(f"# {text} (disabled, not loaded)" if disabled else text)
|
| 199 |
-
files = {
|
| 200 |
-
"rules.txt": "\n".join(lines) + "\n",
|
| 201 |
-
"connections.csv": "id,src_ip,proto,dst_port\n" + "".join(f"{c},{s},{p},{d}\n" for c, s, p, d in conns),
|
| 202 |
-
}
|
| 203 |
-
instruction = (
|
| 204 |
-
"rules.txt and connections.csv are in /app. Evaluate every connection against the rules: a rule matches "
|
| 205 |
-
"when its proto equals the connection's (or is any), the source IP is inside its src network (or src is "
|
| 206 |
-
"any), and the destination port is in its port list or range (or port is any). The first matching rule "
|
| 207 |
-
"decides; commented-out rules are not loaded; no match means deny. Write /app/verdicts.csv with the "
|
| 208 |
-
"header id,verdict,rule and one row per connection: verdict is allow or deny, rule is the deciding "
|
| 209 |
-
"rule's number (0 for the default deny). Example: c001,allow,3"
|
| 210 |
-
)
|
| 211 |
-
artifact = Artifact(
|
| 212 |
-
path="verdicts.csv",
|
| 213 |
-
kind="csv",
|
| 214 |
-
key=("id",),
|
| 215 |
-
fields=[Field("id", "text"), Field("verdict", "text"), Field("rule", "int")],
|
| 216 |
-
expected=verdicts,
|
| 217 |
-
)
|
| 218 |
-
return Built(instruction=instruction, files=files, artifact=artifact)
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
FAMILIES = [
|
| 222 |
-
Family("sec_auth", "cybersecurity", "Find brute-forced SSH logins", build_auth),
|
| 223 |
-
Family("sec_fw", "cybersecurity", "Evaluate firewall rules", build_fw),
|
| 224 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/security3.py
DELETED
|
@@ -1,521 +0,0 @@
|
|
| 1 |
-
"""Cybersecurity v3: SSH brute-force triage, firewall verdicts, off-hours exfiltration flows.
|
| 2 |
-
|
| 3 |
-
Each generator computes the expected answer itself from the records it emits; the oracle
|
| 4 |
-
scripts in terminal_desk/oracles/ only prove the files carry everything the answer needs.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import ipaddress
|
| 8 |
-
import json
|
| 9 |
-
import random
|
| 10 |
-
|
| 11 |
-
from .base import Artifact, Built, Family
|
| 12 |
-
|
| 13 |
-
ROOT = "/root"
|
| 14 |
-
DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def _clock(sec: int) -> str:
|
| 18 |
-
return f"{sec // 3600:02d}:{sec // 60 % 60:02d}:{sec % 60:02d}"
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
def _public_ip(rng: random.Random, used: set) -> str:
|
| 22 |
-
while True:
|
| 23 |
-
ip = f"{rng.choice([37, 45, 61, 77, 89, 91, 94])}.{rng.randint(1, 99)}.{rng.randint(0, 99)}.{rng.randint(2, 99)}"
|
| 24 |
-
if ip not in used:
|
| 25 |
-
used.add(ip)
|
| 26 |
-
return ip
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def _in_any(ip: str, nets) -> bool:
|
| 30 |
-
addr = ipaddress.ip_address(ip)
|
| 31 |
-
return any(addr in ipaddress.ip_network(n) for n in nets)
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def _ip_checks(want: set) -> list:
|
| 35 |
-
def one_ip_per_line(lines):
|
| 36 |
-
for s in lines:
|
| 37 |
-
ipaddress.ip_address(s)
|
| 38 |
-
return True
|
| 39 |
-
|
| 40 |
-
return [
|
| 41 |
-
("test_one_ip_per_line", one_ip_per_line),
|
| 42 |
-
("test_no_duplicates", lambda lines: len(lines) == len(set(lines))),
|
| 43 |
-
("test_no_false_positives", lambda lines: set(lines) <= want),
|
| 44 |
-
("test_no_missed_ips", lambda lines: want <= set(lines)),
|
| 45 |
-
]
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
# ---------------------------------------------------------------- sec3_auth_triage
|
| 49 |
-
|
| 50 |
-
USERS_VALID = ["root", "deploy", "git", "backup", "ubuntu", "alice", "bob", "carol"]
|
| 51 |
-
USERS_INVALID = ["admin", "oracle", "test", "postgres", "user", "pi", "ftp", "guest"]
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def build_auth(level: int, rng: random.Random) -> Built:
|
| 55 |
-
k, w = 5, 10 # fixed: the rule lives in the instruction, so one oracle serves every instance
|
| 56 |
-
span = w * 60
|
| 57 |
-
target = {1: 150, 2: 300, 3: 450}[level]
|
| 58 |
-
while True:
|
| 59 |
-
used: set = set()
|
| 60 |
-
lines = [] # (sec, ip, text, failures)
|
| 61 |
-
allow = []
|
| 62 |
-
|
| 63 |
-
def fail(t, ip, user=None):
|
| 64 |
-
user = user or rng.choice(USERS_VALID[:5] + USERS_INVALID)
|
| 65 |
-
if user in USERS_INVALID:
|
| 66 |
-
if level >= 2:
|
| 67 |
-
lines.append((t, ip, f"Invalid user {user} from {ip}", 0))
|
| 68 |
-
lines.append((t, ip, f"Failed password for invalid user {user} from {ip}", 1))
|
| 69 |
-
else:
|
| 70 |
-
lines.append((t, ip, f"Failed password for {user} from {ip}", 1))
|
| 71 |
-
|
| 72 |
-
def burst(ip, n, gap_lo, gap_hi, t=None, repeats=True):
|
| 73 |
-
t = rng.randint(0, 86399 - n * gap_hi - 700) if t is None else t
|
| 74 |
-
times, i = [], 0
|
| 75 |
-
user = rng.choice(USERS_VALID[:5] + USERS_INVALID)
|
| 76 |
-
while i < n:
|
| 77 |
-
fail(t, ip, user)
|
| 78 |
-
times.append(t)
|
| 79 |
-
i += 1
|
| 80 |
-
if repeats and level == 3 and user in USERS_VALID and n - i >= 2 and rng.random() < 0.3:
|
| 81 |
-
rep = rng.randint(2, min(4, n - i))
|
| 82 |
-
t += rng.randint(1, 3) * rep
|
| 83 |
-
lines.append((t, ip, f"message repeated {rep} times: [ Failed password for {user} from {ip}]", rep))
|
| 84 |
-
times += [t] * rep
|
| 85 |
-
i += rep
|
| 86 |
-
t += rng.randint(gap_lo, gap_hi)
|
| 87 |
-
if rng.random() < 0.3:
|
| 88 |
-
user = rng.choice(USERS_VALID[:5] + USERS_INVALID)
|
| 89 |
-
lines.append((t, ip, f"Connection closed by {ip} [preauth]", 0))
|
| 90 |
-
return times
|
| 91 |
-
|
| 92 |
-
def session(ip, user=None):
|
| 93 |
-
user = user or rng.choice(USERS_VALID[3:])
|
| 94 |
-
t = rng.randint(0, 80000)
|
| 95 |
-
method = rng.choice(["password", "publickey"])
|
| 96 |
-
lines.append((t, ip, f"Accepted {method} for {user} from {ip}", 0))
|
| 97 |
-
lines.append((t + rng.randint(30, 5000), ip, f"Disconnected from user {user} {ip}", 0))
|
| 98 |
-
|
| 99 |
-
n_brute = rng.randint(*{1: (2, 4), 2: (3, 5), 3: (4, 6)}[level])
|
| 100 |
-
for _ in range(n_brute):
|
| 101 |
-
burst(_public_ip(rng, used), rng.randint(k, k + 9), 2, 40)
|
| 102 |
-
for _ in range({1: 2, 2: 3, 3: 4}[level]): # slow: spaced out, unless a collapsed repeat bunches k (L3)
|
| 103 |
-
lo = span // (k - 1) + 5
|
| 104 |
-
burst(_public_ip(rng, used), rng.randint(k + 1, k + 4), lo, lo + 120)
|
| 105 |
-
for _ in range({1: 2, 2: 3, 3: 4}[level]): # near miss: k-1 quick failures, then a login
|
| 106 |
-
ip = _public_ip(rng, used)
|
| 107 |
-
user = rng.choice(USERS_VALID[5:])
|
| 108 |
-
t0 = rng.randint(0, 80000)
|
| 109 |
-
for j in range(k - 1):
|
| 110 |
-
fail(t0 + 9 * j, ip, user)
|
| 111 |
-
lines.append((t0 + 9 * (k - 1), ip, f"Accepted password for {user} from {ip}", 0))
|
| 112 |
-
if level >= 2:
|
| 113 |
-
for exact in (True, False): # k failures spanning exactly the window (blocked) or one second more
|
| 114 |
-
ip = _public_ip(rng, used)
|
| 115 |
-
t0 = rng.randint(0, 80000)
|
| 116 |
-
cuts = sorted(rng.sample(range(1, span), k - 2))
|
| 117 |
-
for off in [0] + cuts + [span + (0 if exact else 1)]:
|
| 118 |
-
fail(t0 + off, ip)
|
| 119 |
-
prefix, base = f"10.{rng.randint(2, 9)}.{rng.randint(2, 9)}", rng.choice([0, 64])
|
| 120 |
-
allow = [f"{prefix}.{base}/26"] # the audit scanner network; its neighbour /26 is not exempt
|
| 121 |
-
scanner = f"{prefix}.{base + rng.randint(1, 62)}"
|
| 122 |
-
outsider = f"{prefix}.{64 + rng.randint(1, 35) if base == 0 else rng.randint(2, 62)}"
|
| 123 |
-
used.update({scanner, outsider})
|
| 124 |
-
burst(scanner, rng.randint(k + 2, k + 8), 1, 5)
|
| 125 |
-
burst(outsider, rng.randint(k, k + 4), 3, 30)
|
| 126 |
-
straddle = None
|
| 127 |
-
if level == 3:
|
| 128 |
-
straddle = _public_ip(rng, used)
|
| 129 |
-
times = burst(straddle, k, 5, 30, t=rng.randint(40000, 46000), repeats=False)
|
| 130 |
-
cut = times[1] + 1
|
| 131 |
-
offices = [f"10.0.{rng.randint(1, 9)}.{rng.randint(2, 99)}" for _ in range(rng.randint(4, 7))]
|
| 132 |
-
while len(lines) < target - 20:
|
| 133 |
-
r = rng.random()
|
| 134 |
-
if r < 0.45:
|
| 135 |
-
session(rng.choice(offices))
|
| 136 |
-
else: # internet background noise: one or two failures
|
| 137 |
-
ip = _public_ip(rng, used)
|
| 138 |
-
t = rng.randint(0, 86000)
|
| 139 |
-
for j in range(rng.randint(1, 2)):
|
| 140 |
-
fail(t + j * rng.randint(60, 900), ip)
|
| 141 |
-
lines = [ln for ln in lines if ln[0] < 86400]
|
| 142 |
-
lines.sort(key=lambda x: x[0])
|
| 143 |
-
|
| 144 |
-
def blocked(notice=0, repeat=None):
|
| 145 |
-
"""The answer; notice=1 or repeat=1 give the two README misreadings."""
|
| 146 |
-
per_ip: dict = {}
|
| 147 |
-
for t, ip, msg, n in lines:
|
| 148 |
-
if msg.startswith("Invalid user"):
|
| 149 |
-
n = notice
|
| 150 |
-
elif repeat is not None and msg.startswith("message repeated"):
|
| 151 |
-
n = repeat
|
| 152 |
-
per_ip.setdefault(ip, []).extend([t] * n)
|
| 153 |
-
out = set()
|
| 154 |
-
for ip, ts in per_ip.items():
|
| 155 |
-
ts.sort()
|
| 156 |
-
if any(ts[i + k - 1] - ts[i] <= span for i in range(len(ts) - k + 1)) and not _in_any(ip, allow):
|
| 157 |
-
out.add(ip)
|
| 158 |
-
return out
|
| 159 |
-
|
| 160 |
-
want = blocked()
|
| 161 |
-
ok = 2 <= len(want) <= 10 and (straddle is None or straddle in want)
|
| 162 |
-
if level >= 2: # counting the Invalid user notices as attempts must change the answer
|
| 163 |
-
ok = ok and blocked(notice=1) != want
|
| 164 |
-
if level == 3: # reading a repeated-message line as one attempt must change the answer
|
| 165 |
-
ok = ok and blocked(repeat=1) != want
|
| 166 |
-
if ok:
|
| 167 |
-
break
|
| 168 |
-
|
| 169 |
-
def text(chunk):
|
| 170 |
-
return "".join(f"{_clock(t)} {msg}\n" for t, _, msg, _ in chunk)
|
| 171 |
-
|
| 172 |
-
if level == 3:
|
| 173 |
-
files = {"auth.log.1": text([x for x in lines if x[0] < cut]), "auth.log": text([x for x in lines if x[0] >= cut])}
|
| 174 |
-
where = ("The log was rotated at midday: /root/auth.log.1 holds the morning and /root/auth.log the rest of "
|
| 175 |
-
"3 November 2026.")
|
| 176 |
-
else:
|
| 177 |
-
files = {"auth.log": text(lines)}
|
| 178 |
-
where = "The sshd messages for 3 November 2026 are in /root/auth.log, one per line."
|
| 179 |
-
readme = ""
|
| 180 |
-
if level >= 2:
|
| 181 |
-
readme = ("# Bastion notes\n\nThe audit team runs a password-spray test from the scanner network below. "
|
| 182 |
-
"Its addresses are expected to fail logins: never block an address inside it.\n\n"
|
| 183 |
-
f"- {allow[0]}\n\nsshd logs `Invalid user NAME from IP` just before the matching failed password "
|
| 184 |
-
"line. That line is a notice, not a separate attempt.\n")
|
| 185 |
-
if level == 3:
|
| 186 |
-
readme += ("\nWhen sshd repeats an identical message, syslog writes `message repeated N times: [ ... ]` "
|
| 187 |
-
"instead. That line stands for N more failed attempts at that line's time.\n")
|
| 188 |
-
files["README.md"] = readme
|
| 189 |
-
opener = rng.choice([
|
| 190 |
-
"You are on call for the company's SSH bastion host and need to stop a password-guessing attack.",
|
| 191 |
-
"A bastion host is being hit by SSH password guessing, and you have been asked to decide which sources to block.",
|
| 192 |
-
])
|
| 193 |
-
notes = " Notes from the security team are in /root/README.md." if level >= 2 else ""
|
| 194 |
-
instruction = (
|
| 195 |
-
f"{opener} {where} Each line starts with the time as HH:MM:SS, for example "
|
| 196 |
-
f"`00:14:07 Failed password for root from 45.9.2.18`.{notes}\n\n"
|
| 197 |
-
"A failed attempt is a `Failed password for USER from IP` line, including `Failed password for invalid user "
|
| 198 |
-
"USER from IP`. Accepted logins, disconnects and other messages are not attempts.\n\n"
|
| 199 |
-
f"Block a source IP when it has at least {k} failed attempts within {w} minutes: some {k} of its failures, "
|
| 200 |
-
f"where the last is no more than {span} seconds after the first. Failures spread over a longer time do not count "
|
| 201 |
-
"together.\n\n"
|
| 202 |
-
"Write /root/blocked.txt with each blocked IP once, one per line, in any order, and nothing else."
|
| 203 |
-
)
|
| 204 |
-
return Built(
|
| 205 |
-
instruction=instruction,
|
| 206 |
-
files=files,
|
| 207 |
-
artifact=Artifact(path="blocked.txt", kind="checks", parse="lines", checks=_ip_checks(want),
|
| 208 |
-
render=lambda: "".join(f"{ip}\n" for ip in sorted(want))),
|
| 209 |
-
root=ROOT,
|
| 210 |
-
notes={"blocked": sorted(want), "k": k, "window_s": span},
|
| 211 |
-
)
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
# ---------------------------------------------------------------- sec3_fw_verdicts
|
| 215 |
-
|
| 216 |
-
FW_NETS = ["10.0.0.0/8", "10.20.0.0/16", "10.20.5.0/24", "192.168.0.0/16", "192.168.10.0/24", "172.16.0.0/12",
|
| 217 |
-
"203.0.113.0/24", "any"]
|
| 218 |
-
FW_PORTS = [22, 25, 53, 80, 443, 3306, 5432, 6379, 8080, 8443]
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
def _fw_ports(rng: random.Random) -> tuple[str, set | None]:
|
| 222 |
-
r = rng.random()
|
| 223 |
-
if r < 0.4:
|
| 224 |
-
p = rng.choice(FW_PORTS)
|
| 225 |
-
return str(p), {p}
|
| 226 |
-
if r < 0.65:
|
| 227 |
-
ps = sorted(rng.sample(FW_PORTS, rng.randint(2, 3)))
|
| 228 |
-
return ";".join(map(str, ps)), set(ps)
|
| 229 |
-
if r < 0.88:
|
| 230 |
-
lo = rng.choice([1000, 3000, 5400, 8000])
|
| 231 |
-
hi = lo + rng.choice([99, 999])
|
| 232 |
-
return f"{lo}-{hi}", set(range(lo, hi + 1))
|
| 233 |
-
return "any", None
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
def _fw_src(rng: random.Random, nets: list[str]) -> str:
|
| 237 |
-
net = ipaddress.ip_network(rng.choice(nets))
|
| 238 |
-
if rng.random() < 0.35: # from anywhere
|
| 239 |
-
return rng.choice([f"10.{rng.randint(0, 40)}.{rng.randint(0, 20)}.{rng.randint(1, 254)}",
|
| 240 |
-
f"192.168.{rng.choice([10, 11, rng.randint(0, 40)])}.{rng.randint(1, 254)}",
|
| 241 |
-
f"172.{rng.randint(12, 34)}.{rng.randint(0, 20)}.{rng.randint(1, 254)}",
|
| 242 |
-
f"203.0.113.{rng.randint(1, 254)}", f"198.51.100.{rng.randint(1, 254)}"])
|
| 243 |
-
return str(net.network_address + rng.randint(1, net.num_addresses - 2))
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
def build_fw(level: int, rng: random.Random) -> Built:
|
| 247 |
-
n_rules, n_conn = {1: 5, 2: 8, 3: 11}[level], {1: 120, 2: 220, 3: 360}[level]
|
| 248 |
-
protos = ["tcp", "tcp", "udp", "any"] + (["icmp"] if level >= 2 else [])
|
| 249 |
-
groups = {}
|
| 250 |
-
if level == 3:
|
| 251 |
-
groups = {"office": sorted(rng.sample(["10.20.5.0/24", "10.20.6.0/24", "10.20.9.0/24"], 2)),
|
| 252 |
-
"vpn": [rng.choice(["172.16.8.0/22", "172.20.0.0/16"])],
|
| 253 |
-
"partners": sorted(rng.sample(["203.0.113.0/25", "198.51.100.0/24", "192.168.10.0/24"], 2))}
|
| 254 |
-
while True:
|
| 255 |
-
nums = sorted(rng.sample(range(100, 1000, 10), n_rules))
|
| 256 |
-
rules = [] # (no, action, proto, src_text, nets or None, port_text, ports or None, enabled)
|
| 257 |
-
for no in nums:
|
| 258 |
-
proto = rng.choice(protos)
|
| 259 |
-
if level == 3 and rng.random() < 0.3:
|
| 260 |
-
g = rng.choice(sorted(groups))
|
| 261 |
-
src_text, nets = f"@{g}", groups[g]
|
| 262 |
-
else:
|
| 263 |
-
src_text = rng.choice(FW_NETS if level >= 2 else ["10.0.0.0/8", "192.168.0.0/16", "172.16.0.0/12", "any"])
|
| 264 |
-
nets = None if src_text == "any" else [src_text]
|
| 265 |
-
ptext, ports = ("any", None) if proto == "icmp" else _fw_ports(rng)
|
| 266 |
-
enabled = not (level == 3 and rng.random() < 0.2)
|
| 267 |
-
rules.append((no, rng.choice(["allow", "allow", "deny"]), proto, src_text, nets, ptext, ports, enabled))
|
| 268 |
-
src_pool = [n for r in rules if r[4] for n in r[4]]
|
| 269 |
-
if not src_pool: # every rule says src=any: draw a new table
|
| 270 |
-
continue
|
| 271 |
-
ends = [int(x) for r in rules if "-" in r[5] for x in r[5].split("-")]
|
| 272 |
-
conns = []
|
| 273 |
-
for i in range(n_conn):
|
| 274 |
-
proto = rng.choice(["tcp", "tcp", "tcp", "udp"] + (["icmp"] if level >= 2 else []))
|
| 275 |
-
port = "" if proto == "icmp" else str(rng.choice(FW_PORTS + [1080, 3100, 5432, 8050, 1234, 5500, 9000] + ends * 2))
|
| 276 |
-
conns.append((f"c{i + 1:04d}", _fw_src(rng, src_pool), proto, port))
|
| 277 |
-
|
| 278 |
-
def decide(rule_list):
|
| 279 |
-
out = []
|
| 280 |
-
for cid, src, proto, port in conns:
|
| 281 |
-
hit = 0
|
| 282 |
-
for no, action, rproto, _, nets, _, ports, enabled in rule_list:
|
| 283 |
-
if not enabled or rproto not in ("any", proto):
|
| 284 |
-
continue
|
| 285 |
-
if nets is not None and not _in_any(src, nets):
|
| 286 |
-
continue
|
| 287 |
-
if ports is not None and (port == "" or int(port) not in ports):
|
| 288 |
-
continue
|
| 289 |
-
hit = no
|
| 290 |
-
break
|
| 291 |
-
verdict = next(r[1] for r in rule_list if r[0] == hit) if hit else "deny"
|
| 292 |
-
out.append((cid, verdict, hit))
|
| 293 |
-
return out
|
| 294 |
-
|
| 295 |
-
rows = decide(rules)
|
| 296 |
-
deciders = {r[2] for r in rows}
|
| 297 |
-
allowed = sum(r[1] == "allow" for r in rows)
|
| 298 |
-
ok = 0 in deciders and len(deciders - {0}) >= (n_rules + 1) // 2 and 0.15 * n_conn < allowed < 0.85 * n_conn
|
| 299 |
-
# a range's upper end is included: reading it as exclusive must change the answer
|
| 300 |
-
excl = [r[:6] + ((r[6] - {max(r[6])}) if "-" in r[5] else r[6], r[7]) for r in rules]
|
| 301 |
-
ok = ok and decide(excl) != rows
|
| 302 |
-
file_order = rules[:]
|
| 303 |
-
if level >= 2:
|
| 304 |
-
rng.shuffle(file_order)
|
| 305 |
-
ok = ok and decide(file_order) != rows and any(c[2] == "icmp" and r[2] for c, r in zip(conns, rows))
|
| 306 |
-
if level == 3:
|
| 307 |
-
loaded = [r[:7] + (True,) for r in rules]
|
| 308 |
-
ok = ok and decide(loaded) != rows and any(r[3].startswith("@") and r[0] in deciders for r in rules)
|
| 309 |
-
if ok:
|
| 310 |
-
break
|
| 311 |
-
head = "rule_no,action,proto,src,ports" + (",enabled" if level == 3 else "")
|
| 312 |
-
body = "".join(f"{no},{a},{p},{s},{pt}" + ((",yes" if en else ",no") if level == 3 else "") + "\n"
|
| 313 |
-
for no, a, p, s, _, pt, _, en in file_order)
|
| 314 |
-
files = {"rules.csv": f"{head}\n{body}",
|
| 315 |
-
"connections.csv": "id,src_ip,proto,dst_port\n" + "".join(f"{c},{s},{p},{d}\n" for c, s, p, d in conns)}
|
| 316 |
-
if level >= 2:
|
| 317 |
-
readme = ("# Rule export notes\n\nICMP connections have no port, so their dst_port is empty. An ICMP "
|
| 318 |
-
"connection matches a rule only when the rule's proto is icmp or any and its ports is any.\n")
|
| 319 |
-
if level == 3:
|
| 320 |
-
readme += ("\nRules with enabled=no are kept for reference and are not loaded. A src that starts with `@` "
|
| 321 |
-
"names an address group in /root/groups.txt: the source matches when it lies inside any of "
|
| 322 |
-
"the group's networks.\n")
|
| 323 |
-
files["groups.txt"] = "# address groups, used in rules.csv as @name\n" + "".join(
|
| 324 |
-
f"{g}: {' '.join(n)}\n" for g, n in groups.items())
|
| 325 |
-
files["README.md"] = readme
|
| 326 |
-
opener = rng.choice([
|
| 327 |
-
"You are reviewing a perimeter firewall change before it goes live.",
|
| 328 |
-
"The network team wants to know what a proposed firewall rule table would have done to yesterday's traffic.",
|
| 329 |
-
])
|
| 330 |
-
notes = " Export notes are in /root/README.md." if level >= 2 else ""
|
| 331 |
-
instruction = (
|
| 332 |
-
f"{opener} The rule table is /root/rules.csv with the columns rule_no, action (allow or deny), proto, src "
|
| 333 |
-
"(a CIDR network or any) and ports (one port, ports joined by `;`, a range such as `8000-8099`, or any). "
|
| 334 |
-
f"The connection attempts are in /root/connections.csv with the columns id, src_ip, proto and dst_port.{notes}\n\n"
|
| 335 |
-
"A rule matches a connection when its proto equals the connection's or is any, the source IP lies inside "
|
| 336 |
-
"its src network or src is any, and dst_port is one of its ports or inside its range (both ends included) "
|
| 337 |
-
"or ports is any. Rules are checked in ascending rule_no and the first match decides. A connection that no "
|
| 338 |
-
"rule matches is denied by the default rule, numbered 0.\n\n"
|
| 339 |
-
"Write /root/verdicts.csv with the header id,verdict,rule and one row per connection in input order, "
|
| 340 |
-
"for example `c0007,allow,120`."
|
| 341 |
-
)
|
| 342 |
-
want = rows
|
| 343 |
-
|
| 344 |
-
def ids_in_order(p):
|
| 345 |
-
return [r["id"] for r in p["rows"]] == [r[0] for r in want]
|
| 346 |
-
|
| 347 |
-
return Built(
|
| 348 |
-
instruction=instruction,
|
| 349 |
-
files=files,
|
| 350 |
-
artifact=Artifact(
|
| 351 |
-
path="verdicts.csv", kind="checks", parse="csv",
|
| 352 |
-
checks=[
|
| 353 |
-
("test_header", lambda p: p["header"] == ["id", "verdict", "rule"]),
|
| 354 |
-
("test_row_count", lambda p: len(p["rows"]) == len(want)),
|
| 355 |
-
("test_ids_in_order", ids_in_order),
|
| 356 |
-
("test_verdicts", lambda p: [r["verdict"] for r in p["rows"]] == [r[1] for r in want]),
|
| 357 |
-
("test_rule_numbers", lambda p: [int(r["rule"]) for r in p["rows"]] == [r[2] for r in want]),
|
| 358 |
-
],
|
| 359 |
-
render=lambda: "id,verdict,rule\n" + "".join(f"{c},{v},{n}\n" for c, v, n in want),
|
| 360 |
-
),
|
| 361 |
-
root=ROOT,
|
| 362 |
-
notes={"allowed": sum(r[1] == "allow" for r in want), "default_deny": sum(r[2] == 0 for r in want)},
|
| 363 |
-
)
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
# ---------------------------------------------------------------- sec3_exfil_flows
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
def _hm(minute: int) -> str:
|
| 370 |
-
return f"{minute // 60:02d}:{minute % 60:02d}"
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
def build_exfil(level: int, rng: random.Random) -> Built:
|
| 374 |
-
n_flows = {1: 130, 2: 250, 3: 380}[level]
|
| 375 |
-
threshold = rng.choice([200, 250, 300, 400, 500])
|
| 376 |
-
start_h, end_h = rng.choice([(8, 18), (7, 19), (9, 17), (8, 17)])
|
| 377 |
-
bdays = list(DAYS[:5]) if rng.random() < 0.8 else list(DAYS[:6])
|
| 378 |
-
offset = rng.choice([-5, -4, 1, 2]) if level == 3 else 0
|
| 379 |
-
internal = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]
|
| 380 |
-
while True:
|
| 381 |
-
used: set = set()
|
| 382 |
-
cloud = [_public_ip(rng, used) for _ in range(rng.randint(14, 22))]
|
| 383 |
-
if level == 1:
|
| 384 |
-
allowlist = rng.sample(cloud, 5)
|
| 385 |
-
allowed_ips = set(allowlist)
|
| 386 |
-
else:
|
| 387 |
-
nets = rng.sample(["52.94.0.0/16", "13.107.6.0/24", "140.82.112.0/20", "151.101.0.0/16"], 3)
|
| 388 |
-
singles = rng.sample(cloud, 3)
|
| 389 |
-
allowlist = sorted(nets) + singles
|
| 390 |
-
for n in nets: # remote hosts inside the approved networks
|
| 391 |
-
net = ipaddress.ip_network(n)
|
| 392 |
-
cloud.append(str(net.network_address + rng.randint(1, min(net.num_addresses - 2, 4000))))
|
| 393 |
-
cloud.append(str(net.network_address + rng.randint(1, min(net.num_addresses - 2, 4000))))
|
| 394 |
-
# just outside an approved network: not approved
|
| 395 |
-
cloud.append(str(ipaddress.ip_network(nets[0]).broadcast_address + rng.randint(2, 200)))
|
| 396 |
-
allowed_ips = set(singles)
|
| 397 |
-
|
| 398 |
-
def approved(ip):
|
| 399 |
-
return ip in allowed_ips or (level >= 2 and _in_any(ip, allowlist))
|
| 400 |
-
|
| 401 |
-
flows = [] # (local day index, local minute, dst, mb)
|
| 402 |
-
for _ in range(n_flows):
|
| 403 |
-
day = rng.randrange(7)
|
| 404 |
-
minute = rng.randint(start_h * 60, end_h * 60 - 1) if rng.random() < 0.65 else rng.randrange(1440)
|
| 405 |
-
dst = rng.choice(cloud)
|
| 406 |
-
if level >= 2 and rng.random() < 0.12:
|
| 407 |
-
dst = f"10.{rng.randint(0, 9)}.{rng.randint(0, 20)}.{rng.randint(2, 254)}"
|
| 408 |
-
r = rng.random()
|
| 409 |
-
mb = rng.randint(threshold + 1, threshold * 4) if r < 0.12 else rng.randint(0, int(threshold * 0.8))
|
| 410 |
-
flows.append([day, minute, dst, mb])
|
| 411 |
-
# boundary rows: exactly the threshold off hours (not flagged), starting at closing time (flagged),
|
| 412 |
-
# starting at opening time (not flagged)
|
| 413 |
-
plain = [c for c in cloud if not approved(c)]
|
| 414 |
-
flows += [[rng.randrange(5), start_h * 60 - rng.randint(1, 30), rng.choice(plain), threshold],
|
| 415 |
-
[rng.randrange(5), end_h * 60, rng.choice(plain), threshold + rng.randint(1, 40)],
|
| 416 |
-
[rng.randrange(5), start_h * 60, rng.choice(plain), threshold + rng.randint(1, 40)]]
|
| 417 |
-
|
| 418 |
-
def off_hours(day, minute):
|
| 419 |
-
return DAYS[day % 7] not in bdays or not (start_h * 60 <= minute < end_h * 60)
|
| 420 |
-
|
| 421 |
-
def flagged(f, clock=None, internal_rule=True, cidr=True):
|
| 422 |
-
day, minute, dst, mb = f
|
| 423 |
-
if clock is not None:
|
| 424 |
-
day, minute = clock // 1440, clock % 1440
|
| 425 |
-
ok_dst = dst in allowed_ips or (level >= 2 and cidr and _in_any(dst, allowlist))
|
| 426 |
-
inside = level >= 2 and internal_rule and _in_any(dst, internal)
|
| 427 |
-
return mb > threshold and not ok_dst and not inside and off_hours(day, minute)
|
| 428 |
-
|
| 429 |
-
# display time: local for L1-L2, UTC for L3 (local = utc + offset)
|
| 430 |
-
shown = []
|
| 431 |
-
for f in flows:
|
| 432 |
-
utc = (f[0] * 1440 + f[1] - offset * 60) % (7 * 1440)
|
| 433 |
-
shown.append((utc, f))
|
| 434 |
-
shown.sort(key=lambda x: x[0])
|
| 435 |
-
fid, rows, want = rng.randint(100, 199), [], []
|
| 436 |
-
for utc, f in shown:
|
| 437 |
-
fid += rng.randint(1, 3)
|
| 438 |
-
rows.append(f"{fid},{DAYS[utc // 1440]},{_hm(utc % 1440)},{f[2]},{f[3]}")
|
| 439 |
-
if flagged(f):
|
| 440 |
-
want.append(fid)
|
| 441 |
-
big_off = [f for f in flows if f[3] > threshold and not flagged(f)]
|
| 442 |
-
ok = 4 <= len(want) <= 14 and len(big_off) >= 4
|
| 443 |
-
if level >= 2: # ignoring the internal networks or the CIDR entries must change the answer
|
| 444 |
-
ok = ok and any(flagged(f, internal_rule=False) != flagged(f) for f in flows)
|
| 445 |
-
ok = ok and any(flagged(f, cidr=False) != flagged(f) for f in flows)
|
| 446 |
-
if level == 3: # judging on the UTC clock must change the answer
|
| 447 |
-
ok = ok and sum(flagged(f, clock=utc) != flagged(f) for utc, f in shown) >= 2
|
| 448 |
-
if ok:
|
| 449 |
-
break
|
| 450 |
-
policy = {"threshold_mb": threshold, "business_days": bdays,
|
| 451 |
-
"business_hours": [f"{start_h:02d}:00", f"{end_h:02d}:00"]}
|
| 452 |
-
if level >= 2:
|
| 453 |
-
policy["internal_networks"] = internal
|
| 454 |
-
if level == 3:
|
| 455 |
-
policy["office_utc_offset_hours"] = offset
|
| 456 |
-
else:
|
| 457 |
-
policy["allowlist"] = allowlist
|
| 458 |
-
files = {"flows.csv": "flow,day,time,dst,mb_out\n" + "\n".join(rows) + "\n",
|
| 459 |
-
"policy.json": json.dumps(policy, indent=2) + "\n"}
|
| 460 |
-
if level == 1:
|
| 461 |
-
policy_text = "threshold_mb, business_days, business_hours as [start, end] and allowlist, the approved remote addresses"
|
| 462 |
-
elif level == 2:
|
| 463 |
-
policy_text = ("threshold_mb, business_days, business_hours as [start, end] and allowlist, the approved remote "
|
| 464 |
-
"destinations (addresses or CIDR networks)")
|
| 465 |
-
else:
|
| 466 |
-
files["allowlist.txt"] = "# approved remote destinations, one address or CIDR network per line\n" + "".join(
|
| 467 |
-
f"{a}\n" for a in allowlist)
|
| 468 |
-
policy_text = ("threshold_mb, business_days and business_hours as [start, end]; the approved remote destinations "
|
| 469 |
-
"are in /root/allowlist.txt, one address or CIDR network per line")
|
| 470 |
-
if level >= 2:
|
| 471 |
-
readme = ("# Collector notes\n\nThe collector also records traffic between internal machines. A flow whose dst "
|
| 472 |
-
"is inside one of policy.json's internal_networks is not outbound and never alerts.\n")
|
| 473 |
-
if level == 3:
|
| 474 |
-
readme += ("\nThe collector writes day and time in UTC. Business days and hours in policy.json are office "
|
| 475 |
-
"local time, which is UTC plus office_utc_offset_hours; convert before checking, which can "
|
| 476 |
-
"change the day.\n")
|
| 477 |
-
files["README.md"] = readme
|
| 478 |
-
opener = rng.choice([
|
| 479 |
-
"You are hunting for data exfiltration in last week's outbound traffic from an office network.",
|
| 480 |
-
"Security suspects that someone copied data out of the office network after hours last week.",
|
| 481 |
-
])
|
| 482 |
-
notes = " Collector notes are in /root/README.md." if level >= 2 else ""
|
| 483 |
-
instruction = (
|
| 484 |
-
f"{opener} The flow summary is /root/flows.csv with the columns flow (an integer id), day (Mon to Sun), time "
|
| 485 |
-
"(HH:MM, when the flow started), dst (the remote IP) and mb_out (whole megabytes sent). The policy file "
|
| 486 |
-
f"/root/policy.json gives {policy_text}.{notes}\n\n"
|
| 487 |
-
"Flag a flow when all three hold:\n"
|
| 488 |
-
"1. mb_out is greater than threshold_mb; equal is not flagged.\n"
|
| 489 |
-
"2. dst is not an approved destination.\n"
|
| 490 |
-
"3. It started outside business hours: on a day not in business_days, or before start, or at or after end.\n\n"
|
| 491 |
-
"Write the flagged flow ids to /root/alerts.json as a JSON array of integers sorted ascending, for example "
|
| 492 |
-
"`[104, 187, 203]`."
|
| 493 |
-
)
|
| 494 |
-
|
| 495 |
-
def is_int_list(p):
|
| 496 |
-
return isinstance(p, list) and all(isinstance(x, int) and not isinstance(x, bool) for x in p)
|
| 497 |
-
|
| 498 |
-
want_set = set(want)
|
| 499 |
-
return Built(
|
| 500 |
-
instruction=instruction,
|
| 501 |
-
files=files,
|
| 502 |
-
artifact=Artifact(
|
| 503 |
-
path="alerts.json", kind="checks", parse="json",
|
| 504 |
-
checks=[
|
| 505 |
-
("test_is_int_list", is_int_list),
|
| 506 |
-
("test_sorted_unique", lambda p: p == sorted(set(p))),
|
| 507 |
-
("test_no_false_positives", lambda p: set(p) <= want_set),
|
| 508 |
-
("test_no_missed_alerts", lambda p: want_set <= set(p)),
|
| 509 |
-
],
|
| 510 |
-
render=lambda: json.dumps(want) + "\n",
|
| 511 |
-
),
|
| 512 |
-
root=ROOT,
|
| 513 |
-
notes={"alerts": want, "threshold_mb": threshold},
|
| 514 |
-
)
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
FAMILIES = [
|
| 518 |
-
Family("sec3_auth_triage", "cybersecurity", "Block SSH brute-force sources", build_auth, v3=True),
|
| 519 |
-
Family("sec3_fw_verdicts", "cybersecurity", "Evaluate an ordered firewall rule table", build_fw, v3=True),
|
| 520 |
-
Family("sec3_exfil_flows", "cybersecurity", "Flag off-hours exfiltration flows", build_exfil, v3=True),
|
| 521 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/families/software3.py
DELETED
|
@@ -1,665 +0,0 @@
|
|
| 1 |
-
"""Software engineering v3: repair a module against hidden tests, replay a token-bucket limiter,
|
| 2 |
-
resolve a lock file against a package index. All three are stdlib-only."""
|
| 3 |
-
|
| 4 |
-
import datetime
|
| 5 |
-
import itertools
|
| 6 |
-
import json
|
| 7 |
-
import os
|
| 8 |
-
import random
|
| 9 |
-
import shutil
|
| 10 |
-
import tempfile
|
| 11 |
-
|
| 12 |
-
from ..core import shell
|
| 13 |
-
from .base import Artifact, Built, Family
|
| 14 |
-
from .software import FUNCS, _compile, _jsonable, _same
|
| 15 |
-
|
| 16 |
-
# ---------------------------------------------------------------- sw3_rate_limit
|
| 17 |
-
|
| 18 |
-
RL_OPENERS = (
|
| 19 |
-
"Our gateway's token-bucket limiter rejected the wrong requests during last night's incident.",
|
| 20 |
-
"A customer says our gateway's rate limiter dropped requests it should have served.",
|
| 21 |
-
"Nobody trusts the rejection log of our gateway's token-bucket limiter after an incident.",
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
def _rl_tiers(rng: random.Random) -> dict:
|
| 26 |
-
return {
|
| 27 |
-
"free": {"capacity": rng.randint(5, 12), "refill_per_sec": round(rng.uniform(0.4, 1.2), 1)},
|
| 28 |
-
"pro": {"capacity": rng.randint(15, 30), "refill_per_sec": round(rng.uniform(1.0, 2.5), 1)},
|
| 29 |
-
"batch": {"capacity": rng.randint(30, 60), "refill_per_sec": round(rng.uniform(0.3, 0.9), 1)},
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def _rl_replay(reqs, tiers, key_tier, default, exempt, change, *, file_order=False, ignore_exempt=False,
|
| 34 |
-
ignore_change=False, charge_rejects=False, whole_seconds=False, unit_cost=False):
|
| 35 |
-
"""Rejected ids, and the smallest |tokens - cost| over decisions whose token count is inexact (and
|
| 36 |
-
|refilled - capacity| over refills), so float evaluation order cannot flip a decision.
|
| 37 |
-
Keyword flags replay the common mistakes so the generator can insist each one changes the answer."""
|
| 38 |
-
order = list(reqs) if file_order else sorted(reqs, key=lambda r: (r["ms"], r["id"]))
|
| 39 |
-
buckets, rejected, margin = {}, [], float("inf")
|
| 40 |
-
for r in order:
|
| 41 |
-
key = r["key"]
|
| 42 |
-
if key in exempt and not ignore_exempt:
|
| 43 |
-
continue
|
| 44 |
-
tier = key_tier.get(key, default)
|
| 45 |
-
cap, rate = tiers[tier]["capacity"], tiers[tier]["refill_per_sec"]
|
| 46 |
-
if change and not ignore_change and tier == change["tier"] and r["ms"] >= change["ms"]:
|
| 47 |
-
cap, rate = change["capacity"], change["refill_per_sec"]
|
| 48 |
-
ts = r["ms"] / 1000
|
| 49 |
-
if key not in buckets:
|
| 50 |
-
tokens, exact = float(cap), True
|
| 51 |
-
else:
|
| 52 |
-
tokens, last, exact = buckets[key]
|
| 53 |
-
gap = ts - last
|
| 54 |
-
if whole_seconds:
|
| 55 |
-
gap = float(int(gap))
|
| 56 |
-
refilled = tokens + gap * rate
|
| 57 |
-
if gap != 0: # a refill that lands within float noise of capacity could clip either way
|
| 58 |
-
margin = min(margin, abs(refilled - cap))
|
| 59 |
-
if refilled >= cap:
|
| 60 |
-
tokens, exact = float(cap), True
|
| 61 |
-
elif gap != 0:
|
| 62 |
-
tokens, exact = refilled, False
|
| 63 |
-
cost = 1 if unit_cost else r["cost"]
|
| 64 |
-
if not exact:
|
| 65 |
-
margin = min(margin, abs(tokens - cost))
|
| 66 |
-
if tokens >= cost:
|
| 67 |
-
tokens -= cost
|
| 68 |
-
else:
|
| 69 |
-
rejected.append(r["id"])
|
| 70 |
-
if charge_rejects:
|
| 71 |
-
tokens = max(0.0, tokens - cost)
|
| 72 |
-
buckets[key] = (tokens, ts, exact)
|
| 73 |
-
return sorted(rejected), margin
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
def build_rate_limit(level: int, rng: random.Random) -> Built:
|
| 77 |
-
n_req = {1: (400, 550), 2: (600, 800), 3: (700, 900)}[level]
|
| 78 |
-
n_keys = {1: (6, 8), 2: (8, 10), 3: (9, 11)}[level]
|
| 79 |
-
while True:
|
| 80 |
-
keys = sorted({f"k-{rng.randrange(16 ** 4):04x}" for _ in range(rng.randint(*n_keys))})
|
| 81 |
-
hot = rng.sample(keys, 4)
|
| 82 |
-
weights = [rng.uniform(4, 7) if k in hot else rng.uniform(0.3, 1.0) for k in keys]
|
| 83 |
-
tiers = _rl_tiers(rng)
|
| 84 |
-
key_tier = {k: rng.choice(sorted(tiers)) for k in keys}
|
| 85 |
-
default, exempt, change = "free", set(), None
|
| 86 |
-
if level >= 2:
|
| 87 |
-
unmapped = rng.sample([k for k in keys if k not in hot[:1]], 2)
|
| 88 |
-
for k in unmapped:
|
| 89 |
-
del key_tier[k]
|
| 90 |
-
default = rng.choice(sorted(tiers))
|
| 91 |
-
exempt = {hot[0]} | ({rng.choice([k for k in keys if k not in hot])} if rng.random() < 0.5 else set())
|
| 92 |
-
base, ms, reqs = rng.randint(100000, 899999), 0, []
|
| 93 |
-
rate = rng.uniform(4.0, 6.0)
|
| 94 |
-
for i in range(rng.randint(*n_req)):
|
| 95 |
-
ms += max(1, int(rng.expovariate(rate) * 1000))
|
| 96 |
-
key = rng.choices(keys, weights)[0]
|
| 97 |
-
reqs.append({"id": base + i, "ms": ms, "key": key, "cost": rng.choice((1, 1, 1, 2, 3, 5))})
|
| 98 |
-
if level >= 3:
|
| 99 |
-
tier = key_tier.get(hot[1], default)
|
| 100 |
-
old = tiers[tier]
|
| 101 |
-
change = {"tier": tier, "ms": reqs[len(reqs) // 2 + rng.randint(-60, 60)]["ms"],
|
| 102 |
-
"capacity": max(5, old["capacity"] + rng.choice((-1, 1)) * rng.randint(3, 8)),
|
| 103 |
-
"refill_per_sec": round(max(0.3, old["refill_per_sec"] * rng.uniform(0.4, 0.7)), 1)}
|
| 104 |
-
file_reqs = list(reqs)
|
| 105 |
-
if level >= 2: # gateway arrival order: some same-key pairs land out of ts order
|
| 106 |
-
i = rng.randint(5, 15)
|
| 107 |
-
while i < len(file_reqs) - 6:
|
| 108 |
-
j = next((j for j in range(i + 1, i + 6) if file_reqs[j]["key"] == file_reqs[i]["key"]), None)
|
| 109 |
-
if j is not None:
|
| 110 |
-
file_reqs[i], file_reqs[j] = file_reqs[j], file_reqs[i]
|
| 111 |
-
i += rng.randint(25, 40)
|
| 112 |
-
args = (file_reqs, tiers, key_tier, default, exempt, change)
|
| 113 |
-
want, margin = _rl_replay(*args)
|
| 114 |
-
if margin < 1e-4 or not 0.05 <= len(want) / len(reqs) <= 0.30:
|
| 115 |
-
continue
|
| 116 |
-
traps = [dict(charge_rejects=True), dict(whole_seconds=True), dict(unit_cost=True)]
|
| 117 |
-
if level >= 2:
|
| 118 |
-
traps += [dict(file_order=True), dict(ignore_exempt=True)]
|
| 119 |
-
if level >= 3:
|
| 120 |
-
traps.append(dict(ignore_change=True))
|
| 121 |
-
if all(_rl_replay(*args, **t)[0] != want for t in traps):
|
| 122 |
-
break
|
| 123 |
-
exempt_ids = {r["id"] for r in reqs if r["key"] in exempt}
|
| 124 |
-
example = sorted(rng.sample([r["id"] for r in reqs if r["id"] not in set(want)], 2))
|
| 125 |
-
csv_lines = ["id,ts,key,cost"] + [f"{r['id']},{r['ms'] / 1000:.3f},{r['key']},{r['cost']}" for r in file_reqs]
|
| 126 |
-
limits = {"tiers": tiers, "keys": dict(sorted(key_tier.items()))}
|
| 127 |
-
if level >= 2:
|
| 128 |
-
limits["default_tier"] = default
|
| 129 |
-
limits["exempt_keys"] = sorted(exempt)
|
| 130 |
-
files = {"requests.csv": "\n".join(csv_lines) + "\n", "limits.json": json.dumps(limits, indent=2) + "\n"}
|
| 131 |
-
inputs = ("- /root/requests.csv: id, ts (seconds, millisecond precision), key and cost (tokens needed) for "
|
| 132 |
-
"each request.\n- /root/limits.json: the tiers (capacity, refill_per_sec) and the key-to-tier map.")
|
| 133 |
-
rules = ["Each key has its own bucket, full (its tier's capacity) at the key's first request."]
|
| 134 |
-
if level == 1:
|
| 135 |
-
inputs += "\n"
|
| 136 |
-
rules.append("Process requests in ts order.")
|
| 137 |
-
else:
|
| 138 |
-
inputs += " Unmapped keys use default_tier; exempt_keys are never limited.\n"
|
| 139 |
-
rules.append("Process requests in ts order, ties by id (the file is not always in ts order).")
|
| 140 |
-
if level >= 3:
|
| 141 |
-
inputs += "- /root/CHANGE_NOTICE.md: a tier change made mid-capture.\n"
|
| 142 |
-
t = change["ms"] / 1000
|
| 143 |
-
files["CHANGE_NOTICE.md"] = (
|
| 144 |
-
"# Limiter config change\n\n"
|
| 145 |
-
f"From ts {t:.3f} onward the {change['tier']} tier is capacity {change['capacity']}, refill_per_sec "
|
| 146 |
-
f"{change['refill_per_sec']}. Requests before that time use the old values. Refill for a gap that spans "
|
| 147 |
-
"the change uses the new rate, and stored tokens above the new capacity are clipped the next time the "
|
| 148 |
-
"key is seen.\n"
|
| 149 |
-
)
|
| 150 |
-
rules += [
|
| 151 |
-
"Before each request, refill: tokens = min(capacity, tokens + seconds since the key's previous request "
|
| 152 |
-
"x refill_per_sec).",
|
| 153 |
-
"If tokens >= cost, accept and subtract cost; otherwise reject without consuming anything.",
|
| 154 |
-
]
|
| 155 |
-
instruction = (
|
| 156 |
-
rng.choice(RL_OPENERS) + " Replay the traffic and find which requests should have been rejected.\n\n"
|
| 157 |
-
"Inputs:\n" + inputs + "\nRules:\n" + "".join(f"{i}. {r}\n" for i, r in enumerate(rules, 1))
|
| 158 |
-
+ "\nWrite /root/rejected.json: the rejected ids as a JSON array of integers, sorted ascending, "
|
| 159 |
-
f"e.g. [{example[0]}, {example[1]}]."
|
| 160 |
-
)
|
| 161 |
-
want_set = set(want)
|
| 162 |
-
checks = [
|
| 163 |
-
("test_is_list", lambda p: isinstance(p, list)),
|
| 164 |
-
("test_items_are_ints", lambda p: all(type(x) is int for x in p)),
|
| 165 |
-
("test_sorted_unique", lambda p: all(a < b for a, b in zip(p, p[1:]))),
|
| 166 |
-
]
|
| 167 |
-
if exempt_ids:
|
| 168 |
-
checks.append(("test_no_exempt_ids", lambda p: not exempt_ids & set(p)))
|
| 169 |
-
checks += [
|
| 170 |
-
("test_rejected_count", lambda p: len(p) == len(want)),
|
| 171 |
-
("test_rejected_ids", lambda p: p == want and set(p) == want_set),
|
| 172 |
-
]
|
| 173 |
-
return Built(
|
| 174 |
-
instruction=instruction,
|
| 175 |
-
files=files,
|
| 176 |
-
artifact=Artifact(path="rejected.json", kind="checks", parse="json", checks=checks,
|
| 177 |
-
render=lambda: json.dumps(want) + "\n"),
|
| 178 |
-
notes={"rejected": len(want), "requests": len(reqs)},
|
| 179 |
-
root="/root",
|
| 180 |
-
)
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
# ---------------------------------------------------------------- sw3_dep_lock
|
| 184 |
-
|
| 185 |
-
PKG_POOL = (
|
| 186 |
-
"acorn", "alder", "amber", "aspen", "basil", "birch", "bramble", "briar", "cedar", "clover", "cobalt", "coral",
|
| 187 |
-
"cypress", "dahlia", "ember", "fennel", "fern", "flint", "garnet", "ginger", "hazel", "heather", "hemlock",
|
| 188 |
-
"indigo", "iris", "ivy", "jasper", "juniper", "kelp", "larch", "laurel", "lichen", "linden", "maple", "marble",
|
| 189 |
-
"moss", "nettle", "obsidian", "onyx", "opal", "pebble", "quartz", "reed", "rowan", "saffron", "sage", "slate",
|
| 190 |
-
"sorrel", "spruce", "tansy", "thistle", "willow", "yarrow", "zinnia",
|
| 191 |
-
)
|
| 192 |
-
DL_OPENERS = (
|
| 193 |
-
"The lock file for our build went stale when the internal package mirror was refreshed.",
|
| 194 |
-
"Our release pipeline will not build until the lock file is regenerated against the new package index.",
|
| 195 |
-
"A dependency bump broke our build, and the lock file must be regenerated from the package index.",
|
| 196 |
-
)
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
def _vkey(v: str) -> tuple:
|
| 200 |
-
return tuple(int(p) for p in v.split("."))
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
def _dl_versions(rng: random.Random, n: int, wide: bool) -> list[str]:
|
| 204 |
-
"""n ascending major.minor versions with single-digit minors; wide=True forces one jump to a minor of 10+."""
|
| 205 |
-
major, minor, out = rng.randint(0, 3), rng.randint(0, 4), []
|
| 206 |
-
for i in range(n):
|
| 207 |
-
out.append(f"{major}.{minor}")
|
| 208 |
-
if wide and i == n // 2 - 1:
|
| 209 |
-
minor = 10 + rng.randint(0, 3)
|
| 210 |
-
if minor <= int(out[-1].split(".")[1]):
|
| 211 |
-
minor = int(out[-1].split(".")[1]) + 1
|
| 212 |
-
continue
|
| 213 |
-
minor += rng.randint(1, 3)
|
| 214 |
-
if rng.random() < 0.25 or minor > 9: # minors of 10+ come only from the wide jump above
|
| 215 |
-
major, minor = major + 1, 0
|
| 216 |
-
return out
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
def _dl_spec(rng: random.Random, versions: list[str], ne: bool) -> list[tuple]:
|
| 220 |
-
"""A constraint as [(op, version)], never empty over `versions`."""
|
| 221 |
-
while True:
|
| 222 |
-
i, j = sorted(rng.sample(range(len(versions) + 1), 2))
|
| 223 |
-
spec = ([(">=", versions[i])] if i > 0 else []) + ([("<", versions[j])] if j < len(versions) else [])
|
| 224 |
-
if ne and rng.random() < 0.35:
|
| 225 |
-
spec = spec[:1] + [("!=", rng.choice(versions))]
|
| 226 |
-
if spec and any(_dl_ok(v, spec) for v in versions):
|
| 227 |
-
return spec
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
def _dl_ok(v: str, spec, key=_vkey) -> bool:
|
| 231 |
-
ops = {">=": lambda a, b: a >= b, "<": lambda a, b: a < b, "!=": lambda a, b: a != b, "==": lambda a, b: a == b}
|
| 232 |
-
return all(ops[op](key(v), key(w)) for op, w in spec)
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
def _dl_fmt(spec) -> str:
|
| 236 |
-
return ",".join(f"{op}{w}" for op, w in spec)
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
def _dl_solve(pkgs, vers, reqs, top, yanked, key=_vkey, cap=50):
|
| 240 |
-
"""Valid picks (one version per package; counted up to `cap`) and the preferred one: the newest version of
|
| 241 |
-
pkgs[0], then of pkgs[1], ... Depth-first, newest first, so the first complete pick is the preferred one."""
|
| 242 |
-
found = []
|
| 243 |
-
|
| 244 |
-
def fits(pick, p, v):
|
| 245 |
-
if (p, v) in yanked or (p in top and not _dl_ok(v, top[p], key)):
|
| 246 |
-
return False
|
| 247 |
-
mine = reqs[(p, v)]
|
| 248 |
-
return all(not (q in mine and not _dl_ok(w, mine[q], key))
|
| 249 |
-
and not (p in reqs[(q, w)] and not _dl_ok(v, reqs[(q, w)][p], key)) for q, w in pick.items())
|
| 250 |
-
|
| 251 |
-
def walk(i, pick):
|
| 252 |
-
if len(found) >= cap:
|
| 253 |
-
return
|
| 254 |
-
if i == len(pkgs):
|
| 255 |
-
found.append(dict(pick))
|
| 256 |
-
return
|
| 257 |
-
p = pkgs[i]
|
| 258 |
-
for v in sorted(vers[p], key=key, reverse=True):
|
| 259 |
-
if fits(pick, p, v):
|
| 260 |
-
pick[p] = v
|
| 261 |
-
walk(i + 1, pick)
|
| 262 |
-
del pick[p]
|
| 263 |
-
|
| 264 |
-
walk(0, {})
|
| 265 |
-
return found, (found[0] if found else None)
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
def _strkey(v: str) -> tuple:
|
| 269 |
-
return tuple(v.split(".")) # the common mistake: comparing version parts as strings
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
def build_dep_lock(level: int, rng: random.Random) -> Built:
|
| 273 |
-
n_pkg, n_ver, n_noise = {1: (4, (3, 4), 36), 2: (5, (4, 5), 38), 3: (6, (3, 4), 40)}[level]
|
| 274 |
-
dep_p = {1: 0.4, 2: 0.35, 3: 0.3}[level]
|
| 275 |
-
names = rng.sample(PKG_POOL, n_pkg + n_noise)
|
| 276 |
-
pkgs, noise = names[:n_pkg], names[n_pkg:]
|
| 277 |
-
while True: # only the requested packages decide the answer; the mirror's other packages come after
|
| 278 |
-
wide = set(rng.sample(pkgs, 2)) if level >= 2 else set()
|
| 279 |
-
vers = {p: _dl_versions(rng, rng.randint(*n_ver), p in wide) for p in pkgs}
|
| 280 |
-
reqs = {}
|
| 281 |
-
for p in pkgs:
|
| 282 |
-
for v in vers[p]:
|
| 283 |
-
reqs[(p, v)] = {q: _dl_spec(rng, vers[q], level >= 2) for q in pkgs if q != p and rng.random() < dep_p}
|
| 284 |
-
top = {p: _dl_spec(rng, vers[p], False) for p in pkgs if rng.random() < 0.5}
|
| 285 |
-
valid, best = _dl_solve(pkgs, vers, reqs, top, set())
|
| 286 |
-
yanked = set()
|
| 287 |
-
if level >= 3 and best:
|
| 288 |
-
target = rng.choice(pkgs)
|
| 289 |
-
yanked = {(target, best[target])}
|
| 290 |
-
yanked |= {(p, rng.choice(vers[p])) for p in rng.sample(pkgs, 2)}
|
| 291 |
-
valid, best = _dl_solve(pkgs, vers, reqs, top, yanked)
|
| 292 |
-
if not best or len(valid) < 3:
|
| 293 |
-
continue
|
| 294 |
-
newest = {p: max(vers[p], key=_vkey) for p in pkgs}
|
| 295 |
-
if best == newest:
|
| 296 |
-
continue
|
| 297 |
-
if level >= 2 and _dl_solve(pkgs, vers, reqs, top, yanked, key=_strkey)[1] == best:
|
| 298 |
-
continue
|
| 299 |
-
if level >= 3 and _dl_solve(pkgs, vers, reqs, top, set())[1] == best:
|
| 300 |
-
continue
|
| 301 |
-
break
|
| 302 |
-
for p in noise:
|
| 303 |
-
vers[p] = _dl_versions(rng, rng.randint(*n_ver), False)
|
| 304 |
-
for p in noise:
|
| 305 |
-
pool = [q for q in names if q != p]
|
| 306 |
-
for v in vers[p]:
|
| 307 |
-
deps = rng.sample(pool, rng.choice((0, 0, 1, 1, 2)))
|
| 308 |
-
reqs[(p, v)] = {q: _dl_spec(rng, vers[q], level >= 2) for q in deps}
|
| 309 |
-
if level >= 3:
|
| 310 |
-
yanked |= {(p, rng.choice(vers[p])) for p in rng.sample(noise, 2)}
|
| 311 |
-
index = ["# package version requires (';'-separated, '-' for none)"]
|
| 312 |
-
for p in sorted(names):
|
| 313 |
-
for v in vers[p]:
|
| 314 |
-
r = reqs[(p, v)]
|
| 315 |
-
index.append(f"{p} {v} " + (";".join(f"{q}{_dl_fmt(s)}" for q, s in sorted(r.items())) or "-"))
|
| 316 |
-
manifest = [f"{p}{_dl_fmt(top[p])}" if p in top else p for p in pkgs]
|
| 317 |
-
files = {"index.txt": "\n".join(index) + "\n", "requirements.txt": "\n".join(manifest) + "\n"}
|
| 318 |
-
ops = "'>=X' means at least X, '<X' below X"
|
| 319 |
-
if level >= 2:
|
| 320 |
-
ops += ", '!=X' anything but X"
|
| 321 |
-
ops += ", and a comma joins conditions"
|
| 322 |
-
extra = ""
|
| 323 |
-
if level >= 2:
|
| 324 |
-
extra = " Versions compare by major, then minor, as numbers (1.10 is newer than 1.9)."
|
| 325 |
-
if level >= 3:
|
| 326 |
-
files["yanked.txt"] = ("# yanked releases: never install these\n"
|
| 327 |
-
+ "".join(f"{p} {v}\n" for p, v in sorted(yanked)))
|
| 328 |
-
extra += " Never pick a release listed in /root/yanked.txt."
|
| 329 |
-
instruction = (
|
| 330 |
-
rng.choice(DL_OPENERS) + "\n\n"
|
| 331 |
-
"/root/requirements.txt names the packages to install, in priority order, some with a version condition. "
|
| 332 |
-
"/root/index.txt lists every release in the mirror, one per line: package, version, and what it requires. "
|
| 333 |
-
"Most mirror packages are unused; releases of the packages you install only require each other.\n\n"
|
| 334 |
-
"Pick one version of each package in requirements.txt so that its conditions and the requirements of "
|
| 335 |
-
f"every picked release hold ({ops}).{extra} Among all valid picks, take the newest version of the first "
|
| 336 |
-
"package in requirements.txt, then of the second, and so on.\n\n"
|
| 337 |
-
"Write /root/lock.txt with one name==version line per package, sorted by name, for example "
|
| 338 |
-
f"{rng.choice(noise)}==2.4, and nothing else."
|
| 339 |
-
)
|
| 340 |
-
want = [f"{p}=={best[p]}" for p in sorted(pkgs)]
|
| 341 |
-
|
| 342 |
-
def lock(lines):
|
| 343 |
-
return dict(ln.split("==", 1) for ln in lines)
|
| 344 |
-
|
| 345 |
-
def satisfies(lines):
|
| 346 |
-
pick = lock(lines)
|
| 347 |
-
return (all(_dl_ok(pick[p], s) for p, s in top.items())
|
| 348 |
-
and all(_dl_ok(pick[q], s) for p in pkgs for q, s in reqs[(p, pick[p])].items())
|
| 349 |
-
and not any((p, v) in yanked for p, v in pick.items()))
|
| 350 |
-
|
| 351 |
-
checks = [
|
| 352 |
-
("test_line_format", lambda p: all(ln.count("==") == 1 and " " not in ln for ln in p)),
|
| 353 |
-
("test_one_line_per_package", lambda p: len(p) == len(pkgs) and set(lock(p)) == set(pkgs)),
|
| 354 |
-
("test_sorted_by_name", lambda p: [ln.split("==")[0] for ln in p] == sorted(pkgs)),
|
| 355 |
-
("test_versions_in_index", lambda p: all(v in vers[n] for n, v in lock(p).items())),
|
| 356 |
-
("test_constraints_hold", satisfies),
|
| 357 |
-
("test_preferred_lock", lambda p: p == want),
|
| 358 |
-
]
|
| 359 |
-
return Built(
|
| 360 |
-
instruction=instruction,
|
| 361 |
-
files=files,
|
| 362 |
-
artifact=Artifact(path="lock.txt", kind="checks", parse="lines", checks=checks,
|
| 363 |
-
render=lambda: "\n".join(want) + "\n"),
|
| 364 |
-
notes={"valid": len(valid), "best": best},
|
| 365 |
-
root="/root",
|
| 366 |
-
)
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
# ---------------------------------------------------------------- sw3_fix_module
|
| 370 |
-
|
| 371 |
-
MODULES = { # module name -> (test class, what the job does)
|
| 372 |
-
"report_utils": ("ReportUtilsTest", "nightly reporting job"),
|
| 373 |
-
"metrics_helpers": ("MetricsHelpersTest", "metrics rollup job"),
|
| 374 |
-
"toolkit": ("ToolkitTest", "nightly export job"),
|
| 375 |
-
"text_tools": ("TextToolsTest", "search indexing job"),
|
| 376 |
-
}
|
| 377 |
-
|
| 378 |
-
# CHANGELOG revisions: the newer behaviour wins over the (stale) docstring.
|
| 379 |
-
REVISIONS = {
|
| 380 |
-
"median": {
|
| 381 |
-
"entry": "`median` now returns `None` for an empty list instead of raising.",
|
| 382 |
-
"edit": (" s = sorted(values)\n", " if not values:\n return None\n s = sorted(values)\n"),
|
| 383 |
-
"extra": lambda r: ([],),
|
| 384 |
-
},
|
| 385 |
-
"percent_change": {
|
| 386 |
-
"entry": "`percent_change` now rounds to 1 decimal place instead of 2.",
|
| 387 |
-
"edit": ("old * 100, 2)", "old * 100, 1)"),
|
| 388 |
-
"extra": lambda r: (r.randint(3, 97), r.randint(3, 997)),
|
| 389 |
-
},
|
| 390 |
-
"clamp": {
|
| 391 |
-
"entry": "`clamp` accepts its bounds in either order: when `lo > hi` the two are swapped first.",
|
| 392 |
-
"edit": (" if x < lo:\n", " if lo > hi:\n lo, hi = hi, lo\n if x < lo:\n"),
|
| 393 |
-
"extra": lambda r: (r.randint(-20, 20), r.randint(1, 10), r.randint(-10, 0)),
|
| 394 |
-
},
|
| 395 |
-
"dedupe": {
|
| 396 |
-
"entry": "`dedupe` compares strings case-insensitively and keeps the first spelling it sees.",
|
| 397 |
-
"edit": (" if item not in seen:\n seen.add(item)\n",
|
| 398 |
-
" k = item.lower() if isinstance(item, str) else item\n if k not in seen:\n"
|
| 399 |
-
" seen.add(k)\n"),
|
| 400 |
-
"extra": lambda r: ([r.choice(["ok", "OK", "Ok", "red", "Red", "RED", "x"]) for _ in range(r.randint(3, 9))],),
|
| 401 |
-
},
|
| 402 |
-
"word_count": {
|
| 403 |
-
"entry": "`word_count` counts digits as word characters: a word is now a run of a-z or 0-9.",
|
| 404 |
-
"edit": ('r"[a-z]+"', 'r"[a-z0-9]+"'),
|
| 405 |
-
"extra": lambda r: (" ".join(r.choice(["Room", "101", "room", "B12", "7", "go", "v2.1"]) for _ in range(r.randint(2, 7))),),
|
| 406 |
-
},
|
| 407 |
-
"moving_average": {
|
| 408 |
-
"entry": "`moving_average` rounds every result to 4 decimal places.",
|
| 409 |
-
"edit": ("[sum(values[i:i + k]) / k ", "[round(sum(values[i:i + k]) / k, 4) "),
|
| 410 |
-
"extra": lambda r: ([r.randint(0, 50) for _ in range(r.randint(4, 9))], 3),
|
| 411 |
-
},
|
| 412 |
-
}
|
| 413 |
-
|
| 414 |
-
NOISE_ENTRIES = (
|
| 415 |
-
("Performance", "`word_count` is faster on long inputs."),
|
| 416 |
-
("Performance", "`chunk` no longer copies the input list first."),
|
| 417 |
-
("Docs", "Added usage examples to the README."),
|
| 418 |
-
("Fixed", "Packaging: the wheel now ships `py.typed`."),
|
| 419 |
-
("Internal", "CI runs on Python 3.12."),
|
| 420 |
-
("Internal", "Moved the helpers out of the monolith into their own module."),
|
| 421 |
-
("Docs", "Fixed a typo in the module docstring."),
|
| 422 |
-
("Internal", "Type hints checked with mypy in CI."),
|
| 423 |
-
("Performance", "`median` sorts a copy only once."),
|
| 424 |
-
("Fixed", "The release script tags versions correctly."),
|
| 425 |
-
)
|
| 426 |
-
|
| 427 |
-
FIX_HARNESS = r'''
|
| 428 |
-
import importlib, json, sys
|
| 429 |
-
sys.path.insert(0, sys.argv[1])
|
| 430 |
-
cases = json.loads(sys.stdin.read())
|
| 431 |
-
out = {}
|
| 432 |
-
try:
|
| 433 |
-
mod = importlib.import_module(sys.argv[2])
|
| 434 |
-
except BaseException as exc:
|
| 435 |
-
print("@@RESULT@@" + json.dumps({"__import_error__": type(exc).__name__}))
|
| 436 |
-
raise SystemExit(0)
|
| 437 |
-
for name, arglists in cases.items():
|
| 438 |
-
res = []
|
| 439 |
-
for args in arglists:
|
| 440 |
-
try:
|
| 441 |
-
res.append(getattr(mod, name)(*args))
|
| 442 |
-
except BaseException as exc:
|
| 443 |
-
res.append({"__error__": type(exc).__name__})
|
| 444 |
-
out[name] = res
|
| 445 |
-
print("@@RESULT@@" + json.dumps(out, default=repr))
|
| 446 |
-
'''
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
def _call(fn, args):
|
| 450 |
-
try:
|
| 451 |
-
return _jsonable(fn(*args))
|
| 452 |
-
except Exception as exc: # the harness records raises the same way
|
| 453 |
-
return {"__error__": type(exc).__name__}
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
def _diff(f, g, args) -> bool:
|
| 457 |
-
return not _same(_call(f, args), _call(g, args))
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
def _raises(fn, args) -> bool:
|
| 461 |
-
got = _call(fn, args)
|
| 462 |
-
return isinstance(got, dict) and "__error__" in got
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
def _run_hidden(module: str, source: str, cases: dict) -> dict | None:
|
| 466 |
-
"""Import the agent's module as nobody on a private copy and call every hidden case."""
|
| 467 |
-
tmp = tempfile.mkdtemp(prefix="tdchk-")
|
| 468 |
-
try:
|
| 469 |
-
os.chmod(tmp, 0o755)
|
| 470 |
-
src_dir = os.path.join(tmp, "src")
|
| 471 |
-
os.mkdir(src_dir)
|
| 472 |
-
with open(os.path.join(src_dir, f"{module}.py"), "w") as fh:
|
| 473 |
-
fh.write(source)
|
| 474 |
-
with open(os.path.join(tmp, "harness.py"), "w") as fh:
|
| 475 |
-
fh.write(FIX_HARNESS)
|
| 476 |
-
shell.give_to_nobody(tmp)
|
| 477 |
-
_, text = shell.run(["python3", "-I", os.path.join(tmp, "harness.py"), src_dir, module], tmp,
|
| 478 |
-
stdin_text=json.dumps(cases))
|
| 479 |
-
lines = [ln for ln in text.splitlines() if ln.startswith("@@RESULT@@")]
|
| 480 |
-
return json.loads(lines[-1][len("@@RESULT@@"):]) if lines else None
|
| 481 |
-
finally:
|
| 482 |
-
shell.kill_nobody()
|
| 483 |
-
shutil.rmtree(tmp, ignore_errors=True)
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
def _ci_log(rng: random.Random, module: str, job: str, test_cls: str, failing: tuple) -> str:
|
| 487 |
-
"""A noisy nightly CI log, a few hundred short lines, with the one failing visible test near the end."""
|
| 488 |
-
t = rng.randint(0, 600)
|
| 489 |
-
|
| 490 |
-
def stamp():
|
| 491 |
-
nonlocal t
|
| 492 |
-
t += rng.randint(0, 4)
|
| 493 |
-
return f"02:{t // 60 % 60:02d}:{t % 60:02d}"
|
| 494 |
-
|
| 495 |
-
out = [f"{stamp()} [ci] nightly run of the {job}, 2026-10-13"]
|
| 496 |
-
for step in ("checkout", "setup-python 3.12", f"restore cache (hit, {rng.randint(20, 90)} MB)"):
|
| 497 |
-
out.append(f"{stamp()} [step] {step}")
|
| 498 |
-
out.append(f"{stamp()} [step] install requirements")
|
| 499 |
-
for _ in range(rng.randint(24, 40)):
|
| 500 |
-
pkg = rng.choice(PKG_POOL)
|
| 501 |
-
out.append(f"{stamp()} fetched {pkg}-{rng.randint(0, 4)}.{rng.randint(0, 19)} ({rng.randint(8, 900)} kB)")
|
| 502 |
-
out.append(f"{stamp()} [step] run job dry-run")
|
| 503 |
-
for _ in range(rng.randint(70, 110)):
|
| 504 |
-
out.append(f"{stamp()} {rng.choice(('INFO', 'INFO', 'INFO', 'DEBUG', 'WARN'))} "
|
| 505 |
-
f"{rng.choice(('ingest', 'transform', 'rollup', 'export'))}: batch {rng.randint(1, 400)} "
|
| 506 |
-
f"rows={rng.randint(10, 9999)} took={rng.randint(3, 2000)}ms")
|
| 507 |
-
out.append(f"{stamp()} [step] unit tests: python3 -m unittest discover -s tests -v")
|
| 508 |
-
name, idx, args, got, want = failing
|
| 509 |
-
out.append(f"{stamp()} FAILED (failures=1)")
|
| 510 |
-
out += [
|
| 511 |
-
"=" * 70,
|
| 512 |
-
f"FAIL: test_{name}_{idx} (test_{module}.{test_cls}.test_{name}_{idx})",
|
| 513 |
-
"-" * 70,
|
| 514 |
-
"Traceback (most recent call last):",
|
| 515 |
-
f' File "/app/tests/test_{module}.py", line {9 + 3 * idx}, in test_{name}_{idx}',
|
| 516 |
-
f" self.assertEqual({module}.{name}(*{list(args)!r}), {want!r})",
|
| 517 |
-
f"AssertionError: {got!r} != {want!r}",
|
| 518 |
-
f"{stamp()} [ci] job failed: exit code 1",
|
| 519 |
-
]
|
| 520 |
-
return "\n".join(out) + "\n"
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
def _changelog(rng: random.Random, revised: str | None, n: int, position: int) -> str:
|
| 524 |
-
entries = rng.sample(NOISE_ENTRIES, n - (revised is not None))
|
| 525 |
-
if revised is not None:
|
| 526 |
-
entries.insert(position, ("Changed", REVISIONS[revised]["entry"]))
|
| 527 |
-
minor, day = rng.randint(2, 4), datetime.date(2026, 5, 1) + datetime.timedelta(days=rng.randint(0, 60))
|
| 528 |
-
blocks = []
|
| 529 |
-
for patch, (kind, text) in enumerate(reversed(entries), 1): # oldest release first
|
| 530 |
-
day += datetime.timedelta(days=rng.randint(3, 14))
|
| 531 |
-
blocks.append(f"## [{minor}.{patch}.0] - {day.isoformat()}\n\n### {kind}\n- {text}\n")
|
| 532 |
-
blocks.reverse() # printed newest first
|
| 533 |
-
return "# Changelog\n\nAll notable changes to this module. Newest first.\n\n" + "\n".join(blocks)
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
def build_fix_module(level: int, rng: random.Random) -> Built:
|
| 537 |
-
n_funcs, n_bugs = {1: (3, 1), 2: (4, 2), 3: (5, 2)}[level]
|
| 538 |
-
module = rng.choice(sorted(MODULES))
|
| 539 |
-
test_cls, job = MODULES[module]
|
| 540 |
-
while True:
|
| 541 |
-
names = rng.sample(sorted(FUNCS), n_funcs)
|
| 542 |
-
buggy = rng.sample(names, n_bugs)
|
| 543 |
-
revised = None
|
| 544 |
-
if level == 2: # the CHANGELOG revises a function that is not buggy
|
| 545 |
-
pool = [n for n in names if n in REVISIONS and n not in buggy]
|
| 546 |
-
elif level == 3: # it revises a buggy one, so restoring the docstring is wrong
|
| 547 |
-
pool = [n for n in buggy if n in REVISIONS]
|
| 548 |
-
else:
|
| 549 |
-
pool = [None]
|
| 550 |
-
if pool:
|
| 551 |
-
revised = rng.choice(pool)
|
| 552 |
-
break
|
| 553 |
-
shown = next(n for n in buggy if n != revised) # the bug with a failing visible test (never the revised one)
|
| 554 |
-
sources, good_sources, hidden, tests, failing = [], [], {}, [], None
|
| 555 |
-
for name in names:
|
| 556 |
-
spec = FUNCS[name]
|
| 557 |
-
good_src = spec["src"]
|
| 558 |
-
if name == revised:
|
| 559 |
-
old, new = REVISIONS[name]["edit"]
|
| 560 |
-
assert old in good_src, (name, old)
|
| 561 |
-
good_src = good_src.replace(old, new, 1)
|
| 562 |
-
good = _compile(good_src)
|
| 563 |
-
src, bad = spec["src"], None
|
| 564 |
-
if name in buggy:
|
| 565 |
-
old, new = rng.choice(spec["bugs"])
|
| 566 |
-
assert old in src, (name, old)
|
| 567 |
-
src = src.replace(old, new, 1)
|
| 568 |
-
bad = _compile(src)
|
| 569 |
-
cases = [spec["gen"](rng) for _ in range(40)]
|
| 570 |
-
if name == revised:
|
| 571 |
-
original = _compile(spec["src"])
|
| 572 |
-
extra = [REVISIONS[name]["extra"](rng) for _ in range(6)]
|
| 573 |
-
assert sum(_diff(original, good, c) for c in cases + extra) >= 3, name
|
| 574 |
-
cases += extra
|
| 575 |
-
if bad is not None:
|
| 576 |
-
diffs = [c for c in cases if _diff(good, bad, c)]
|
| 577 |
-
while len(diffs) < 3:
|
| 578 |
-
c = spec["gen"](rng)
|
| 579 |
-
if _diff(good, bad, c):
|
| 580 |
-
diffs.append(c)
|
| 581 |
-
cases.append(c)
|
| 582 |
-
sources.append(src)
|
| 583 |
-
good_sources.append(good_src)
|
| 584 |
-
hidden[name] = (_jsonable([list(c) for c in cases]), [_call(good, c) for c in cases])
|
| 585 |
-
if name == shown:
|
| 586 |
-
c = next(c for c in cases if _diff(good, bad, c) and not _raises(bad, c) and not _raises(good, c))
|
| 587 |
-
failing = (name, len(tests), c, bad(*c), good(*c))
|
| 588 |
-
tests.append((name, c, good(*c)))
|
| 589 |
-
elif name not in buggy and name != revised:
|
| 590 |
-
for c in cases[:2]:
|
| 591 |
-
tests.append((name, c, good(*c)))
|
| 592 |
-
header = f'"""{module}: small helpers used by the {job}."""\n\nimport re\n\n\n'
|
| 593 |
-
module_src = header + "\n\n".join(sources)
|
| 594 |
-
fixed_src = header + "\n\n".join(good_sources)
|
| 595 |
-
test_lines = [
|
| 596 |
-
"import os, sys, unittest",
|
| 597 |
-
"sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'src'))",
|
| 598 |
-
f"import {module}",
|
| 599 |
-
"",
|
| 600 |
-
"",
|
| 601 |
-
f"class {test_cls}(unittest.TestCase):",
|
| 602 |
-
]
|
| 603 |
-
for i, (name, args, want) in enumerate(tests):
|
| 604 |
-
test_lines += [f" def test_{name}_{i}(self):",
|
| 605 |
-
f" self.assertEqual({module}.{name}(*{list(args)!r}), {want!r})", ""]
|
| 606 |
-
test_lines += ["", 'if __name__ == "__main__":', " unittest.main()", ""]
|
| 607 |
-
files = {
|
| 608 |
-
f"src/{module}.py": module_src,
|
| 609 |
-
f"tests/test_{module}.py": "\n".join(test_lines),
|
| 610 |
-
"ci/nightly.log": _ci_log(rng, module, job, test_cls, failing),
|
| 611 |
-
}
|
| 612 |
-
path = f"src/{module}.py"
|
| 613 |
-
broken = "one of them no longer does what its docstring says" if n_bugs == 1 else \
|
| 614 |
-
f"{n_bugs} of them no longer do what their docstrings say"
|
| 615 |
-
listing = [
|
| 616 |
-
f"- src/{module}.py: the module; each function's docstring is its specification.",
|
| 617 |
-
f"- tests/test_{module}.py: visible unit tests. They are incomplete: a function can be wrong and still "
|
| 618 |
-
"pass them. Run them from /app with python3 -m unittest discover -s tests.",
|
| 619 |
-
"- ci/nightly.log: the log of last night's failed run.",
|
| 620 |
-
]
|
| 621 |
-
if level >= 2:
|
| 622 |
-
n_entries = rng.randint(6, 8)
|
| 623 |
-
files["CHANGELOG.md"] = _changelog(rng, revised, n_entries, rng.randint(1, n_entries - 2) if level == 3 else
|
| 624 |
-
rng.randint(0, 2))
|
| 625 |
-
listing.append("- CHANGELOG.md: release notes. Where an entry and a docstring disagree, the entry is newer "
|
| 626 |
-
"and wins; leave the docstring as it is.")
|
| 627 |
-
instruction = (
|
| 628 |
-
f"Our {job} started failing in CI after a refactor of /app/{path}. The module has {n_funcs} functions and "
|
| 629 |
-
f"{broken}. Repair the module in place.\n\nFiles in /app:\n" + "\n".join(listing) + "\n\n"
|
| 630 |
-
"Keep every function name and signature, use only the standard library, and do not edit the tests. The "
|
| 631 |
-
f"grader imports /app/{path} and runs its own hidden tests against every function, including the ones the "
|
| 632 |
-
"visible tests do not cover; the task passes only if all of them pass."
|
| 633 |
-
)
|
| 634 |
-
cases = {n: args for n, (args, _) in hidden.items()}
|
| 635 |
-
cache: dict = {}
|
| 636 |
-
|
| 637 |
-
def results(text: str):
|
| 638 |
-
if cache.get("text") != text:
|
| 639 |
-
cache.update(text=text, got=_run_hidden(module, text, cases))
|
| 640 |
-
return cache["got"]
|
| 641 |
-
|
| 642 |
-
def imports(text):
|
| 643 |
-
got = results(text)
|
| 644 |
-
return isinstance(got, dict) and "__import_error__" not in got
|
| 645 |
-
|
| 646 |
-
def passes(name):
|
| 647 |
-
return lambda text: imports(text) and _same(results(text)[name], hidden[name][1])
|
| 648 |
-
|
| 649 |
-
checks = [("test_module_imports", imports)] + [(f"test_{n}", passes(n)) for n in names]
|
| 650 |
-
return Built(
|
| 651 |
-
instruction=instruction,
|
| 652 |
-
files=files,
|
| 653 |
-
artifact=Artifact(path=path, kind="checks", parse="text", checks=checks, render=lambda: fixed_src),
|
| 654 |
-
notes={"buggy": sorted(buggy), "revised": revised, "module": module},
|
| 655 |
-
root="/app",
|
| 656 |
-
)
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
FAMILIES = [
|
| 660 |
-
Family("sw3_fix_module", "software engineering", "Repair a helper module against hidden tests",
|
| 661 |
-
build_fix_module, v3=True),
|
| 662 |
-
Family("sw3_rate_limit", "software engineering", "Replay token-bucket rate limiting", build_rate_limit, v3=True),
|
| 663 |
-
Family("sw3_dep_lock", "software engineering", "Resolve a lock file against a package index", build_dep_lock,
|
| 664 |
-
v3=True),
|
| 665 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/__init__.py
DELETED
|
@@ -1,40 +0,0 @@
|
|
| 1 |
-
"""Oracle scripts for v3 families: terminal_desk/oracles/<family_id>.py.
|
| 2 |
-
|
| 3 |
-
An oracle is the standalone script a good agent writes in one write_file: it
|
| 4 |
-
reads the inputs and writes the output file using only the image's packages.
|
| 5 |
-
It is not the grader; it proves the files carry everything the answer needs.
|
| 6 |
-
|
| 7 |
-
Oracles open paths relative to the working directory (the environment runs
|
| 8 |
-
commands with cwd = the family root), so the same script works under the real
|
| 9 |
-
/root and /app and under TERMINAL_DESK_ROOTS in tests.
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
-
import os
|
| 13 |
-
|
| 14 |
-
from ..models import Tbench2Action
|
| 15 |
-
|
| 16 |
-
ORACLE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 17 |
-
ORACLE_FILE = "oracle.py" # where the runner writes the script, relative to the root
|
| 18 |
-
EXIT_MARK = "@@oracle-exit="
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
def oracle_path(family_id: str, directory: str = ORACLE_DIR) -> str:
|
| 22 |
-
return os.path.join(directory, f"{family_id}.py")
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
def oracle_source(family_id: str, directory: str = ORACLE_DIR) -> str | None:
|
| 26 |
-
path = oracle_path(family_id, directory)
|
| 27 |
-
if not os.path.isfile(path):
|
| 28 |
-
return None
|
| 29 |
-
with open(path, encoding="utf-8") as fh:
|
| 30 |
-
return fh.read()
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def run_oracle(env, source: str):
|
| 34 |
-
"""Play the oracle the way an agent would on a reset env: write_file it, exec python3, evaluate.
|
| 35 |
-
Returns (exec output, evaluate observation). Commands run as nobody when the server is root."""
|
| 36 |
-
wrote = env.step(Tbench2Action(action_type="write_file", file_path=ORACLE_FILE, content=source))
|
| 37 |
-
if not wrote.success:
|
| 38 |
-
raise RuntimeError(f"could not write the oracle: {wrote.error}")
|
| 39 |
-
ran = env.step(Tbench2Action(action_type="exec", command=f'python3 {ORACLE_FILE}; echo "{EXIT_MARK}$?"'))
|
| 40 |
-
return ran.output, env.step(Tbench2Action(action_type="evaluate"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/fin3_invoice_fraud.py
DELETED
|
@@ -1,34 +0,0 @@
|
|
| 1 |
-
"""Oracle for fin3_invoice_fraud: the first matching rule per invoice row, in file order."""
|
| 2 |
-
import csv
|
| 3 |
-
import json
|
| 4 |
-
import os
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
def rows(name):
|
| 8 |
-
with open(f"data/{name}", newline="") as fh:
|
| 9 |
-
return list(csv.DictReader(fh))
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
pos = {r["po_number"]: float(r["amount"]) for r in rows("purchase_orders.csv")}
|
| 13 |
-
vendors = {r["vendor_id"]: r["status"] for r in rows("vendors.csv")} if os.path.exists("data/vendors.csv") else None
|
| 14 |
-
|
| 15 |
-
report, seen = [], set()
|
| 16 |
-
for n, inv in enumerate(rows("invoices.csv"), 1):
|
| 17 |
-
vid, po, amount = inv["vendor_id"], inv["po_number"], float(inv["amount"])
|
| 18 |
-
key = (vid, inv["invoice_no"])
|
| 19 |
-
if vendors is not None and vendors.get(vid) != "ACTIVE":
|
| 20 |
-
reason = "Unknown Vendor"
|
| 21 |
-
elif po not in pos:
|
| 22 |
-
reason = "Missing PO"
|
| 23 |
-
elif abs(amount - pos[po]) > 0.02 * pos[po]:
|
| 24 |
-
reason = "Amount Mismatch"
|
| 25 |
-
elif key in seen:
|
| 26 |
-
reason = "Duplicate Invoice"
|
| 27 |
-
else:
|
| 28 |
-
reason = None
|
| 29 |
-
seen.add(key)
|
| 30 |
-
if reason:
|
| 31 |
-
report.append({"row": n, "invoice_no": inv["invoice_no"], "amount": amount, "reason": reason})
|
| 32 |
-
|
| 33 |
-
with open("fraud_report.json", "w") as fh:
|
| 34 |
-
json.dump(report, fh, indent=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/fin3_loan_schedule.py
DELETED
|
@@ -1,55 +0,0 @@
|
|
| 1 |
-
"""Oracle for fin3_loan_schedule."""
|
| 2 |
-
import csv
|
| 3 |
-
import os
|
| 4 |
-
from decimal import ROUND_HALF_UP, Decimal
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
def r2(x):
|
| 8 |
-
return x.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
def annuity(bal, pct, n):
|
| 12 |
-
i = pct / 1200
|
| 13 |
-
return r2(bal * i / (1 - (1 + i) ** -n))
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
def rows(name):
|
| 17 |
-
if not os.path.exists(f"data/{name}"):
|
| 18 |
-
return []
|
| 19 |
-
with open(f"data/{name}", newline="") as fh:
|
| 20 |
-
return [r for r in csv.DictReader(fh) if r.get("loan_id") == lid]
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
lid = open("data/ticket.txt").read().split("Loan:")[1].split()[0]
|
| 24 |
-
loan = rows("loans.csv")[0]
|
| 25 |
-
bal, cur, term = Decimal(loan["principal"]), Decimal(loan["annual_rate_pct"]), int(loan["term_months"])
|
| 26 |
-
extras = {}
|
| 27 |
-
for r in rows("extra_payments.csv"):
|
| 28 |
-
if r.get("status") != "REVERSED":
|
| 29 |
-
m = int(r["payment_no"])
|
| 30 |
-
extras[m] = extras.get(m, 0) + Decimal(r["amount"])
|
| 31 |
-
resets = {int(r["from_payment"]): Decimal(r["new_rate_pct"]) for r in rows("rate_resets.csv")}
|
| 32 |
-
|
| 33 |
-
out, month, pay = [], 0, annuity(bal, cur, term)
|
| 34 |
-
while bal > 0:
|
| 35 |
-
month += 1
|
| 36 |
-
if month in resets:
|
| 37 |
-
cur = resets[month]
|
| 38 |
-
pay = annuity(bal, cur, term - month + 1)
|
| 39 |
-
i = r2(bal * cur / 1200)
|
| 40 |
-
if bal + i <= pay or month == term:
|
| 41 |
-
out.append([month, bal + i, i, bal, 0, 0])
|
| 42 |
-
break
|
| 43 |
-
bal -= pay - i
|
| 44 |
-
extra = min(extras.get(month, 0), bal)
|
| 45 |
-
bal -= extra
|
| 46 |
-
out.append([month, pay, i, pay - i, extra, bal])
|
| 47 |
-
|
| 48 |
-
head = ["month", "payment", "interest", "principal", "extra", "balance"]
|
| 49 |
-
if not os.path.exists("data/extra_payments.csv"):
|
| 50 |
-
head.remove("extra")
|
| 51 |
-
out = [r[:4] + r[5:] for r in out]
|
| 52 |
-
with open("schedule.csv", "w", newline="") as fh:
|
| 53 |
-
w = csv.writer(fh)
|
| 54 |
-
w.writerow(head)
|
| 55 |
-
w.writerows([r[0]] + [f"{Decimal(x):.2f}" for x in r[1:]] for r in out)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/fin3_portfolio_value.py
DELETED
|
@@ -1,42 +0,0 @@
|
|
| 1 |
-
"""Oracle for fin3_portfolio_value: replay trades and corporate actions, value at the last close."""
|
| 2 |
-
import csv
|
| 3 |
-
import os
|
| 4 |
-
import re
|
| 5 |
-
from decimal import Decimal
|
| 6 |
-
|
| 7 |
-
with open("data/prices.csv", newline="") as fh:
|
| 8 |
-
prices = list(csv.DictReader(fh))
|
| 9 |
-
last = max(r["date"] for r in prices)
|
| 10 |
-
close = {r["ticker"]: Decimal(r["close"]) for r in prices if r["date"] == last}
|
| 11 |
-
|
| 12 |
-
events = [] # (date, 0 = corporate action before 1 = that day's trades, kind, data)
|
| 13 |
-
if os.path.exists("data/corporate_actions.txt"):
|
| 14 |
-
for line in open("data/corporate_actions.txt"):
|
| 15 |
-
m = re.match(r"(\S+) (\S+) (\d+)-for-1", line)
|
| 16 |
-
if m:
|
| 17 |
-
events.append((m[1], 0, "split", (m[2], int(m[3]))))
|
| 18 |
-
m = re.match(r"(\S+) (\S+) cash dividend of ([\d.]+)", line)
|
| 19 |
-
if m:
|
| 20 |
-
events.append((m[1], 0, "div", (m[2], Decimal(m[3]))))
|
| 21 |
-
with open("data/trades.csv", newline="") as fh:
|
| 22 |
-
events += [(r["date"], 1, "trade", r) for r in csv.DictReader(fh)]
|
| 23 |
-
|
| 24 |
-
cash, hold = Decimal(100000), {}
|
| 25 |
-
for date, _, kind, data in sorted(events, key=lambda e: (e[0], e[1])):
|
| 26 |
-
if kind == "split":
|
| 27 |
-
hold[data[0]] = hold.get(data[0], 0) * data[1]
|
| 28 |
-
elif kind == "div":
|
| 29 |
-
cash += data[1] * hold.get(data[0], 0)
|
| 30 |
-
else:
|
| 31 |
-
sign = 1 if data["side"] == "BUY" else -1
|
| 32 |
-
qty = sign * int(data["shares"])
|
| 33 |
-
hold[data["ticker"]] = hold.get(data["ticker"], 0) + qty
|
| 34 |
-
cash -= qty * Decimal(data["price"])
|
| 35 |
-
|
| 36 |
-
with open("positions.csv", "w", newline="") as fh:
|
| 37 |
-
w = csv.writer(fh)
|
| 38 |
-
w.writerow(["ticker", "shares", "close", "market_value"])
|
| 39 |
-
for t, q in sorted(hold.items()):
|
| 40 |
-
if q:
|
| 41 |
-
w.writerow([t, q, f"{close[t]:.2f}", f"{q * close[t]:.2f}"])
|
| 42 |
-
w.writerow(["CASH", 0, 0, f"{cash:.2f}"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/ind3_service_due.py
DELETED
|
@@ -1,47 +0,0 @@
|
|
| 1 |
-
"""Oracle for ind3_service_due: run-hours and days since service against each type's limits."""
|
| 2 |
-
import csv
|
| 3 |
-
import os
|
| 4 |
-
import re
|
| 5 |
-
from datetime import date
|
| 6 |
-
|
| 7 |
-
ASOF = date(2026, 10, 31)
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
def rows(path):
|
| 11 |
-
with open(path, newline="") as fh:
|
| 12 |
-
return list(csv.DictReader(fh))
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def text(path):
|
| 16 |
-
return open(path).read() if os.path.exists(path) else ""
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
limits = {r["type"]: (float(r["max_run_hours"]), int(r["max_days"])) for r in rows("data/service_intervals.csv")}
|
| 20 |
-
machines = {r["machine"]: r for r in rows("data/machines.csv")}
|
| 21 |
-
service = {m: (date.fromisoformat(r["last_service_date"]), float(r["meter_at_service"])) for m, r in machines.items()}
|
| 22 |
-
for day, m, meter in re.findall(r"(\S+): (M\d+) was serviced again; its hour meter read ([\d.]+)", text("data/notes.md")):
|
| 23 |
-
service[m] = (date.fromisoformat(day), float(meter))
|
| 24 |
-
swaps = {m: date.fromisoformat(d) for d, m in re.findall(r"(\S+): (M\d+) hour meter failed", text("data/shift_log.txt"))}
|
| 25 |
-
|
| 26 |
-
readings = {}
|
| 27 |
-
for r in rows("data/meter_readings.csv"):
|
| 28 |
-
day = date.fromisoformat(r["date"])
|
| 29 |
-
if day <= ASOF:
|
| 30 |
-
readings.setdefault(r["machine"], []).append((day, float(r["meter_hours"])))
|
| 31 |
-
|
| 32 |
-
out = []
|
| 33 |
-
for m in sorted(machines):
|
| 34 |
-
served, at = service[m]
|
| 35 |
-
seq = sorted(readings[m])
|
| 36 |
-
hours = seq[-1][1] - at
|
| 37 |
-
if m in swaps: # the new meter counts from zero; add the old meter's hours up to the swap
|
| 38 |
-
hours += max(x for x in seq if x[0] < swaps[m])[1]
|
| 39 |
-
days = (ASOF - served).days
|
| 40 |
-
max_hours, max_days = limits[machines[m]["type"]]
|
| 41 |
-
out.append([m, f"{hours:.1f}", days, "yes" if hours >= max_hours or days >= max_days else "no"])
|
| 42 |
-
|
| 43 |
-
with open("service_report.csv", "w", newline="") as fh:
|
| 44 |
-
w = csv.writer(fh)
|
| 45 |
-
w.writerow(["machine", "run_hours_since_service", "days_since_service", "due"])
|
| 46 |
-
w.writerows(out)
|
| 47 |
-
print(out)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/ind3_stl_mass.py
DELETED
|
@@ -1,42 +0,0 @@
|
|
| 1 |
-
"""Oracle for ind3_stl_mass: signed-tetrahedron volume and area per solid, keep the largest, mass."""
|
| 2 |
-
import csv
|
| 3 |
-
import json
|
| 4 |
-
import os
|
| 5 |
-
|
| 6 |
-
with open("data/materials.csv", newline="") as fh:
|
| 7 |
-
density = {r["code"]: float(r["density_g_cm3"]) for r in csv.DictReader(fh)}
|
| 8 |
-
notes = open("data/scan_notes.md").read() if os.path.exists("data/scan_notes.md") else ""
|
| 9 |
-
|
| 10 |
-
solids = []
|
| 11 |
-
for line in open("data/scan.stl"):
|
| 12 |
-
w = line.split()
|
| 13 |
-
if w and w[0] == "solid":
|
| 14 |
-
solid = {"name": w[1], "code": w[2], "tris": [], "v": []}
|
| 15 |
-
solids.append(solid)
|
| 16 |
-
elif w and w[0] == "vertex":
|
| 17 |
-
solid["v"].append([float(x) for x in w[1:4]])
|
| 18 |
-
if len(solid["v"]) == 3:
|
| 19 |
-
solid["tris"].append(solid["v"])
|
| 20 |
-
solid["v"] = []
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
def cross(a, b):
|
| 24 |
-
return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
for s in solids:
|
| 28 |
-
vol = area = 0.0
|
| 29 |
-
for a, b, c in s["tris"]:
|
| 30 |
-
vol += sum(x * y for x, y in zip(a, cross(b, c))) / 6
|
| 31 |
-
n = cross([q - p for p, q in zip(a, b)], [q - p for p, q in zip(a, c)])
|
| 32 |
-
area += sum(x * x for x in n) ** 0.5 / 2
|
| 33 |
-
s["vol"], s["area"] = abs(vol), area
|
| 34 |
-
|
| 35 |
-
part = max(solids, key=lambda s: s["vol"])
|
| 36 |
-
k = 2.54 if "exported in inches" in notes else 0.1 # file units to cm
|
| 37 |
-
volume, area = part["vol"] * k**3, part["area"] * k**2
|
| 38 |
-
report = {"solid": part["name"], "material": part["code"], "volume_cm3": volume, "area_cm2": area,
|
| 39 |
-
"mass_g": volume * density[part["code"]]}
|
| 40 |
-
with open("mass_report.json", "w") as fh:
|
| 41 |
-
json.dump(report, fh)
|
| 42 |
-
print(report)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/ind3_tank_balance.py
DELETED
|
@@ -1,50 +0,0 @@
|
|
| 1 |
-
"""Oracle for ind3_tank_balance: trapezoid inflow/outflow, net, and the longest high-level run."""
|
| 2 |
-
import csv
|
| 3 |
-
import json
|
| 4 |
-
import os
|
| 5 |
-
import re
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
def text(path):
|
| 9 |
-
return open(path).read() if os.path.exists(path) else ""
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def sec(t):
|
| 13 |
-
h, m, s = map(int, t.split(":"))
|
| 14 |
-
return h * 3600 + m * 60 + s
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
readme, note = text("data/README.md"), text("data/maintenance_note.txt")
|
| 18 |
-
cal = re.search(r"at (\d\d:\d\d:\d\d)\. Inflow readings taken before that time read (\d+)% high", note)
|
| 19 |
-
with open("data/tank_log.csv", newline="") as fh:
|
| 20 |
-
rows = [r for r in csv.DictReader(fh) if r.get("status", "OK") != "FAULT"]
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
def inflow(r):
|
| 24 |
-
f = float(r["inflow_lpm"])
|
| 25 |
-
if cal and sec(r["time"]) < sec(cal.group(1)):
|
| 26 |
-
f /= 1 + int(cal.group(2)) / 100
|
| 27 |
-
return f
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
tin = tout = 0.0
|
| 31 |
-
for a, b in zip(rows, rows[1:]):
|
| 32 |
-
minutes = (sec(b["time"]) - sec(a["time"])) / 60
|
| 33 |
-
tin += (inflow(a) + inflow(b)) / 2 * minutes
|
| 34 |
-
tout += (float(a["outflow_lpm"]) + float(b["outflow_lpm"])) / 2 * minutes
|
| 35 |
-
report = {"inflow_liters": round(tin, 2), "outflow_liters": round(tout, 2), "net_liters": round(tin - tout, 2)}
|
| 36 |
-
|
| 37 |
-
alarm = re.search(r"alarm setpoint is (\d+) cm", readme)
|
| 38 |
-
if alarm:
|
| 39 |
-
best, start = 0, None
|
| 40 |
-
for r in rows:
|
| 41 |
-
if float(r["level_cm"]) > int(alarm.group(1)):
|
| 42 |
-
start = sec(r["time"]) if start is None else start
|
| 43 |
-
best = max(best, sec(r["time"]) - start)
|
| 44 |
-
else:
|
| 45 |
-
start = None
|
| 46 |
-
report["longest_high_minutes"] = round(best / 60, 2)
|
| 47 |
-
|
| 48 |
-
with open("tank_report.json", "w") as fh:
|
| 49 |
-
json.dump(report, fh)
|
| 50 |
-
print(report)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/math3_count_items.py
DELETED
|
@@ -1,32 +0,0 @@
|
|
| 1 |
-
"""Oracle for math3_count_items: filter the raffle tickets by the draw rules, then rank and count pairs."""
|
| 2 |
-
import csv
|
| 3 |
-
import json
|
| 4 |
-
import os
|
| 5 |
-
|
| 6 |
-
cfg = json.load(open("data/draw.json"))
|
| 7 |
-
void = set()
|
| 8 |
-
if os.path.exists("data/voided.csv"):
|
| 9 |
-
void = {r["ticket"] for r in csv.DictReader(open("data/voided.csv"))}
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def wins(x):
|
| 13 |
-
if not any(x % d == 0 for d in cfg["divisors"]) or x % cfg["excluded_divisor"] == 0:
|
| 14 |
-
return False
|
| 15 |
-
ds = cfg.get("digit_sum_divisor")
|
| 16 |
-
return ds is None or sum(map(int, str(x))) % ds == 0
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
nums = set()
|
| 20 |
-
for r in csv.DictReader(open("data/tickets.csv")):
|
| 21 |
-
x = int(r["number"])
|
| 22 |
-
if r["ticket"] not in void and wins(x):
|
| 23 |
-
nums.add(x)
|
| 24 |
-
nums = sorted(nums)
|
| 25 |
-
|
| 26 |
-
out = {"count": len(nums), "kth_smallest": nums[cfg["rank"] - 1], "largest": nums[-1]}
|
| 27 |
-
if "pair_modulus" in cfg:
|
| 28 |
-
m = cfg["pair_modulus"]
|
| 29 |
-
out["pairs"] = sum((p + q) % m == 0 for i, p in enumerate(nums) for q in nums[i + 1:])
|
| 30 |
-
with open("results.json", "w") as f:
|
| 31 |
-
json.dump(out, f)
|
| 32 |
-
print(out)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/math3_exam_slots.py
DELETED
|
@@ -1,50 +0,0 @@
|
|
| 1 |
-
"""Oracle for math3_exam_slots: brute-force every block order that respects front-loading."""
|
| 2 |
-
import csv
|
| 3 |
-
import itertools
|
| 4 |
-
import json
|
| 5 |
-
import os
|
| 6 |
-
|
| 7 |
-
inst = json.load(open("data/instance.json"))
|
| 8 |
-
blocks, slots = inst["blocks"], inst["slots"]
|
| 9 |
-
evening = "evening-to-morning" in open("data/README.md").read().lower()
|
| 10 |
-
cutoff = inst.get("large_block_cutoff")
|
| 11 |
-
large = {b for b in blocks if cutoff is not None and inst["block_size"][b] >= cutoff}
|
| 12 |
-
early = set(inst.get("early_slots", []))
|
| 13 |
-
|
| 14 |
-
pair, trip = {}, {}
|
| 15 |
-
for r in csv.DictReader(open("data/pair_counts.csv")):
|
| 16 |
-
pair[frozenset((r["block_a"], r["block_b"]))] = int(r["students"])
|
| 17 |
-
for r in csv.DictReader(open("data/triplet_counts.csv")):
|
| 18 |
-
trip[frozenset((r["block_a"], r["block_b"], r["block_c"]))] = int(r["students"])
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
def cost(order):
|
| 22 |
-
total = 0
|
| 23 |
-
for i in range(len(slots) - 1):
|
| 24 |
-
s, t = slots[i], slots[i + 1]
|
| 25 |
-
k = pair[frozenset(order[i:i + 2])]
|
| 26 |
-
if s["day"] == t["day"]:
|
| 27 |
-
total += 3 * k
|
| 28 |
-
elif evening and s["period"] == "PM" and t["period"] == "AM" and t["day"] == s["day"] + 1:
|
| 29 |
-
total += k
|
| 30 |
-
days = {}
|
| 31 |
-
for s, b in zip(slots, order):
|
| 32 |
-
days.setdefault(s["day"], []).append(b)
|
| 33 |
-
return total + sum(10 * trip[frozenset(d)] for d in days.values() if len(d) == 3)
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
best = None
|
| 37 |
-
for order in itertools.permutations(blocks):
|
| 38 |
-
if any(b in large and s["slot"] not in early for s, b in zip(slots, order)):
|
| 39 |
-
continue
|
| 40 |
-
c = cost(order)
|
| 41 |
-
if best is None or c < best[0]:
|
| 42 |
-
best = (c, order)
|
| 43 |
-
|
| 44 |
-
os.makedirs("output", exist_ok=True)
|
| 45 |
-
with open("output/schedule.csv", "w", newline="") as f:
|
| 46 |
-
w = csv.writer(f)
|
| 47 |
-
w.writerow(["slot", "block"])
|
| 48 |
-
for s, b in zip(slots, best[1]):
|
| 49 |
-
w.writerow([s["slot"], b])
|
| 50 |
-
print("objective", best[0])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/math3_route_plan.py
DELETED
|
@@ -1,48 +0,0 @@
|
|
| 1 |
-
"""Oracle for math3_route_plan: earliest-arrival Dijkstra over the open roads, waiting out timed closures."""
|
| 2 |
-
import heapq
|
| 3 |
-
import json
|
| 4 |
-
import os
|
| 5 |
-
import re
|
| 6 |
-
|
| 7 |
-
req = json.load(open("request.json"))
|
| 8 |
-
src, dst = req["from"], req["to"]
|
| 9 |
-
closed, shut, timed = set(), set(), {}
|
| 10 |
-
if os.path.exists("closures.md"):
|
| 11 |
-
section = ""
|
| 12 |
-
for line in open("closures.md"):
|
| 13 |
-
line = line.strip()
|
| 14 |
-
if line.startswith("## "):
|
| 15 |
-
section = line[3:].lower()
|
| 16 |
-
elif line.startswith("- "):
|
| 17 |
-
m = re.match(r"- (\w+) -> (\w+)(?:: closed from minute (\d+) to minute (\d+))?$", line)
|
| 18 |
-
if section.startswith("closed roads"):
|
| 19 |
-
closed.add(m.group(1, 2))
|
| 20 |
-
elif section.startswith("closed junctions"):
|
| 21 |
-
shut.add(line[2:])
|
| 22 |
-
elif section.startswith("timed"):
|
| 23 |
-
timed[m.group(1, 2)] = (int(m.group(3)), int(m.group(4)))
|
| 24 |
-
|
| 25 |
-
adj = {}
|
| 26 |
-
for r in json.load(open("graph.json"))["roads"]:
|
| 27 |
-
u, v = r["from"], r["to"]
|
| 28 |
-
if (u, v) not in closed and u not in shut and v not in shut:
|
| 29 |
-
adj.setdefault(u, []).append((v, r["minutes"]))
|
| 30 |
-
|
| 31 |
-
best, prev, heap = {src: 0}, {}, [(0, src)]
|
| 32 |
-
while heap:
|
| 33 |
-
t, u = heapq.heappop(heap)
|
| 34 |
-
if t > best[u]:
|
| 35 |
-
continue
|
| 36 |
-
for v, w in adj.get(u, []):
|
| 37 |
-
a, b = timed.get((u, v), (0, 0))
|
| 38 |
-
arrive = (b if a <= t < b else t) + w
|
| 39 |
-
if arrive < best.get(v, float("inf")):
|
| 40 |
-
best[v], prev[v] = arrive, u
|
| 41 |
-
heapq.heappush(heap, (arrive, v))
|
| 42 |
-
|
| 43 |
-
path = [dst]
|
| 44 |
-
while path[-1] != src:
|
| 45 |
-
path.append(prev[path[-1]])
|
| 46 |
-
with open("route.json", "w") as f:
|
| 47 |
-
json.dump({"path": path[::-1], "total_minutes": best[dst]}, f)
|
| 48 |
-
print(path[::-1], best[dst])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/med3_silence_report.py
DELETED
|
@@ -1,44 +0,0 @@
|
|
| 1 |
-
"""Oracle for med3_silence_report: 50 ms windows, RMS in dBFS, silent runs become removed segments."""
|
| 2 |
-
import json
|
| 3 |
-
import math
|
| 4 |
-
import os
|
| 5 |
-
import re
|
| 6 |
-
import wave
|
| 7 |
-
from array import array
|
| 8 |
-
|
| 9 |
-
w = wave.open("data/lecture.wav")
|
| 10 |
-
rate, ch, n = w.getframerate(), w.getnchannels(), w.getnframes()
|
| 11 |
-
x = array("h", w.readframes(n))[::ch] # mono, or channel 1 (the lapel mic) of a stereo file
|
| 12 |
-
win = int(rate * 0.05)
|
| 13 |
-
nwin = len(x) // win
|
| 14 |
-
|
| 15 |
-
notes = open("data/notes.md").read() if os.path.exists("data/notes.md") else ""
|
| 16 |
-
m = re.search(r"From ([\d.]+) s to ([\d.]+) s.*?use (-[\d.]+) dBFS", notes, re.S)
|
| 17 |
-
|
| 18 |
-
silent = []
|
| 19 |
-
for i in range(nwin):
|
| 20 |
-
rms = math.sqrt(sum(v * v for v in x[i * win:(i + 1) * win]) / win)
|
| 21 |
-
db = 20 * math.log10(max(rms, 1e-9) / 32768)
|
| 22 |
-
limit = float(m[3]) if m and float(m[1]) <= i * 0.05 < float(m[2]) else -40.0
|
| 23 |
-
silent.append(db < limit)
|
| 24 |
-
|
| 25 |
-
segments, i = [], 0
|
| 26 |
-
while i < nwin:
|
| 27 |
-
j = i
|
| 28 |
-
while j < nwin and silent[j] == silent[i]:
|
| 29 |
-
j += 1
|
| 30 |
-
if silent[i] and (i == 0 or (j - i) * 0.05 > 2.0):
|
| 31 |
-
segments.append({"start": round(i * 0.05, 3), "end": round(j * 0.05, 3), "duration": round((j - i) * 0.05, 3)})
|
| 32 |
-
i = j
|
| 33 |
-
|
| 34 |
-
original = n / rate
|
| 35 |
-
removed = sum(s["duration"] for s in segments)
|
| 36 |
-
report = {
|
| 37 |
-
"original_duration_seconds": round(original, 3),
|
| 38 |
-
"compressed_duration_seconds": round(original - removed, 3),
|
| 39 |
-
"removed_duration_seconds": round(removed, 3),
|
| 40 |
-
"compression_percentage": round(removed / original * 100, 2),
|
| 41 |
-
"segments_removed": segments,
|
| 42 |
-
}
|
| 43 |
-
json.dump(report, open("compression_report.json", "w"), indent=2)
|
| 44 |
-
print(len(segments), "segments removed")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/med3_sprite_count.py
DELETED
|
@@ -1,44 +0,0 @@
|
|
| 1 |
-
"""Oracle for med3_sprite_count: grayscale template matching with a mean-abs-diff threshold."""
|
| 2 |
-
import csv
|
| 3 |
-
import glob
|
| 4 |
-
import os
|
| 5 |
-
|
| 6 |
-
import numpy as np
|
| 7 |
-
from numpy.lib.stride_tricks import sliding_window_view
|
| 8 |
-
from PIL import Image
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
def gray(path):
|
| 12 |
-
return np.asarray(Image.open(path).convert("L"), dtype=np.float32)
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
notes = open("notes.md").read() if os.path.exists("notes.md") else ""
|
| 16 |
-
templates = {}
|
| 17 |
-
for name in ("coin", "enemy", "turtle"):
|
| 18 |
-
t = gray(f"sprites/{name}.png")
|
| 19 |
-
templates[name] = [t, t[:, ::-1]] if "mirrored" in notes else [t]
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def count(frame, variants):
|
| 23 |
-
h, w = variants[0].shape
|
| 24 |
-
windows = sliding_window_view(frame, (h, w)) # only windows fully inside the frame
|
| 25 |
-
hits = np.zeros(windows.shape[:2], dtype=bool)
|
| 26 |
-
for t in variants:
|
| 27 |
-
hits |= np.abs(windows - t).mean(axis=(2, 3)) < 10
|
| 28 |
-
found = []
|
| 29 |
-
for y, x in zip(*np.nonzero(hits)):
|
| 30 |
-
if all(abs(y - fy) >= h or abs(x - fx) >= w for fy, fx in found):
|
| 31 |
-
found.append((y, x)) # neighbouring hits belong to the same object
|
| 32 |
-
return len(found)
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
rows = []
|
| 36 |
-
for path in sorted(glob.glob("frames/frame_*.png")):
|
| 37 |
-
frame = gray(path)
|
| 38 |
-
rows.append([os.path.basename(path)] + [count(frame, templates[n]) for n in ("coin", "enemy", "turtle")])
|
| 39 |
-
|
| 40 |
-
with open("counting_results.csv", "w", newline="") as f:
|
| 41 |
-
writer = csv.writer(f)
|
| 42 |
-
writer.writerow(["frame_id", "coins", "enemies", "turtles"])
|
| 43 |
-
writer.writerows(rows)
|
| 44 |
-
print(len(rows), "frames; totals", [sum(r[i] for r in rows) for i in (1, 2, 3)])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/med3_subtitle_retime.py
DELETED
|
@@ -1,43 +0,0 @@
|
|
| 1 |
-
"""Oracle for med3_subtitle_retime: map every cue time through the union of the active cuts."""
|
| 2 |
-
import csv
|
| 3 |
-
import os
|
| 4 |
-
import re
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
def ms(s):
|
| 8 |
-
h, m, sec, milli = map(int, re.search(r"(\d+):(\d\d):(\d\d)[,.](\d{3})", s).groups())
|
| 9 |
-
return ((h * 60 + m) * 60 + sec) * 1000 + milli
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def fmt(t):
|
| 13 |
-
return f"{t // 3600000:02d}:{t // 60000 % 60:02d}:{t // 1000 % 60:02d},{t % 1000:03d}"
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
notes = open("edit_notes.md").read() if os.path.exists("edit_notes.md") else ""
|
| 17 |
-
reverted = set(re.findall(r"(C\d+) was reverted", notes))
|
| 18 |
-
min_len = 500 if "shorter than 500 ms" in notes else 1
|
| 19 |
-
|
| 20 |
-
cuts = sorted([ms(r["start"]), ms(r["end"])] for r in csv.DictReader(open("edl.csv")) if r["cut_id"] not in reverted)
|
| 21 |
-
union = []
|
| 22 |
-
for s, e in cuts: # merge overlapping cuts so no footage is removed twice
|
| 23 |
-
if union and s <= union[-1][1]:
|
| 24 |
-
union[-1][1] = max(union[-1][1], e)
|
| 25 |
-
else:
|
| 26 |
-
union.append([s, e])
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def shift(t):
|
| 30 |
-
return t - sum(min(t, e) - s for s, e in union if t > s)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
text = open("episode.srt", encoding="utf-8-sig").read().replace("\r\n", "\n")
|
| 34 |
-
out = []
|
| 35 |
-
for block in re.split(r"\n\s*\n", text.strip()):
|
| 36 |
-
lines = block.split("\n")
|
| 37 |
-
start, end = (shift(ms(p)) for p in lines[1].split("-->"))
|
| 38 |
-
if end - start >= min_len:
|
| 39 |
-
out.append(f"{len(out) + 1}\n{fmt(start)} --> {fmt(end)}\n" + "\n".join(lines[2:]) + "\n")
|
| 40 |
-
|
| 41 |
-
os.makedirs("output", exist_ok=True)
|
| 42 |
-
open("output/episode.srt", "w").write("\n".join(out))
|
| 43 |
-
print(len(union), "cut spans;", len(out), "cues written")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/off3_ar_recon.py
DELETED
|
@@ -1,39 +0,0 @@
|
|
| 1 |
-
"""Oracle for off3_ar_recon: credit notes first, then payments top to bottom, memo corrections applied."""
|
| 2 |
-
import csv
|
| 3 |
-
import os
|
| 4 |
-
import re
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
def rows(name):
|
| 8 |
-
with open(name, newline="") as fh:
|
| 9 |
-
return list(csv.DictReader(fh))
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def cents(s):
|
| 13 |
-
return round(float(s) * 100)
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
inv = {r["invoice"]: r for r in rows("invoices.csv")}
|
| 17 |
-
bal = {i: cents(r["amount"]) for i, r in inv.items()}
|
| 18 |
-
void, moved = None, {}
|
| 19 |
-
if os.path.exists("controller_memo.md"):
|
| 20 |
-
memo = open("controller_memo.md").read()
|
| 21 |
-
void = re.search(r"(INV-\d+) was voided", memo).group(1)
|
| 22 |
-
m = re.search(r"payment of ([\d.]+) received on (\S+) .*? to (INV-\d+)", memo)
|
| 23 |
-
moved = {(m.group(2), cents(m.group(1))): [m.group(3)]}
|
| 24 |
-
if os.path.exists("credit_notes.csv"):
|
| 25 |
-
for r in rows("credit_notes.csv"):
|
| 26 |
-
bal[r["invoice"]] = max(0, bal[r["invoice"]] - cents(r["amount"]))
|
| 27 |
-
for r in rows("payments.csv"):
|
| 28 |
-
named = [f"INV-{n}" for n in re.findall(r"\d+", r["memo"])] if "memo" in r else [r["invoice"]]
|
| 29 |
-
left = cents(r["amount"])
|
| 30 |
-
for i in moved.get((r["date"], left), named):
|
| 31 |
-
take = min(left, bal[i])
|
| 32 |
-
bal[i] -= take
|
| 33 |
-
left -= take
|
| 34 |
-
with open("balances.csv", "w") as fh:
|
| 35 |
-
fh.write("invoice,customer,balance,status\n")
|
| 36 |
-
for i, b in bal.items():
|
| 37 |
-
status = "paid" if b == 0 else "open" if b == cents(inv[i]["amount"]) else "partial"
|
| 38 |
-
if i != void:
|
| 39 |
-
fh.write(f"{i},{inv[i]['customer']},{b / 100:.2f},{status}\n")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/off3_meeting_slot.py
DELETED
|
@@ -1,44 +0,0 @@
|
|
| 1 |
-
"""Oracle for off3_meeting_slot: earliest quarter-hour UTC start inside everyone's 09-17 local and free."""
|
| 2 |
-
import csv
|
| 3 |
-
import json
|
| 4 |
-
import os
|
| 5 |
-
import re
|
| 6 |
-
from datetime import datetime, time, timedelta
|
| 7 |
-
|
| 8 |
-
people = {}
|
| 9 |
-
for r in csv.DictReader(open("people.csv")):
|
| 10 |
-
h, m = r["utc_offset"][4:].split(":")
|
| 11 |
-
sign = -1 if r["utc_offset"][3] == "-" else 1
|
| 12 |
-
people[r["person"]] = sign * timedelta(hours=int(h), minutes=int(m))
|
| 13 |
-
reader = csv.reader(open("busy.csv"))
|
| 14 |
-
in_utc = next(reader)[2] == "start_utc"
|
| 15 |
-
busy = {p: [] for p in people}
|
| 16 |
-
for p, d, s, e in reader:
|
| 17 |
-
b0, b1 = datetime.fromisoformat(f"{d} {s}"), datetime.fromisoformat(f"{d} {e}")
|
| 18 |
-
shift = people[p] if in_utc else timedelta(0)
|
| 19 |
-
busy[p].append((b0 + shift, b1 + shift))
|
| 20 |
-
ooo, lunch = {}, set()
|
| 21 |
-
if os.path.exists("calendar_notes.md"):
|
| 22 |
-
for line in open("calendar_notes.md"):
|
| 23 |
-
m = re.match(r"- (\w+) is out of office .* (\d{4}-\d\d-\d\d)", line)
|
| 24 |
-
if m:
|
| 25 |
-
ooo[m.group(1)] = m.group(2)
|
| 26 |
-
if re.match(r"- \w+ takes lunch", line):
|
| 27 |
-
lunch.add(line.split()[1])
|
| 28 |
-
|
| 29 |
-
dur, t = timedelta(minutes=30), datetime(2026, 11, 2)
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
def works(p, off):
|
| 33 |
-
s = t + off
|
| 34 |
-
e, day = s + dur, s.date()
|
| 35 |
-
blocks = busy[p] + ([(datetime.combine(day, time(12)), datetime.combine(day, time(13)))] if p in lunch else [])
|
| 36 |
-
if str(day) == ooo.get(p) or s < datetime.combine(day, time(9)) or e > datetime.combine(day, time(17)):
|
| 37 |
-
return False
|
| 38 |
-
return all(e <= b0 or s >= b1 for b0, b1 in blocks)
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
while not all(works(p, off) for p, off in people.items()):
|
| 42 |
-
t += timedelta(minutes=15)
|
| 43 |
-
with open("meeting.json", "w") as fh:
|
| 44 |
-
json.dump({"start_utc": f"{t:%Y-%m-%dT%H:%M}", "end_utc": f"{t + dur:%Y-%m-%dT%H:%M}"}, fh)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/off3_pdf_xlsx_diff.py
DELETED
|
@@ -1,36 +0,0 @@
|
|
| 1 |
-
"""Oracle for off3_pdf_xlsx_diff: PDF table (pdfplumber) vs workbook (openpyxl), matched by ID."""
|
| 2 |
-
import json
|
| 3 |
-
|
| 4 |
-
import openpyxl
|
| 5 |
-
import pdfplumber
|
| 6 |
-
|
| 7 |
-
NUMERIC = ("Salary", "Years", "Score")
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
def value(field, v):
|
| 11 |
-
if field in NUMERIC: # the PDF may print salaries as $52,300
|
| 12 |
-
x = float(str(v).replace("$", "").replace(",", ""))
|
| 13 |
-
return x if field == "Score" else int(x)
|
| 14 |
-
return str(v).strip() # trailing spaces are not changes
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
old, cols = {}, None
|
| 18 |
-
with pdfplumber.open("employees_backup.pdf") as pdf:
|
| 19 |
-
for page in pdf.pages:
|
| 20 |
-
for row in page.extract_table():
|
| 21 |
-
if row[0] == "ID": # the header repeats on every page
|
| 22 |
-
cols = row
|
| 23 |
-
else:
|
| 24 |
-
old[row[0]] = dict(zip(cols, row))
|
| 25 |
-
rows = list(openpyxl.load_workbook("employees_current.xlsx")["Employees"].iter_rows(values_only=True))
|
| 26 |
-
new = {r[0]: dict(zip(rows[0], r)) for r in rows[1:]}
|
| 27 |
-
|
| 28 |
-
mods = []
|
| 29 |
-
for i in sorted(set(old) & set(new)):
|
| 30 |
-
for f in cols[1:]:
|
| 31 |
-
a, b = value(f, old[i][f]), value(f, new[i][f])
|
| 32 |
-
if a != b:
|
| 33 |
-
mods.append({"id": i, "field": f, "old_value": a, "new_value": b})
|
| 34 |
-
report = {"deleted_employees": sorted(set(old) - set(new)), "modified_employees": mods}
|
| 35 |
-
with open("diff_report.json", "w") as fh:
|
| 36 |
-
json.dump(report, fh, indent=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/sci3_kinetics_fit.py
DELETED
|
@@ -1,38 +0,0 @@
|
|
| 1 |
-
# sci3_kinetics_fit: order by R^2, k, half-life, Arrhenius
|
| 2 |
-
import csv
|
| 3 |
-
import glob
|
| 4 |
-
import json
|
| 5 |
-
import math
|
| 6 |
-
import os
|
| 7 |
-
import re
|
| 8 |
-
from statistics import correlation, linear_regression
|
| 9 |
-
|
| 10 |
-
notes = open("data/lab_notes.txt").read() if os.path.exists("data/lab_notes.txt") else ""
|
| 11 |
-
bad = set(re.findall(r"Sample (S\d+) in (\S+\.csv)", notes))
|
| 12 |
-
SCALE = {"time_s": 1, "time_min": 60, "conc_M": 1, "conc_mM": 0.001}
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def ols(t, y): # slope and R^2
|
| 16 |
-
return linear_regression(t, y).slope, correlation(t, y) ** 2
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
fits = []
|
| 20 |
-
for path in sorted(glob.glob("data/run*.csv")): # run_289K.csv sorts before run_302K.csv
|
| 21 |
-
name = os.path.basename(path)
|
| 22 |
-
(_, tk, ck, *_), *body = csv.reader(open(path))
|
| 23 |
-
t, c = zip(*[(float(x) * SCALE[tk], float(y) * SCALE[ck]) for s, x, y, *flag in body
|
| 24 |
-
if "<LOD" not in [y] + flag and (s, name) not in bad])
|
| 25 |
-
s1, r1 = ols(t, [math.log(x) for x in c])
|
| 26 |
-
s2, r2 = ols(t, [1 / x for x in c])
|
| 27 |
-
fits.append((name, 1, -s1, c[0]) if r1 > r2 else (name, 2, s2, c[0]))
|
| 28 |
-
|
| 29 |
-
name, order, k, c0 = fits[0]
|
| 30 |
-
if not notes: # stated first order
|
| 31 |
-
report = {"k_per_s": k, "half_life_s": math.log(2) / k}
|
| 32 |
-
elif len(fits) == 1:
|
| 33 |
-
report = {"order": order, "k": k, "half_life_s": math.log(2) / k if order == 1 else 1 / (k * c0)}
|
| 34 |
-
else:
|
| 35 |
-
lo, hi, k_hi = int(name[4:7]), int(fits[1][0][4:7]), fits[1][2]
|
| 36 |
-
ea = 8.314 * math.log(k_hi / k) / (1 / lo - 1 / hi) / 1000
|
| 37 |
-
report = {"order": order, "k_low": k, "k_high": k_hi, "ea_kj_per_mol": ea}
|
| 38 |
-
json.dump(report, open("kinetics_report.json", "w"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/sci3_lightcurve_period.py
DELETED
|
@@ -1,38 +0,0 @@
|
|
| 1 |
-
# oracle for sci3_lightcurve_period: filter, running-median detrend, box search over the stated grid
|
| 2 |
-
import math
|
| 3 |
-
import os
|
| 4 |
-
import re
|
| 5 |
-
|
| 6 |
-
rows = [list(map(float, ln.split())) for ln in open("data/lc.txt") if not ln.startswith("#")]
|
| 7 |
-
rows = [r for r in rows if r[2] == 0]
|
| 8 |
-
if os.path.exists("data/README.md"):
|
| 9 |
-
a, b = map(float, re.search(r"MJD ([\d.]+) and ([\d.]+)", open("data/README.md").read()).groups())
|
| 10 |
-
rows = [r for r in rows if not a <= r[0] <= b]
|
| 11 |
-
t = [r[0] for r in rows]
|
| 12 |
-
f = [r[1] for r in rows]
|
| 13 |
-
resid = []
|
| 14 |
-
for i in range(len(f)): # divide by a running median ~0.75 d wide (27 points each side)
|
| 15 |
-
win = sorted(f[max(0, i - 27):i + 28])
|
| 16 |
-
resid.append(f[i] / win[len(win) // 2] - 1)
|
| 17 |
-
|
| 18 |
-
DUR, SUB = 0.10, 4 # box days (stated 0.08-0.12; 0.10 finds all), sub-bins per box
|
| 19 |
-
t = [x - t[0] for x in t]
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def power(p):
|
| 23 |
-
"""Best box signal at trial period p: phase-fold into bins, slide a box of SUB bins."""
|
| 24 |
-
nb = int(round(SUB * p / DUR))
|
| 25 |
-
c, s, n = nb / p, [0.0] * nb, [0] * nb
|
| 26 |
-
for b, r in zip([int(x * c) % nb for x in t], resid):
|
| 27 |
-
s[b] += r
|
| 28 |
-
n[b] += 1
|
| 29 |
-
s, n = s + s[:SUB], n + n[:SUB]
|
| 30 |
-
return max(-sum(s[b:b + SUB]) / math.sqrt(max(sum(n[b:b + SUB]), 1)) for b in range(nb))
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
coarse = max((k / 1000 for k in range(1000, 5001, 2)), key=power) # every other grid step
|
| 34 |
-
period = max((coarse + k / 10000 for k in range(-20, 21)), key=power) # then refine
|
| 35 |
-
|
| 36 |
-
with open("period.txt", "w") as fh:
|
| 37 |
-
fh.write(f"{period:.5f}\n")
|
| 38 |
-
print(f"{period:.5f}", "power", round(power(period), 5), "points", len(t))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/sci3_stoich_batch.py
DELETED
|
@@ -1,46 +0,0 @@
|
|
| 1 |
-
# oracle for sci3_stoich_batch: lot lookup, molar masses, limiting reagent, yields
|
| 2 |
-
import csv
|
| 3 |
-
import json
|
| 4 |
-
import re
|
| 5 |
-
|
| 6 |
-
mass = {r["element"]: float(r["mass"]) for r in csv.DictReader(open("data/atomic_masses.csv"))}
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
def molar(formula):
|
| 10 |
-
total = 0.0
|
| 11 |
-
for part in formula.split("*"): # hydrate: CuSO4*5H2O
|
| 12 |
-
n, body = re.match(r"(\d*)(.*)", part).groups()
|
| 13 |
-
while "(" in body: # (SO4)3 -> SO4SO4SO4
|
| 14 |
-
body = re.sub(r"\(([^()]*)\)(\d*)", lambda m: m.group(1) * int(m.group(2) or 1), body)
|
| 15 |
-
atoms = re.findall(r"([A-Z][a-z]?)(\d*)", body)
|
| 16 |
-
total += int(n or 1) * sum(mass[e] * int(k or 1) for e, k in atoms)
|
| 17 |
-
return total
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
lots = {}
|
| 21 |
-
for r in csv.DictReader(open("data/reagents.csv")): # latest certified row per lot wins
|
| 22 |
-
if r["lot"] not in lots or r["certified"] > lots[r["lot"]]["certified"]:
|
| 23 |
-
lots[r["lot"]] = r
|
| 24 |
-
|
| 25 |
-
text = open("data/batch.txt").read()
|
| 26 |
-
left, right = re.search(r"Reaction: (.+)", text).group(1).split(" -> ")
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def side(s):
|
| 30 |
-
return {f: int(c or 1) for c, f in re.findall(r"(?:(\d+) )?(\S+)", s) if f != "+"}
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
coef, prod_coef = side(left), side(right)
|
| 34 |
-
equiv = {}
|
| 35 |
-
for grams, formula, lot in re.findall(r"Charged: ([\d.]+) g (\S+) from lot (\S+)", text):
|
| 36 |
-
pure = float(grams) * float(lots[lot]["purity_pct"]) / 100
|
| 37 |
-
equiv[formula] = pure / molar(formula) / coef[formula]
|
| 38 |
-
iso, product = re.search(r"Isolated: ([\d.]+) g (\S+)", text).groups()
|
| 39 |
-
|
| 40 |
-
limiting = min(equiv, key=equiv.get)
|
| 41 |
-
mm = molar(product)
|
| 42 |
-
theo = equiv[limiting] * prod_coef[product] * mm
|
| 43 |
-
report = {"limiting_reagent": limiting, "product_molar_mass": mm, "theoretical_yield_g": theo,
|
| 44 |
-
"percent_yield": float(iso) / theo * 100}
|
| 45 |
-
json.dump(report, open("batch_report.json", "w"), indent=1)
|
| 46 |
-
print(report)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/sec3_auth_triage.py
DELETED
|
@@ -1,37 +0,0 @@
|
|
| 1 |
-
# oracle: sec3_auth_triage. Count failed SSH passwords per source inside a 10-minute window.
|
| 2 |
-
import ipaddress
|
| 3 |
-
import os
|
| 4 |
-
import re
|
| 5 |
-
from collections import defaultdict
|
| 6 |
-
|
| 7 |
-
K, WINDOW = 5, 600
|
| 8 |
-
notes = open("README.md").read() if os.path.exists("README.md") else ""
|
| 9 |
-
allow = [ipaddress.ip_network(n) for n in re.findall(r"\d+\.\d+\.\d+\.\d+/\d+", notes)]
|
| 10 |
-
|
| 11 |
-
fails = defaultdict(list)
|
| 12 |
-
for name in ("auth.log.1", "auth.log"): # older file first
|
| 13 |
-
if not os.path.exists(name):
|
| 14 |
-
continue
|
| 15 |
-
for line in open(name):
|
| 16 |
-
clock, _, msg = line.rstrip("\n").partition(" ")
|
| 17 |
-
h, m, s = map(int, clock.split(":"))
|
| 18 |
-
t = h * 3600 + m * 60 + s
|
| 19 |
-
rep = re.match(r"message repeated (\d+) times: \[ Failed password for .* from (\S+?)\]$", msg)
|
| 20 |
-
if rep:
|
| 21 |
-
fails[rep.group(2)] += [t] * int(rep.group(1))
|
| 22 |
-
continue
|
| 23 |
-
hit = re.match(r"Failed password for .* from (\S+)$", msg)
|
| 24 |
-
if hit:
|
| 25 |
-
fails[hit.group(1)].append(t)
|
| 26 |
-
|
| 27 |
-
if not fails:
|
| 28 |
-
raise SystemExit("no failed attempts parsed")
|
| 29 |
-
blocked = []
|
| 30 |
-
for ip, ts in fails.items():
|
| 31 |
-
ts.sort()
|
| 32 |
-
if any(ts[i + K - 1] - ts[i] <= WINDOW for i in range(len(ts) - K + 1)):
|
| 33 |
-
if not any(ipaddress.ip_address(ip) in net for net in allow):
|
| 34 |
-
blocked.append(ip)
|
| 35 |
-
with open("blocked.txt", "w") as f:
|
| 36 |
-
f.write("".join(ip + "\n" for ip in sorted(blocked)))
|
| 37 |
-
print(len(fails), "sources with failures,", len(blocked), "blocked:", blocked)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/sec3_exfil_flows.py
DELETED
|
@@ -1,35 +0,0 @@
|
|
| 1 |
-
# oracle: sec3_exfil_flows. Big, unapproved, outbound flows that start outside office hours.
|
| 2 |
-
import csv
|
| 3 |
-
import ipaddress
|
| 4 |
-
import json
|
| 5 |
-
import os
|
| 6 |
-
|
| 7 |
-
DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
| 8 |
-
policy = json.load(open("policy.json"))
|
| 9 |
-
approved = list(policy.get("allowlist", []))
|
| 10 |
-
if os.path.exists("allowlist.txt"):
|
| 11 |
-
approved += [ln.strip() for ln in open("allowlist.txt") if ln.strip() and not ln.startswith("#")]
|
| 12 |
-
approved = [ipaddress.ip_network(a) for a in approved]
|
| 13 |
-
internal = [ipaddress.ip_network(n) for n in policy.get("internal_networks", [])]
|
| 14 |
-
offset = policy.get("office_utc_offset_hours", 0) * 60 # local = UTC + offset (README, L3)
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def minutes(hhmm):
|
| 18 |
-
h, m = hhmm.split(":")
|
| 19 |
-
return int(h) * 60 + int(m)
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
start, end = (minutes(x) for x in policy["business_hours"])
|
| 23 |
-
alerts = []
|
| 24 |
-
for r in csv.DictReader(open("flows.csv", newline="")):
|
| 25 |
-
t = (DAYS.index(r["day"]) * 1440 + minutes(r["time"]) + offset) % (7 * 1440)
|
| 26 |
-
day, minute = DAYS[t // 1440], t % 1440
|
| 27 |
-
off_hours = day not in policy["business_days"] or not start <= minute < end
|
| 28 |
-
dst = ipaddress.ip_address(r["dst"])
|
| 29 |
-
if (float(r["mb_out"]) > policy["threshold_mb"] and off_hours
|
| 30 |
-
and not any(dst in n for n in approved) and not any(dst in n for n in internal)):
|
| 31 |
-
alerts.append(int(r["flow"]))
|
| 32 |
-
alerts.sort()
|
| 33 |
-
with open("alerts.json", "w") as f:
|
| 34 |
-
json.dump(alerts, f)
|
| 35 |
-
print(len(alerts), "alerts:", alerts[:10])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/sec3_fw_verdicts.py
DELETED
|
@@ -1,49 +0,0 @@
|
|
| 1 |
-
# oracle: sec3_fw_verdicts. First matching rule by ascending rule_no; default deny is rule 0.
|
| 2 |
-
import csv
|
| 3 |
-
import ipaddress
|
| 4 |
-
import os
|
| 5 |
-
|
| 6 |
-
groups = {}
|
| 7 |
-
if os.path.exists("groups.txt"):
|
| 8 |
-
for line in open("groups.txt"):
|
| 9 |
-
if line.strip() and not line.startswith("#"):
|
| 10 |
-
name, _, nets = line.partition(":")
|
| 11 |
-
groups["@" + name.strip()] = nets.split()
|
| 12 |
-
|
| 13 |
-
rules = []
|
| 14 |
-
for r in csv.DictReader(open("rules.csv", newline="")):
|
| 15 |
-
if r.get("enabled", "yes") != "yes":
|
| 16 |
-
continue
|
| 17 |
-
src = r["src"]
|
| 18 |
-
nets = None if src == "any" else [ipaddress.ip_network(n) for n in groups.get(src, [src])]
|
| 19 |
-
ports = None
|
| 20 |
-
if r["ports"] != "any":
|
| 21 |
-
ports = set()
|
| 22 |
-
for part in r["ports"].split(";"):
|
| 23 |
-
lo, _, hi = part.partition("-")
|
| 24 |
-
ports.update(range(int(lo), int(hi or lo) + 1))
|
| 25 |
-
rules.append((int(r["rule_no"]), r["action"], r["proto"], nets, ports))
|
| 26 |
-
rules.sort(key=lambda r: r[0])
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def decide(c):
|
| 30 |
-
ip = ipaddress.ip_address(c["src_ip"])
|
| 31 |
-
port = c["dst_port"].strip()
|
| 32 |
-
for no, action, proto, nets, ports in rules:
|
| 33 |
-
if proto not in ("any", c["proto"]):
|
| 34 |
-
continue
|
| 35 |
-
if nets is not None and not any(ip in n for n in nets):
|
| 36 |
-
continue
|
| 37 |
-
if ports is not None and (not port or int(port) not in ports):
|
| 38 |
-
continue
|
| 39 |
-
return action, no
|
| 40 |
-
return "deny", 0
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
conns = list(csv.DictReader(open("connections.csv", newline="")))
|
| 44 |
-
with open("verdicts.csv", "w", newline="") as f:
|
| 45 |
-
w = csv.writer(f)
|
| 46 |
-
w.writerow(["id", "verdict", "rule"])
|
| 47 |
-
for c in conns:
|
| 48 |
-
w.writerow([c["id"], *decide(c)])
|
| 49 |
-
print(len(rules), "rules loaded,", len(conns), "connections")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
components/dnakhla/upstream/terminal_desk/oracles/sw3_dep_lock.py
DELETED
|
@@ -1,51 +0,0 @@
|
|
| 1 |
-
"""Oracle for sw3_dep_lock: brute-force every pick of the requested packages and keep the preferred valid one."""
|
| 2 |
-
import itertools
|
| 3 |
-
import os
|
| 4 |
-
import re
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
def vkey(v):
|
| 8 |
-
return tuple(int(x) for x in v.split("."))
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
def parse(spec):
|
| 12 |
-
m = re.match(r"([a-z]+)(.*)", spec)
|
| 13 |
-
conds = [re.match(r"(>=|<|!=|==)(.+)", c).groups() for c in m[2].split(",") if c]
|
| 14 |
-
return m[1], [(op, vkey(w)) for op, w in conds]
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def ok(v, conds):
|
| 18 |
-
k = vkey(v)
|
| 19 |
-
tests = {">=": k.__ge__, "<": k.__lt__, "!=": k.__ne__, "==": k.__eq__}
|
| 20 |
-
return all(tests[op](w) for op, w in conds)
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
wanted = [parse(ln.strip()) for ln in open("requirements.txt") if ln.strip()]
|
| 24 |
-
pkgs = [n for n, _ in wanted]
|
| 25 |
-
yanked = set()
|
| 26 |
-
if os.path.exists("yanked.txt"):
|
| 27 |
-
yanked = {tuple(ln.split()) for ln in open("yanked.txt") if ln.strip() and not ln.startswith("#")}
|
| 28 |
-
|
| 29 |
-
releases = {} # package -> {version: [(dep, conds)]}
|
| 30 |
-
for ln in open("index.txt"):
|
| 31 |
-
if not ln.strip() or ln.startswith("#"):
|
| 32 |
-
continue
|
| 33 |
-
name, ver, req = ln.split()
|
| 34 |
-
if name in pkgs and (name, ver) not in yanked:
|
| 35 |
-
releases.setdefault(name, {})[ver] = [] if req == "-" else [parse(r) for r in req.split(";")]
|
| 36 |
-
|
| 37 |
-
best = None
|
| 38 |
-
for combo in itertools.product(*(sorted(releases[p], key=vkey) for p in pkgs)):
|
| 39 |
-
pick = dict(zip(pkgs, combo))
|
| 40 |
-
if not all(ok(pick[n], c) for n, c in wanted):
|
| 41 |
-
continue
|
| 42 |
-
if not all(ok(pick[d], c) for p in pkgs for d, c in releases[p][pick[p]]):
|
| 43 |
-
continue
|
| 44 |
-
score = tuple(vkey(pick[p]) for p in pkgs)
|
| 45 |
-
if best is None or score > best[0]:
|
| 46 |
-
best = (score, pick)
|
| 47 |
-
|
| 48 |
-
pick = best[1]
|
| 49 |
-
with open("lock.txt", "w") as fh:
|
| 50 |
-
fh.write("".join(f"{p}=={pick[p]}\n" for p in sorted(pick)))
|
| 51 |
-
print(open("lock.txt").read())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|