-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathschema_support.rs
More file actions
2551 lines (2426 loc) · 101 KB
/
Copy pathschema_support.rs
File metadata and controls
2551 lines (2426 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::*;
#[derive(Debug, Clone, Default)]
pub(super) struct CreateContext {
num_vertices: Option<usize>,
num_edges: Option<usize>,
num_arcs: Option<usize>,
parsed_fields: BTreeMap<String, serde_json::Value>,
}
impl CreateContext {
pub(super) fn with_field(mut self, name: &str, value: serde_json::Value) -> Self {
self.parsed_fields.insert(name.to_string(), value);
self
}
fn seed_field<T: Serialize>(&mut self, name: &str, value: T) -> Result<()> {
let value = serde_json::to_value(value)?;
if name == "num_vertices" {
self.num_vertices = value.as_u64().and_then(|raw| usize::try_from(raw).ok());
}
self.parsed_fields.insert(name.to_string(), value);
Ok(())
}
fn usize_field(&self, name: &str) -> Option<usize> {
self.parsed_fields
.get(name)
.and_then(serde_json::Value::as_u64)
.and_then(|value| usize::try_from(value).ok())
}
fn f64_field(&self, name: &str) -> Option<f64> {
self.parsed_fields
.get(name)
.and_then(serde_json::Value::as_f64)
}
fn remember(&mut self, name: &str, concrete_type: &str, value: &serde_json::Value) {
self.parsed_fields.insert(name.to_string(), value.clone());
match normalize_type_name(concrete_type).as_str() {
"SimpleGraph" => {
self.num_vertices = value
.get("num_vertices")
.and_then(serde_json::Value::as_u64)
.and_then(|raw| usize::try_from(raw).ok());
self.num_edges = value
.get("edges")
.and_then(serde_json::Value::as_array)
.map(Vec::len);
}
"DirectedGraph" => {
self.num_vertices = value
.get("num_vertices")
.and_then(serde_json::Value::as_u64)
.and_then(|raw| usize::try_from(raw).ok());
self.num_arcs = value
.get("arcs")
.and_then(serde_json::Value::as_array)
.map(Vec::len);
}
"KingsSubgraph" | "TriangularSubgraph" => {
self.num_vertices = value
.get("positions")
.and_then(serde_json::Value::as_array)
.map(Vec::len);
}
"UnitDiskGraph" => {
self.num_vertices = value
.get("positions")
.and_then(serde_json::Value::as_array)
.map(Vec::len);
self.num_edges = value
.get("edges")
.and_then(serde_json::Value::as_array)
.map(Vec::len);
}
_ => {}
}
}
}
pub(super) fn create_schema_driven(
args: &CreateArgs,
canonical: &str,
resolved_variant: &BTreeMap<String, String>,
) -> Result<Option<(serde_json::Value, BTreeMap<String, String>)>> {
if !schema_driven_supported_problem(canonical) {
return Ok(None);
}
let Some(schema) = collect_schemas()
.into_iter()
.find(|schema| schema.name == canonical)
else {
return Ok(None);
};
let Some(variant_entry) =
problemreductions::registry::find_variant_entry(canonical, resolved_variant)
else {
return Ok(None);
};
let graph_type = resolved_graph_type(resolved_variant);
let is_geometry = matches!(
graph_type,
"KingsSubgraph" | "TriangularSubgraph" | "UnitDiskGraph"
);
let flag_map = args.flag_map();
let mut context = CreateContext::default();
seed_schema_context_from_cli(args, graph_type, &mut context)?;
validate_schema_driven_semantics(args, canonical, resolved_variant, &serde_json::Value::Null)
.map_err(|error| with_schema_usage(error, canonical, resolved_variant))?;
let mut json_map = serde_json::Map::new();
for field in &schema.fields {
let concrete_type = resolve_schema_field_type(&field.type_name, resolved_variant);
let flag_keys =
schema_field_flag_keys(canonical, &field.name, &field.type_name, is_geometry);
let raw_value = get_schema_flag_value(&flag_map, &flag_keys);
let value = if !schema_field_requires_derived_input(&field.name, &concrete_type) {
if let Some(raw_value) = raw_value.clone() {
match parse_schema_field_value(
args,
canonical,
&concrete_type,
&field.name,
&raw_value,
&context,
) {
Ok(value) => value,
Err(error) => {
return Err(with_schema_usage(error, canonical, resolved_variant))
}
}
} else if let Some(derived) =
derive_schema_field_value(args, canonical, &field.name, &concrete_type, &context)?
{
derived
} else {
return Err(with_schema_usage(
missing_schema_field_error(
canonical,
&field.name,
&field.type_name,
is_geometry,
),
canonical,
resolved_variant,
));
}
} else if let Some(derived) =
derive_schema_field_value(args, canonical, &field.name, &concrete_type, &context)?
{
derived
} else if let Some(raw_value) = raw_value {
match parse_schema_field_value(
args,
canonical,
&concrete_type,
&field.name,
&raw_value,
&context,
) {
Ok(value) => value,
Err(error) => return Err(with_schema_usage(error, canonical, resolved_variant)),
}
} else {
return Err(with_schema_usage(
missing_schema_field_error(canonical, &field.name, &field.type_name, is_geometry),
canonical,
resolved_variant,
));
};
context.remember(&field.name, &concrete_type, &value);
json_map.insert(field.name.clone(), value);
}
// KColoring/KN stores the number of colors at runtime in `num_colors`.
// The schema only declares `graph`, so inject `num_colors` from --k for KN.
if canonical == "KColoring" && resolved_variant.get("k").map(|s| s.as_str()) == Some("KN") {
if let Some(k) = args.k {
json_map.insert("num_colors".to_string(), serde_json::json!(k));
}
}
// Decision<P> types serialize as {inner: {graph, weights, ...}, bound} but schema
// fields are flat (graph, weights, bound). Restructure when the canonical name
// indicates a Decision wrapper.
let data = if canonical.starts_with("Decision") {
let bound = json_map
.remove("bound")
.expect("Decision types require a bound field");
let mut outer = serde_json::Map::new();
outer.insert("inner".to_string(), serde_json::Value::Object(json_map));
outer.insert("bound".to_string(), bound);
serde_json::Value::Object(outer)
} else {
serde_json::Value::Object(json_map)
};
validate_schema_driven_semantics(args, canonical, resolved_variant, &data)
.map_err(|error| with_schema_usage(error, canonical, resolved_variant))?;
(variant_entry.factory)(data.clone()).map_err(|error| {
with_schema_usage(
anyhow::anyhow!(
"Schema-driven factory rejected generated data for {canonical}: {error}"
),
canonical,
resolved_variant,
)
})?;
Ok(Some((data, resolved_variant.clone())))
}
pub(super) fn missing_schema_field_error(
canonical: &str,
field_name: &str,
field_type: &str,
is_geometry: bool,
) -> anyhow::Error {
let display = problem_help_flag_name(canonical, field_name, field_type, is_geometry);
let flags: Vec<String> = display
.split('/')
.filter_map(|part| {
let trimmed = part.trim().trim_start_matches("--");
(!trimmed.is_empty()).then(|| format!("--{trimmed}"))
})
.collect();
let requirement = match flags.as_slice() {
[] => format!("--{}", field_name.replace('_', "-")),
[flag] => flag.clone(),
[first, second] => format!("{first} or {second}"),
_ => {
let last = flags.last().cloned().unwrap_or_default();
format!("{}, or {}", flags[..flags.len() - 1].join(", "), last)
}
};
anyhow::anyhow!("{canonical} requires {requirement}")
}
pub(super) fn parse_schema_field_value(
args: &CreateArgs,
canonical: &str,
concrete_type: &str,
field_name: &str,
raw: &str,
context: &CreateContext,
) -> Result<serde_json::Value> {
match (canonical, field_name) {
("BoyceCoddNormalFormViolation", "functional_deps") => {
let num_attributes = args.n.ok_or_else(|| {
anyhow::anyhow!("BoyceCoddNormalFormViolation requires --n, --sets, and --target")
})?;
Ok(serde_json::to_value(parse_bcnf_functional_deps(
raw,
num_attributes,
)?)?)
}
("BoundedComponentSpanningForest", "max_weight") => {
let usage = "Usage: pred create BoundedComponentSpanningForest --graph 0-1,1-2,2-3,3-4,4-5,5-6,6-7,0-7,1-5,2-6 --weights 2,3,1,2,3,1,2,1 --k 3 --max-weight 6";
let bound_raw = args.bound.ok_or_else(|| {
anyhow::anyhow!("BoundedComponentSpanningForest requires --max-weight\n\n{usage}")
})?;
let max_weight = i32::try_from(bound_raw).map_err(|_| {
anyhow::anyhow!(
"BoundedComponentSpanningForest requires --max-weight within i32 range\n\n{usage}"
)
})?;
Ok(serde_json::json!(max_weight))
}
("ConsecutiveBlockMinimization", "matrix") => {
let usage = "Usage: pred create ConsecutiveBlockMinimization --matrix '[[true,false,true],[false,true,true]]' --bound-k 2";
let matrix: Vec<Vec<bool>> = serde_json::from_str(raw).map_err(|err| {
anyhow::anyhow!(
"ConsecutiveBlockMinimization requires --matrix as a JSON 2D bool array (e.g., '[[true,false,true],[false,true,true]]')\n\n{usage}\n\nFailed to parse --matrix: {err}"
)
})?;
Ok(serde_json::to_value(matrix)?)
}
("FeasibleBasisExtension", "matrix") => {
let usage = "Usage: pred create FeasibleBasisExtension --matrix '[[1,0,1],[0,1,0]]' --rhs '7,5' --required-columns '0'";
let matrix: Vec<Vec<i64>> = serde_json::from_str(raw).map_err(|err| {
anyhow::anyhow!(
"FeasibleBasisExtension requires --matrix as a JSON 2D integer array (e.g., '[[1,0,1],[0,1,0]]')\n\n{usage}\n\nFailed to parse --matrix: {err}"
)
})?;
Ok(serde_json::to_value(matrix)?)
}
("IntegralFlowBundles", "bundle_capacities") => {
let usage = "Usage: pred create IntegralFlowBundles --arcs \"0>1,0>2,1>3,2>3,1>2,2>1\" --bundles \"0,1;2,5;3,4\" --bundle-capacities 1,1,1 --source 0 --sink 3 --requirement 1 --num-vertices 4";
let arcs_str = args
.arcs
.as_deref()
.ok_or_else(|| anyhow::anyhow!("IntegralFlowBundles requires --arcs\n\n{usage}"))?;
let (_, num_arcs) = parse_directed_graph(arcs_str, args.num_vertices)
.map_err(|e| anyhow::anyhow!("{e}\n\n{usage}"))?;
let bundles = parse_bundles(args, num_arcs, usage)?;
Ok(serde_json::to_value(parse_bundle_capacities(
args,
bundles.len(),
usage,
)?)?)
}
("IntegralFlowHomologousArcs", "homologous_pairs") => {
Ok(serde_json::to_value(parse_homologous_pairs(args)?)?)
}
("LengthBoundedDisjointPaths", "max_length") => {
let usage = "Usage: pred create LengthBoundedDisjointPaths --graph 0-1,1-6,0-2,2-3,3-6,0-4,4-5,5-6 --source 0 --sink 6 --max-length 3";
let bound = args.bound.ok_or_else(|| {
anyhow::anyhow!("LengthBoundedDisjointPaths requires --max-length\n\n{usage}")
})?;
let max_length = usize::try_from(bound).map_err(|_| {
anyhow::anyhow!(
"--max-length must be a nonnegative integer for LengthBoundedDisjointPaths\n\n{usage}"
)
})?;
Ok(serde_json::json!(max_length))
}
("LongestCommonSubsequence", "strings") => {
let (strings, _) = parse_lcs_strings(raw)?;
Ok(serde_json::to_value(strings)?)
}
("MinimumDecisionTree", "test_matrix") => {
let usage = "Usage: pred create MinimumDecisionTree --test-matrix '[[true,true,false,false],[true,false,false,false],[false,true,false,true]]' --num-objects 4 --num-tests 3";
let matrix: Vec<Vec<bool>> = serde_json::from_str(raw).map_err(|err| {
anyhow::anyhow!(
"MinimumDecisionTree requires --test-matrix as a JSON 2D bool array\n\n{usage}\n\nFailed to parse --test-matrix: {err}"
)
})?;
Ok(serde_json::to_value(matrix)?)
}
("MinimumWeightDecoding", "matrix") => {
let usage = "Usage: pred create MinimumWeightDecoding --matrix '[[true,false,true],[false,true,true]]' --rhs 'true,true'";
let matrix: Vec<Vec<bool>> = serde_json::from_str(raw).map_err(|err| {
anyhow::anyhow!(
"MinimumWeightDecoding requires --matrix as a JSON 2D bool array (e.g., '[[true,false],[false,true]]')\n\n{usage}\n\nFailed to parse --matrix: {err}"
)
})?;
Ok(serde_json::to_value(matrix)?)
}
("MinimumWeightSolutionToLinearEquations", "matrix") => {
let usage = "Usage: pred create MinimumWeightSolutionToLinearEquations --matrix '[[1,2,3,1],[2,1,1,3]]' --rhs '5,4'";
let matrix: Vec<Vec<i64>> = serde_json::from_str(raw).map_err(|err| {
anyhow::anyhow!(
"MinimumWeightSolutionToLinearEquations requires --matrix as a JSON 2D integer array (e.g., '[[1,2,3],[4,5,6]]')\n\n{usage}\n\nFailed to parse --matrix: {err}"
)
})?;
Ok(serde_json::to_value(matrix)?)
}
("GroupingBySwapping", "string")
| ("StringToStringCorrection", "source")
| ("StringToStringCorrection", "target") => {
Ok(serde_json::to_value(parse_symbol_list_allow_empty(raw)?)?)
}
("MultipleCopyFileAllocation", "usage") => {
let (_, num_vertices) = parse_graph(args)
.map_err(|e| anyhow::anyhow!("{e}\n\n{MULTIPLE_COPY_FILE_ALLOCATION_USAGE}"))?;
Ok(serde_json::to_value(parse_vertex_i64_values(
args.usage.as_deref(),
"usage",
num_vertices,
"MultipleCopyFileAllocation",
MULTIPLE_COPY_FILE_ALLOCATION_USAGE,
)?)?)
}
("MultipleCopyFileAllocation", "storage") => {
let (_, num_vertices) = parse_graph(args)
.map_err(|e| anyhow::anyhow!("{e}\n\n{MULTIPLE_COPY_FILE_ALLOCATION_USAGE}"))?;
Ok(serde_json::to_value(parse_vertex_i64_values(
args.storage.as_deref(),
"storage",
num_vertices,
"MultipleCopyFileAllocation",
MULTIPLE_COPY_FILE_ALLOCATION_USAGE,
)?)?)
}
("SequencingToMinimizeMaximumCumulativeCost", "precedences") => {
Ok(serde_json::to_value(parse_precedence_pairs(
args.precedences
.as_deref()
.or(args.precedence_pairs.as_deref()),
)?)?)
}
("UndirectedTwoCommodityIntegralFlow", "capacities") => {
let usage = "Usage: pred create UndirectedTwoCommodityIntegralFlow --graph 0-2,1-2,2-3 --capacities 1,1,2 --source-1 0 --sink-1 3 --source-2 1 --sink-2 3 --requirement-1 1 --requirement-2 1";
let (graph, _) = parse_graph(args).map_err(|e| anyhow::anyhow!("{e}\n\n{usage}"))?;
Ok(serde_json::to_value(parse_capacities(
args,
graph.num_edges(),
usage,
)?)?)
}
_ => parse_field_value(concrete_type, field_name, raw, context),
}
}
pub(super) fn schema_driven_supported_problem(canonical: &str) -> bool {
canonical != "ILP" && canonical != "CircuitSAT"
}
pub(super) fn schema_field_flag_keys(
canonical: &str,
field_name: &str,
field_type: &str,
is_geometry: bool,
) -> Vec<String> {
let mut keys = vec![field_name.replace('_', "-")];
for display_key in problem_help_flag_name(canonical, field_name, field_type, is_geometry)
.split('/')
.map(|key| key.trim().trim_start_matches("--").to_string())
.filter(|key| !key.is_empty())
{
if !keys.contains(&display_key) {
keys.push(display_key);
}
}
keys
}
pub(super) fn get_schema_flag_value(
flag_map: &std::collections::HashMap<&'static str, Option<String>>,
keys: &[String],
) -> Option<String> {
keys.iter()
.find_map(|key| flag_map.get(key.as_str()).cloned().flatten())
}
pub(super) fn resolve_schema_field_type(
type_name: &str,
resolved_variant: &BTreeMap<String, String>,
) -> String {
let normalized = normalize_type_name(type_name);
let graph_type = resolved_variant
.get("graph")
.map(String::as_str)
.unwrap_or("SimpleGraph");
let weight_type = resolved_variant
.get("weight")
.map(String::as_str)
.unwrap_or("One");
match normalized.as_str() {
"G" => graph_type.to_string(),
"W" => weight_type.to_string(),
"W::Sum" => weight_sum_type(weight_type).to_string(),
"Vec<W>" => format!("Vec<{weight_type}>"),
"Vec<Vec<W>>" => format!("Vec<Vec<{weight_type}>>"),
"Vec<(usize,usize,W)>" => format!("Vec<(usize,usize,{weight_type})>"),
"Vec<Vec<T>>" => format!("Vec<Vec<{weight_type}>>"),
other => other.to_string(),
}
}
pub(super) fn weight_sum_type(weight_type: &str) -> &'static str {
match weight_type {
"One" | "i32" => "i32",
"f64" => "f64",
_ => "i32",
}
}
pub(super) fn seed_schema_context_from_cli(
args: &CreateArgs,
graph_type: &str,
context: &mut CreateContext,
) -> Result<()> {
if let Some(num_vertices) = args.num_vertices {
context.seed_field("num_vertices", num_vertices)?;
}
if graph_type == "UnitDiskGraph" {
context.seed_field("radius", args.radius.unwrap_or(1.0))?;
}
Ok(())
}
pub(super) fn derive_schema_field_value(
args: &CreateArgs,
canonical: &str,
field_name: &str,
concrete_type: &str,
context: &CreateContext,
) -> Result<Option<serde_json::Value>> {
if let Some(defaulted) =
derive_schema_default_value(canonical, field_name, concrete_type, context)?
{
return Ok(Some(defaulted));
}
if field_name == "graph" && concrete_type == "MixedGraph" {
let usage = format!(
"Usage: pred create {canonical} {}",
example_for(canonical, None)
);
return Ok(Some(serde_json::to_value(parse_mixed_graph(
args, &usage,
)?)?));
}
if field_name == "graph" && concrete_type == "BipartiteGraph" {
let left = args
.left
.ok_or_else(|| anyhow::anyhow!("{canonical} requires --left"))?;
let right = args
.right
.ok_or_else(|| anyhow::anyhow!("{canonical} requires --right"))?;
let edges_raw = args
.biedges
.as_deref()
.ok_or_else(|| anyhow::anyhow!("{canonical} requires --biedges"))?;
let edges = util::parse_edge_pairs(edges_raw)?;
validate_bipartite_edges(canonical, left, right, &edges)?;
return Ok(Some(serde_json::to_value(BipartiteGraph::new(
left, right, edges,
))?));
}
if canonical == "ClosestVectorProblem"
&& field_name == "bounds"
&& normalize_type_name(concrete_type) == "Vec<VarBounds>"
{
return Ok(Some(parse_cvp_bounds_value(
args.bounds.as_deref(),
context,
)?));
}
if canonical == "ConjunctiveBooleanQuery"
&& field_name == "num_variables"
&& normalize_type_name(concrete_type) == "usize"
{
let raw = args
.conjuncts_spec
.as_deref()
.ok_or_else(|| anyhow::anyhow!("ConjunctiveBooleanQuery requires --conjuncts-spec"))?;
return Ok(Some(serde_json::json!(infer_cbq_num_variables(raw)?)));
}
if canonical == "GroupingBySwapping"
&& field_name == "alphabet_size"
&& normalize_type_name(concrete_type) == "usize"
{
let raw = args
.string
.as_deref()
.ok_or_else(|| anyhow::anyhow!("GroupingBySwapping requires --string"))?;
let string = parse_symbol_list_allow_empty(raw)?;
let inferred = string.iter().copied().max().map_or(0, |value| value + 1);
return Ok(Some(serde_json::json!(args
.alphabet_size
.unwrap_or(inferred))));
}
if canonical == "JobShopScheduling"
&& field_name == "num_processors"
&& normalize_type_name(concrete_type) == "usize"
{
let usage = "Usage: pred create JobShopScheduling --jobs \"0:3,1:4;1:2,0:3,1:2;0:4,1:3\" --num-processors 2";
let inferred_processors = match args.job_tasks.as_deref() {
Some(job_tasks) => {
let jobs = parse_job_shop_jobs(job_tasks)?;
jobs.iter()
.flat_map(|job| job.iter().map(|(processor, _)| *processor))
.max()
.map(|processor| processor + 1)
}
None => None,
};
let num_processors =
resolve_processor_count_flags("JobShopScheduling", usage, args.num_processors, args.m)?
.or(inferred_processors)
.ok_or_else(|| {
anyhow::anyhow!(
"Cannot infer num_processors from empty job list; use --num-processors"
)
})?;
return Ok(Some(serde_json::json!(num_processors)));
}
if canonical == "LongestCommonSubsequence"
&& field_name == "alphabet_size"
&& normalize_type_name(concrete_type) == "usize"
{
let raw = args
.strings
.as_deref()
.ok_or_else(|| anyhow::anyhow!("LongestCommonSubsequence requires --strings"))?;
let (_, inferred_alphabet_size) = parse_lcs_strings(raw)?;
return Ok(Some(serde_json::json!(args
.alphabet_size
.unwrap_or(inferred_alphabet_size))));
}
if canonical == "LongestCommonSubsequence"
&& field_name == "max_length"
&& normalize_type_name(concrete_type) == "usize"
{
let strings: Vec<Vec<usize>> =
serde_json::from_value(context.parsed_fields.get("strings").cloned().ok_or_else(
|| anyhow::anyhow!("LCS max_length derivation requires parsed strings"),
)?)?;
let max_length = strings.iter().map(Vec::len).min().unwrap_or(0);
return Ok(Some(serde_json::json!(max_length)));
}
if canonical == "QUBO"
&& field_name == "num_vars"
&& normalize_type_name(concrete_type) == "usize"
{
let matrix = parse_matrix(args)?;
return Ok(Some(serde_json::json!(matrix.len())));
}
if canonical == "StringToStringCorrection"
&& field_name == "alphabet_size"
&& normalize_type_name(concrete_type) == "usize"
{
let source = parse_symbol_list_allow_empty(args.source_string.as_deref().unwrap_or(""))?;
let target = parse_symbol_list_allow_empty(args.target_string.as_deref().unwrap_or(""))?;
let inferred = source
.iter()
.chain(target.iter())
.copied()
.max()
.map_or(0, |value| value + 1);
return Ok(Some(serde_json::json!(args
.alphabet_size
.unwrap_or(inferred))));
}
if field_name == "precedences"
&& normalize_type_name(concrete_type) == "Vec<(usize,usize)>"
&& args.precedences.is_none()
&& args.precedence_pairs.is_none()
{
return Ok(Some(serde_json::json!([])));
}
if canonical == "ComparativeContainment"
&& matches!(field_name, "r_weights" | "s_weights")
&& matches!(
normalize_type_name(concrete_type).as_str(),
"Vec<One>" | "Vec<i32>" | "Vec<f64>"
)
{
let sets_len = context
.parsed_fields
.get(match field_name {
"r_weights" => "r_sets",
_ => "s_sets",
})
.and_then(serde_json::Value::as_array)
.map(Vec::len);
if let Some(len) = sets_len {
let value = match normalize_type_name(concrete_type).as_str() {
"Vec<One>" | "Vec<i32>" => serde_json::json!(vec![1_i32; len]),
"Vec<f64>" => serde_json::json!(vec![1.0_f64; len]),
_ => unreachable!(),
};
return Ok(Some(value));
}
}
if canonical == "ConsistencyOfDatabaseFrequencyTables"
&& field_name == "known_values"
&& normalize_type_name(concrete_type) == "Vec<KnownValue>"
&& args.known_values.is_none()
{
return Ok(Some(serde_json::json!([])));
}
if canonical == "LengthBoundedDisjointPaths"
&& field_name == "max_paths"
&& normalize_type_name(concrete_type) == "usize"
{
let graph_value = context.parsed_fields.get("graph").cloned();
let source = context.usize_field("source");
let sink = context.usize_field("sink");
if let (Some(graph_value), Some(source), Some(sink)) = (graph_value, source, sink) {
let graph: SimpleGraph =
serde_json::from_value(graph_value).context("Failed to deserialize graph")?;
let max_paths = graph
.neighbors(source)
.len()
.min(graph.neighbors(sink).len());
return Ok(Some(serde_json::json!(max_paths)));
}
}
Ok(None)
}
pub(super) fn derive_schema_default_value(
canonical: &str,
field_name: &str,
concrete_type: &str,
context: &CreateContext,
) -> Result<Option<serde_json::Value>> {
let normalized = normalize_type_name(concrete_type);
let one_list = |len: usize| match normalized.as_str() {
"Vec<One>" | "Vec<i32>" => Some(serde_json::json!(vec![1_i32; len])),
"Vec<u64>" => Some(serde_json::json!(vec![1_u64; len])),
"Vec<i64>" => Some(serde_json::json!(vec![1_i64; len])),
"Vec<usize>" => Some(serde_json::json!(vec![1_usize; len])),
"Vec<f64>" => Some(serde_json::json!(vec![1.0_f64; len])),
_ => None,
};
let derived = match field_name {
"weights" | "vertex_weights" => context.num_vertices.and_then(one_list),
"edge_weights" | "edge_lengths" => context.num_edges.and_then(one_list),
"arc_weights" | "arc_lengths" if context.num_arcs.is_some() => {
context.num_arcs.and_then(one_list)
}
"capacities" if canonical == "PathConstrainedNetworkFlow" => {
context.num_arcs.and_then(one_list)
}
"couplings" if canonical == "SpinGlass" => context.num_edges.and_then(one_list),
"fields" if canonical == "SpinGlass" => match normalized.as_str() {
"Vec<i32>" => context
.num_vertices
.map(|len| serde_json::json!(vec![0_i32; len])),
"Vec<f64>" => context
.num_vertices
.map(|len| serde_json::json!(vec![0.0_f64; len])),
_ => None,
},
_ => None,
};
Ok(derived)
}
pub(super) fn schema_field_requires_derived_input(field_name: &str, concrete_type: &str) -> bool {
field_name == "graph" && matches!(concrete_type, "MixedGraph" | "BipartiteGraph")
}
pub(super) fn with_schema_usage(
error: anyhow::Error,
canonical: &str,
resolved_variant: &BTreeMap<String, String>,
) -> anyhow::Error {
let message = error.to_string();
if message.contains("Usage: pred create") {
return error;
}
let graph_type = resolved_variant.get("graph").map(String::as_str);
anyhow::anyhow!(
"{message}\n\nUsage: pred create {canonical} {}",
example_for(canonical, graph_type)
)
}
pub(super) fn parse_field_value(
concrete_type: &str,
field_name: &str,
raw: &str,
context: &CreateContext,
) -> Result<serde_json::Value> {
let normalized_type = normalize_type_name(concrete_type);
let value = match normalized_type.as_str() {
"SimpleGraph" => parse_simple_graph_value(raw, context)?,
"DirectedGraph" => parse_directed_graph_value(raw, context)?,
"KingsSubgraph" => parse_grid_subgraph_value(raw, true)?,
"TriangularSubgraph" => parse_grid_subgraph_value(raw, false)?,
"UnitDiskGraph" => parse_unit_disk_graph_value(raw, context)?,
"Vec<i32>" => parse_numeric_list_value::<i32>(raw)?,
"Vec<f64>" => parse_numeric_list_value::<f64>(raw)?,
"Vec<u64>" => parse_numeric_list_value::<u64>(raw)?,
"Vec<i64>" => parse_numeric_list_value::<i64>(raw)?,
"Vec<usize>" => parse_numeric_list_value::<usize>(raw)?,
"Vec<One>" => parse_numeric_list_value::<i32>(raw)?,
"Vec<bool>" => parse_bool_list_value(raw)?,
"Vec<Vec<usize>>" => parse_nested_numeric_list_value::<usize>(raw)?,
"Vec<Vec<u64>>" => parse_nested_numeric_list_value::<u64>(raw)?,
"Vec<Vec<i32>>" => parse_nested_numeric_list_value::<i32>(raw)?,
"Vec<Vec<i64>>" => parse_nested_numeric_list_value::<i64>(raw)?,
"Vec<Vec<f64>>" => parse_nested_numeric_list_value::<f64>(raw)?,
"Vec<Vec<One>>" => parse_nested_numeric_list_value::<i32>(raw)?,
"Vec<Vec<bool>>" => parse_bool_rows_value(raw, field_name)?,
"Vec<Vec<Vec<usize>>>" => parse_3d_numeric_list_value::<usize>(raw)?,
"Vec<Vec<Vec<i64>>>" => parse_3d_numeric_list_value::<i64>(raw)?,
"Vec<[usize;3]>" => parse_triple_array_list_value(raw)?,
"Vec<CNFClause>" => serde_json::to_value(parse_clauses_raw(raw)?)?,
"Vec<(usize,usize)>" => parse_pair_list_value(raw)?,
"Vec<(u64,u64)>" => parse_semicolon_tuple_list_value::<u64, 2>(raw)?,
"Vec<(usize,f64)>" => parse_indexed_numeric_pairs_value::<f64>(raw)?,
"Vec<(usize,usize,usize)>" => parse_semicolon_tuple_list_value::<usize, 3>(raw)?,
"Vec<(usize,usize,usize,usize)>" => parse_semicolon_tuple_list_value::<usize, 4>(raw)?,
"Vec<(usize,usize,One)>" => parse_weighted_edge_list_value::<i32>(raw)?,
"Vec<(usize,usize,i32)>" => parse_weighted_edge_list_value::<i32>(raw)?,
"Vec<(usize,usize,i64)>" => parse_weighted_edge_list_value::<i64>(raw)?,
"Vec<(usize,usize,u64)>" => parse_weighted_edge_list_value::<u64>(raw)?,
"Vec<(usize,usize,f64)>" => parse_weighted_edge_list_value::<f64>(raw)?,
"Vec<(Vec<usize>,Vec<usize>)>" => serde_json::to_value(parse_dependencies(raw)?)?,
"Vec<(Vec<usize>,usize)>" => serde_json::to_value(parse_implications(raw)?)?,
"Vec<(usize,Vec<QueryArg>)>" => serde_json::to_value(parse_cbq_conjuncts(raw, context)?)?,
"Vec<(usize,Vec<usize>)>" => parse_indexed_usize_lists_value(raw)?,
"Vec<Vec<(usize,u64)>>" => serde_json::to_value(parse_job_shop_jobs(raw)?)?,
"Vec<(f64,f64)>" => serde_json::to_value(util::parse_positions::<f64>(raw, "0.0,0.0")?)?,
"Vec<FrequencyTable>" => {
serde_json::to_value(parse_cdft_frequency_tables_value(raw, context)?)?
}
"Vec<KnownValue>" => serde_json::to_value(parse_cdft_known_values_value(raw, context)?)?,
"Vec<Relation>" => serde_json::to_value(parse_cbq_relations(raw, context)?)?,
"Vec<String>" => parse_string_list_value(raw)?,
"Vec<VarBounds>" => parse_cvp_bounds_value(Some(raw), context)?,
"Vec<BigUint>" => parse_biguint_list_value(raw)?,
"BigUint" => parse_biguint_value(raw)?,
"Vec<Option<bool>>" => parse_optional_bool_list_value(raw)?,
"Vec<Quantifier>" => serde_json::to_value(parse_quantifiers_raw(raw, context)?)?,
"IntExpr" => parse_json_passthrough_value(raw)?,
"bool" => serde_json::to_value(parse_bool_token(raw.trim())?)?,
"One" => serde_json::json!(1),
"usize" => parse_scalar_value::<usize>(raw)?,
"u64" => parse_scalar_value::<u64>(raw)?,
"i32" => parse_scalar_value::<i32>(raw)?,
"i64" => parse_scalar_value::<i64>(raw)?,
"f64" => parse_scalar_value::<f64>(raw)?,
other => bail!("Unsupported schema parser for field '{field_name}' with type '{other}'"),
};
Ok(value)
}
pub(super) fn normalize_type_name(type_name: &str) -> String {
type_name.chars().filter(|ch| !ch.is_whitespace()).collect()
}
pub(super) fn parse_scalar_value<T>(raw: &str) -> Result<serde_json::Value>
where
T: std::str::FromStr + Serialize,
T::Err: std::fmt::Display,
{
Ok(serde_json::to_value(raw.trim().parse::<T>().map_err(
|err| anyhow::anyhow!("Invalid value '{}': {err}", raw.trim()),
)?)?)
}
pub(super) fn parse_numeric_list_value<T>(raw: &str) -> Result<serde_json::Value>
where
T: std::str::FromStr + Serialize,
T::Err: std::fmt::Display,
{
Ok(serde_json::to_value(util::parse_comma_list::<T>(raw)?)?)
}
pub(super) fn parse_bool_list_value(raw: &str) -> Result<serde_json::Value> {
let values: Vec<bool> = raw
.split(',')
.map(|entry| parse_bool_token(entry.trim()))
.collect::<Result<_>>()?;
Ok(serde_json::to_value(values)?)
}
pub(super) fn parse_bool_rows_value(raw: &str, field_name: &str) -> Result<serde_json::Value> {
let flag = format!("--{}", field_name.replace('_', "-"));
let rows = parse_bool_rows(raw)
.map_err(|err| anyhow::anyhow!("{}", err.to_string().replace("--matrix", &flag)))?;
Ok(serde_json::to_value(rows)?)
}
pub(super) fn parse_nested_numeric_list_value<T>(raw: &str) -> Result<serde_json::Value>
where
T: std::str::FromStr + Serialize,
T::Err: std::fmt::Display,
{
let rows: Vec<Vec<T>> = raw
.split(';')
.map(|row| util::parse_comma_list::<T>(row.trim()))
.collect::<Result<_>>()?;
Ok(serde_json::to_value(rows)?)
}
pub(super) fn parse_3d_numeric_list_value<T>(raw: &str) -> Result<serde_json::Value>
where
T: std::str::FromStr + Serialize,
T::Err: std::fmt::Display,
{
let matrices: Vec<Vec<Vec<T>>> = raw
.split('|')
.map(|matrix| {
matrix
.split(';')
.map(|row| util::parse_comma_list::<T>(row.trim()))
.collect::<Result<Vec<_>>>()
})
.collect::<Result<_>>()?;
Ok(serde_json::to_value(matrices)?)
}
pub(super) fn parse_triple_array_list_value(raw: &str) -> Result<serde_json::Value> {
let triples: Vec<[usize; 3]> = raw
.split(';')
.map(|entry| {
let values: Vec<usize> = util::parse_comma_list(entry.trim())?;
anyhow::ensure!(
values.len() == 3,
"Expected triple with exactly 3 entries, got {}",
values.len()
);
Ok([values[0], values[1], values[2]])
})
.collect::<Result<_>>()?;
Ok(serde_json::to_value(triples)?)
}
pub(super) fn parse_clauses_raw(raw: &str) -> Result<Vec<CNFClause>> {
raw.split(';')
.map(|clause| {
let literals: Vec<i32> = clause
.trim()
.split(',')
.map(|value| value.trim().parse::<i32>())
.collect::<std::result::Result<Vec<_>, _>>()?;
Ok(CNFClause::new(literals))
})
.collect()
}
pub(super) fn parse_pair_list_value(raw: &str) -> Result<serde_json::Value> {
let pairs: Vec<(usize, usize)> = raw
.split(',')
.map(|entry| {
let entry = entry.trim();
let parts: Vec<&str> = if entry.contains('>') {
entry.split('>').collect()
} else {
entry.split('-').collect()
};
anyhow::ensure!(
parts.len() == 2,
"Invalid pair '{entry}': expected u-v or u>v"
);
Ok((
parts[0].trim().parse::<usize>()?,
parts[1].trim().parse::<usize>()?,
))
})
.collect::<Result<_>>()?;
Ok(serde_json::to_value(pairs)?)
}
pub(super) fn infer_cbq_num_variables(raw: &str) -> Result<usize> {
let mut num_vars = 0usize;
for conjunct in raw.split(';').filter(|entry| !entry.trim().is_empty()) {
let (_, args_str) = conjunct.trim().split_once(':').ok_or_else(|| {
anyhow::anyhow!(
"Invalid conjunct format: expected 'rel_idx:args', got '{}'",
conjunct.trim()
)
})?;
for arg in args_str
.split(',')
.map(str::trim)
.filter(|arg| !arg.is_empty())
{
if let Some(rest) = arg.strip_prefix('v') {
let index: usize = rest
.parse()
.map_err(|err| anyhow::anyhow!("Invalid variable index '{rest}': {err}"))?;
num_vars = num_vars.max(index + 1);
}
}
}
Ok(num_vars)
}
pub(super) fn parse_cbq_relations(raw: &str, context: &CreateContext) -> Result<Vec<CbqRelation>> {
let domain_size = context.usize_field("domain_size").ok_or_else(|| {
anyhow::anyhow!("CBQ relation parsing requires a prior domain_size field")
})?;
raw.split(';')
.filter(|entry| !entry.trim().is_empty())
.map(|rel_str| {
let rel_str = rel_str.trim();
let (arity_str, tuples_str) = rel_str.split_once(':').ok_or_else(|| {
anyhow::anyhow!("Invalid relation format: expected 'arity:tuples', got '{rel_str}'")
})?;
let arity: usize = arity_str
.trim()
.parse()
.map_err(|e| anyhow::anyhow!("Invalid arity '{arity_str}': {e}"))?;
let tuples: Vec<Vec<usize>> = if tuples_str.trim().is_empty() {
Vec::new()
} else {
tuples_str
.split('|')
.filter(|tuple| !tuple.trim().is_empty())
.map(|tuple| {
let tuple: Vec<usize> = util::parse_comma_list(tuple.trim())?;
anyhow::ensure!(
tuple.len() == arity,
"Relation tuple has {} entries, expected arity {arity}",
tuple.len()
);