Skip to main content

sas_plus/
random.rs

1//! Tiny deterministic random task generator for property tests across the
2//! workspace (no external RNG dependency).
3
4use alloc::format;
5use alloc::vec::Vec;
6
7use crate::{Axiom, Effect, Fact, Operator, State, Task, Variable};
8
9/// xorshift64* — good enough for test-case generation.
10#[derive(Clone, Debug)]
11pub struct Rng(u64);
12
13impl Rng {
14    pub fn new(seed: u64) -> Self {
15        Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
16    }
17    pub fn next_u64(&mut self) -> u64 {
18        self.0 ^= self.0 >> 12;
19        self.0 ^= self.0 << 25;
20        self.0 ^= self.0 >> 27;
21        self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
22    }
23    /// Uniform in `lo..=hi`. Panics if `lo > hi`.
24    pub fn range(&mut self, lo: u64, hi: u64) -> u64 {
25        assert!(lo <= hi, "empty range {lo}..={hi}");
26        let x = self.next_u64();
27        // The full `u64` range has no modulus that fits.
28        (hi - lo).checked_add(1).map_or(x, |n| lo + x % n)
29    }
30    fn distinct_vars(&mut self, n: usize, k: usize) -> Vec<usize> {
31        let mut vars: Vec<usize> = (0..n).collect();
32        for i in 0..k.min(n) {
33            let j = self.range(i as u64, n as u64 - 1) as usize;
34            vars.swap(i, j);
35        }
36        vars.truncate(k.min(n));
37        vars
38    }
39}
40
41#[derive(Clone, Copy, Debug)]
42pub struct RandomTaskParams {
43    pub num_vars: usize,
44    pub max_domain: u32,
45    pub num_ops: usize,
46    pub max_cost: u32,
47    /// Up to this many conditions per effect; `0` means no conditional effects.
48    pub max_conditions: usize,
49    /// Number of binary derived variables, each in its own axiom layer, with
50    /// one or two rules apiece. Goals and preconditions may then mention them.
51    pub num_derived: usize,
52}
53
54impl Default for RandomTaskParams {
55    fn default() -> Self {
56        Self {
57            num_vars: 4,
58            max_domain: 3,
59            num_ops: 10,
60            max_cost: 5,
61            max_conditions: 0,
62            num_derived: 0,
63        }
64    }
65}
66
67pub fn random_task(seed: u64, p: RandomTaskParams) -> Task {
68    let mut rng = Rng::new(seed);
69    let variables: Vec<Variable> = (0..p.num_vars)
70        .map(|i| {
71            Variable::new(
72                format!("v{i}"),
73                rng.range(2, u64::from(p.max_domain.max(2))) as u32,
74            )
75        })
76        .collect();
77    let fact = |rng: &mut Rng, var: usize| {
78        Fact::new(
79            var,
80            rng.range(0, u64::from(variables[var].domain_size) - 1) as u32,
81        )
82    };
83    let mut operators: Vec<Operator> = (0..p.num_ops)
84        .map(|i| {
85            let n_pre = rng.range(0, 2) as usize;
86            let n_eff = rng.range(1, 2) as usize;
87            let pre = rng
88                .distinct_vars(p.num_vars, n_pre)
89                .into_iter()
90                .map(|v| fact(&mut rng, v))
91                .collect();
92            let eff = rng
93                .distinct_vars(p.num_vars, n_eff)
94                .into_iter()
95                .map(|v| {
96                    let head = fact(&mut rng, v);
97                    // No draw without conditions, so seeds keep their tasks.
98                    let conditions = if p.max_conditions == 0 {
99                        Vec::new()
100                    } else {
101                        let n = rng.range(0, p.max_conditions as u64) as usize;
102                        rng.distinct_vars(p.num_vars, n)
103                            .into_iter()
104                            .map(|c| fact(&mut rng, c))
105                            .collect()
106                    };
107                    Effect {
108                        conditions,
109                        fact: head,
110                    }
111                })
112                .collect();
113            Operator {
114                name: format!("op{i}"),
115                pre,
116                eff,
117                cost: rng.range(1, u64::from(p.max_cost.max(1))) as u32,
118            }
119        })
120        .collect();
121    let mut initial = State((0..p.num_vars).map(|v| fact(&mut rng, v).value).collect());
122    let n_goal = rng.range(1, 2) as usize;
123    let mut goal: Vec<Fact> = rng
124        .distinct_vars(p.num_vars, n_goal)
125        .into_iter()
126        .map(|v| fact(&mut rng, v))
127        .collect();
128
129    // Derived variables come last, so tasks without them stay the same per seed.
130    let mut variables = variables;
131    let mut axioms = Vec::new();
132    for layer in 0..p.num_derived {
133        let var = variables.len();
134        for _ in 0..rng.range(1, 2) {
135            // Conditions on state variables and lower layers (at any value, which
136            // includes negation as failure).
137            let n = rng.range(1, 2) as usize;
138            let conditions = rng
139                .distinct_vars(var, n)
140                .into_iter()
141                .map(|c| {
142                    let domain = variables[c].domain_size;
143                    Fact::new(c, rng.range(0, u64::from(domain) - 1) as u32)
144                })
145                .collect();
146            axioms.push(Axiom {
147                conditions,
148                head: Fact::new(var, 1),
149            });
150        }
151        variables.push(Variable {
152            axiom_layer: Some(layer as u32),
153            ..Variable::new(format!("d{layer}"), 2)
154        });
155        initial.0.push(0);
156        let derived = Fact::new(var, rng.range(0, 1) as u32);
157        if rng.range(0, 1) == 0 {
158            goal.push(derived);
159        } else {
160            let op = rng.range(0, p.num_ops.max(1) as u64 - 1) as usize;
161            if let Some(op) = operators.get_mut(op) {
162                op.pre.push(derived);
163            }
164        }
165    }
166    Task {
167        variables,
168        operators,
169        initial,
170        goal,
171        axioms,
172    }
173}