nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
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
//! Complete motion clauses assign signed roles; output units never select a formula.
use super::{Goal, Model, Request, invalid, physical};
use crate::{Error, Outcome, re};
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};

type Goals = Vec<(Goal, Option<String>)>;

fn toward(direction: &str) -> bool {
    matches!(
        direction.to_ascii_lowercase().as_str(),
        "approaches" | "toward" | "moves toward"
    )
}

fn log_positive_ratio(numerator: &BigRational, denominator: &BigRational) -> Result<f64, Error> {
    // ln(1 + (a-b)/b) retains changes near equality. Far from equality,
    // subtract operand logs to avoid cancellation when the change approaches -1.
    let change = (numerator - denominator) / denominator;
    if let Some(delta) = change.to_f64()
        && delta.is_finite()
        && delta.abs() <= 0.5
    {
        return Ok(delta.ln_1p());
    }
    let logarithm = |value: &BigRational| {
        value
            .to_f64()
            .filter(|number| number.is_finite() && *number > 0.0)
            .map(f64::ln)
            .ok_or_else(|| Error("numeric_underflow".into()))
    };
    Ok(logarithm(numerator)? - logarithm(denominator)?)
}

impl Request<'_> {
    pub(super) fn wording(&self, input: &str) -> Outcome {
        self.lower_wording(input).transpose()
    }

    fn goals(input: &str) -> Result<Goals, Error> {
        // Only the declared equivalent equation may be removed from a request.
        let input =
            re!(r"(?i)\s+using f_heard\s*=\s*f_source\s*\*\s*\(v\s*\+\s*vo\)/\(v\s*-\s*vs\)$")
                .replace(input, "");
        if re!(r"(?i)^(?:find|calculate) (?:the )?(?:heard|observed|received) frequency$")
            .is_match(&input)
            || re!(r"(?i)^evaluate (?:the )?(?:doppler expression|heard frequency)$")
                .is_match(&input)
        {
            return Ok(vec![(Goal::Frequency, None)]);
        }
        if re!(r"(?i)^(?:find|calculate) (?:the )?(?:heard|observed) frequency and period$")
            .is_match(&input)
        {
            return Ok(vec![(Goal::Frequency, None), (Goal::Period, None)]);
        }
        if re!(r"(?i)^(?:infer|find|calculate) (?:the )?source frequency$").is_match(&input) {
            return Ok(vec![(Goal::Source, None)]);
        }
        if let Some(c) = re!(r"(?i)^(?:find|calculate) (?:the )?(?:heard|observed) frequency, then calculate (?:the )?period in (.+)$").captures(&input) {
            return Ok(vec![(Goal::Frequency, None), (Goal::Period, Some(c[1].to_string()))]);
        }
        Err(invalid())
    }

    fn medium_request(input: &str) -> Result<(String, Goals), Error> {
        let input =
            re!(r"(?i) and use positive velocities toward each other to ").replace(input, ", ");
        // A clause separator must introduce a request verb; typed calls remain intact.
        let c = re!(r"(?i)^(?:with (?:stationary-medium speed |medium speed )?v\s*=\s*|with sound speed |(?:take|set|use) (?:medium speed )?v\s*=\s*|(?:stationary-medium|medium) speed (?:is\s+|v\s*=\s*))(.+?)(?: in still air)?(?:[;,]\s*|\s+and\s+)((?:find|calculate|infer|evaluate) .+)$")
            .captures(&input).ok_or_else(invalid)?;
        Ok((c[1].to_string(), Self::goals(&c[2])?))
    }

    fn motion_answer(
        &self,
        f: &str,
        vo: &str,
        vs: &str,
        tail: &str,
        heard: bool,
    ) -> Result<String, Error> {
        let (v, goals) = Self::medium_request(tail)?;
        let model = self.model(f, &v, vo, vs)?;
        self.motion_answer_in(model, &goals, heard)
    }

    fn motion_answer_in(&self, model: Model, goals: &Goals, heard: bool) -> Result<String, Error> {
        // An explicitly heard frequency cannot silently become an emitted-frequency role.
        if heard && (goals.len() != 1 || !matches!(goals[0].0, Goal::Source))
            || !heard && goals.iter().any(|(goal, _)| matches!(goal, Goal::Source))
        {
            return Err(invalid());
        }
        self.answer_in(model, goals)
    }

    fn motion_clauses(&self, input: &str) -> Result<Option<String>, Error> {
        macro_rules! family {
            ($pattern:literal, $c:ident, $answer:expr) => {
                if let Some($c) = re!($pattern).captures(input) {
                    return Ok(Some($answer?));
                }
            };
        }
        family!(
            r"(?i)^a (.+?) (?:sound )?source (approaches|recedes from|moves toward|moves away from) a stationary (?:listener|observer) at (.+?); (.+)$",
            c,
            self.motion_answer(
                &c[1],
                "0 m/s",
                &self.speed(&c[3], toward(&c[2]))?,
                &c[4],
                false
            )
        );
        family!(
            r"(?i)^a source emits (.+?) and moves (toward|away from) a stationary (?:observer|listener) at (.+?); (.+)$",
            c,
            self.motion_answer(
                &c[1],
                "0 m/s",
                &self.speed(&c[3], toward(&c[2]))?,
                &c[4],
                false
            )
        );
        family!(
            r"(?i)^a stationary (.+?) source is approached by an (?:observer|listener) at (.+?); (.+)$",
            c,
            self.motion_answer(&c[1], &self.speed(&c[2], true)?, "0 m/s", &c[3], false)
        );
        family!(
            r"(?i)^an (?:observer|listener) moves (toward|away from) a stationary (.+?) source at (.+?); (.+)$",
            c,
            self.motion_answer(
                &c[2],
                &self.speed(&c[3], toward(&c[1]))?,
                "0 m/s",
                &c[4],
                false
            )
        );
        family!(
            r"(?i)^a (.+?) source moves (toward|away) at (.+?) (?:while|from) (?:the|an) (?:observer|listener) (?:moves|moving) (toward|away)(?: it| from the source)? at (.+?); (.+)$",
            c,
            self.motion_answer(
                &c[1],
                &self.speed(&c[5], toward(&c[4]))?,
                &self.speed(&c[3], toward(&c[2]))?,
                &c[6],
                false
            )
        );
        family!(
            r"(?i)^a stationary (?:observer|listener) hears (.+?) from a source moving (toward|away from) (?:them|it) at (.+?); (.+)$",
            c,
            self.motion_answer(
                &c[1],
                "0 m/s",
                &self.speed(&c[3], toward(&c[2]))?,
                &c[4],
                true
            )
        );
        family!(
            r"(?i)^a source emits (.+?) while stationary and a stationary (?:observer|listener) is in a medium with speed v\s*=\s*(.+?); (.+)$",
            c,
            self.answer_in(
                self.model(&c[1], &c[2], "0 m/s", "0 m/s")?,
                &Self::goals(&c[3])?
            )
        );
        if let Some(c) = re!(r"(?i)^a (.+?) source approaches an (?:observer|listener) who approaches it at (.+?); (.+)$").captures(input) {
            let (v, _) = Self::medium_request(&c[3])?;
            self.coordinate(&c[1], "Hz", true)?;
            self.speed(&c[2], true)?;
            self.coordinate(&v, "m/s", true)?;
            // The source's direction is known, but its speed is not supplied.
            return Err(invalid());
        }
        Ok(None)
    }

    fn lower_wording(&self, input: &str) -> Result<Option<String>, Error> {
        if !re!(r"(?i)\b(?:doppler|sound|source|siren|echo)\b").is_match(input) {
            return Ok(None);
        }
        let input = input
            .replace('−', "-")
            .replace("f′", "fprime")
            .replace("f'", "fprime");
        let input = input.split_whitespace().collect::<Vec<_>>().join(" ");
        let input = input.trim().trim_end_matches(['.', '?']);
        macro_rules! rule {
            ($pattern:literal, $c:ident, $answer:expr) => {
                if let Some($c) = re!($pattern).captures(input) {
                    return Ok(Some($answer?));
                }
            };
        }
        rule!(
            r"(?i)^a speaker emits (.+?) dB sound level\. a second independent speaker at the same location also emits (.+?) dB; what combined level results using intensity addition and dB\s*=\s*10\s*(?:\*\s*)?log10\s*\(\s*I\s*/\s*I(?:₀|0)\s*\)$",
            c,
            {
                let first = self.coordinate(&c[1], "1", false)?;
                let second = self.coordinate(&c[2], "1", false)?;
                let first = first
                    .value
                    .to_f64()
                    .ok_or_else(|| Error("numeric_overflow".into()))?;
                let second = second
                    .value
                    .to_f64()
                    .ok_or_else(|| Error("numeric_overflow".into()))?;
                let high = first.max(second);
                let low = first.min(second);
                // Both stated levels use the same I₀. Add their independent
                // intensities as ratios, without inventing a numerical I₀.
                let combined = high
                    + 10.0 * (10.0_f64.powf((low - high) / 10.0)).ln_1p() / std::f64::consts::LN_10;
                if !combined.is_finite() {
                    return Err(Error("numeric_overflow".into()));
                }
                // dB is a logarithmic level label, so it is rendered only by
                // the acoustics operation after expression rewriting finishes.
                Ok(format!("acoustics_level(real({combined:e}))"))
            }
        );
        rule!(
            r"(?i)^a sound level is l\s*=\s*10\s*log10\s*\(\s*i\s*/\s*i(?:₀|0)\s*\) decibels, with i\s*=\s*(.+?) and supplied reference intensity i(?:₀|0)\s*=\s*(.+?)\. find l in decibels$",
            c,
            {
                let intensity = self.coordinate(&c[1], "W/m²", true)?;
                let reference = self.coordinate(&c[2], "W/m²", true)?;
                let level = 10.0 * log_positive_ratio(&intensity.value, &reference.value)?
                    / std::f64::consts::LN_10;
                if !level.is_finite() {
                    return Err(Error("numeric_overflow".into()));
                }
                Ok(format!("acoustics_level(real({level:e}))"))
            }
        );
        rule!(
            r"(?i)^a sound source emits (.+?) dB at (.+?) in a free field; assuming spherical spreading with no absorption, what level is expected at (.+)$",
            c,
            {
                let initial = self.coordinate(&c[1], "1", false)?;
                let reference = self.coordinate(&c[2], "m", true)?;
                let target = self.coordinate(&c[3], "m", true)?;
                let level = initial
                    .value
                    .to_f64()
                    .ok_or_else(|| Error("numeric_overflow".into()))?;
                // I_target / I_reference = (r_reference / r_target)^2.
                let log_radius_ratio = log_positive_ratio(&reference.value, &target.value)?;
                let result = level + 20.0 * log_radius_ratio / std::f64::consts::LN_10;
                if !result.is_finite() {
                    return Err(Error("numeric_overflow".into()));
                }
                Ok(format!("acoustics_level(real({result:e}))"))
            }
        );
        rule!(
            r"(?i)^an echo returns after (.+?) in air; if sound speed is (.+?), calculate the reflector distance assuming the sound travels out and back$",
            c,
            {
                let elapsed = self.coordinate(&c[1], "s", true)?;
                let speed = self.coordinate(&c[2], "m/s", true)?;
                self.result(
                    elapsed.value * speed.value / num_rational::BigRational::from_integer(2.into()),
                    "m",
                    elapsed.authored && speed.authored,
                )
                .map(|distance| format!("{distance} in m"))
            }
        );
        rule!(
            r"(?i)^a sound pulse travels (.+?) in air over (.+?)\. using that measured speed, how long would it take to travel (.+)$",
            c,
            {
                let observed_distance = self.coordinate(&c[1], "m", true)?;
                let observed_time = self.coordinate(&c[2], "s", true)?;
                let target_distance = self.coordinate(&c[3], "m", false)?;
                if target_distance.value.is_negative() {
                    return Err(physical());
                }
                self.result(
                    target_distance.value * observed_time.value / observed_distance.value,
                    "s",
                    observed_distance.authored
                        && observed_time.authored
                        && target_distance.authored,
                )
            }
        );
        rule!(
            r"(?i)^a source emits (.+?) sound and approaches a stationary observer at (.+?); sound speed is (.+?) in still air, so find heard frequency$",
            c,
            self.answer(
                self.model(&c[1], &c[3], "0 m/s", &self.speed(&c[2], true)?)?,
                &[Goal::Frequency]
            )
        );
        rule!(
            r"(?i)^a source recedes at (.+?) from an observer who also moves away at (.+?); emitted frequency is (.+?) and sound speed is (.+?); calculate received frequency$",
            c,
            self.answer(
                self.model(
                    &c[3],
                    &c[4],
                    &self.speed(&c[2], false)?,
                    &self.speed(&c[1], false)?
                )?,
                &[Goal::Frequency]
            )
        );
        rule!(
            r"(?i)^a siren has period (.+?) and moves toward a stationary listener at (.+?); with still-medium sound speed (.+?), calculate emitted and heard frequencies$",
            c,
            {
                let period = self.coordinate(&c[1], "s", true)?;
                let emitted = self.result(period.value.recip(), "Hz", period.authored)?;
                self.answer(
                    self.model(&emitted, &c[3], "0 m/s", &self.speed(&c[2], true)?)?,
                    &[Goal::Emitted, Goal::Frequency],
                )
            }
        );
        rule!(
            r"(?i)^a stationary source emits (.+?) in air where sound speed is (.+?); calculate wavelength and period$",
            c,
            self.answer(
                self.model(&c[1], &c[2], "0 m/s", "0 m/s")?,
                &[Goal::PlainWavelength, Goal::PlainPeriod]
            )
        );
        rule!(
            r"(?i)^a source approaches a stationary observer at (.+?) while emitting (.+?) in a medium with sound speed (.+?); calculate the classical doppler expression's outcome$",
            c,
            self.answer(
                self.model(&c[2], &c[3], "0 m/s", &self.speed(&c[1], true)?)?,
                &[Goal::Frequency]
            )
        );
        rule!(
            r"(?i)^a stationary source emits (.+?); an observer recedes at (.+?) in a still medium where sound speed is (.+?); find observed period$",
            c,
            self.answer(
                self.model(&c[1], &c[3], &self.speed(&c[2], false)?, "0 m/s")?,
                &[Goal::Period]
            )
        );
        rule!(
            r"(?i)^a sound wave travels (.+?) in (.+?); find speed, then calculate wavelength for frequency (.+?)$",
            c,
            {
                let distance = self.coordinate(&c[1], "m", false)?;
                let duration = self.coordinate(&c[2], "s", true)?;
                if distance.value.is_negative() {
                    return Err(physical());
                }
                let speed = self.result(
                    distance.value / duration.value,
                    "m/s",
                    distance.authored && duration.authored,
                )?;
                self.answer(
                    self.model(&c[3], &speed, "0 m/s", "0 m/s")?,
                    &[Goal::Speed, Goal::PlainWavelength],
                )
            }
        );
        rule!(
            r"(?i)^a stationary (.+?) siren is heard by an observer moving (toward|away) at (.+?) through still air at (.+?); (.+)$",
            c,
            self.motion_answer_in(
                self.model(&c[1], &c[4], &self.speed(&c[3], toward(&c[2]))?, "0 m/s")?,
                &Self::goals(&c[5])?,
                false
            )
        );
        rule!(
            r"(?i)^a source emitting (.+?) (recedes|approaches) at (.+?) while an observer (recedes|approaches) at (.+?) in a stationary medium with sound speed (.+?); (.+)$",
            c,
            self.motion_answer_in(
                self.model(
                    &c[1],
                    &c[6],
                    &self.speed(&c[5], toward(&c[4]))?,
                    &self.speed(&c[3], toward(&c[2]))?
                )?,
                &Self::goals(&c[7])?,
                false
            )
        );
        rule!(
            r"(?i)^a stationary source emits a tone with period (.+?) in air where sound speed is (.+?); determine frequency and wavelength$",
            c,
            {
                let period = self.coordinate(&c[1], "s", true)?;
                let f = self.result(period.value.recip(), "Hz", period.authored)?;
                self.answer(
                    self.model(&f, &c[2], "0 m/s", "0 m/s")?,
                    &[Goal::Frequency, Goal::Wavelength],
                )
            }
        );
        rule!(
            r"(?i)^a source moving toward an observer at (.+?) emits (.+?) in still air with sound speed (.+?); state the doppler formula result or its physical limitation$",
            c,
            self.answer(
                self.model(&c[2], &c[3], "0 m/s", &self.speed(&c[1], true)?)?,
                &[Goal::Frequency]
            )
        );
        rule!(
            r"(?i)^sound travels at (.+?); an observer moves toward a stationary (.+?) source at (.+?); using fprime = f\(v \+ vo\)/\(v - vs\), where vo is positive toward the source and vs positive toward the observer, find observed frequency$",
            c,
            self.answer(
                self.model(&c[2], &c[1], &self.speed(&c[3], true)?, "0 m/s")?,
                &[Goal::Frequency]
            )
        );
        rule!(
            r"(?i)^a stationary observer hears a (.+?) source moving toward them at (.+?); use fprime = f\(v \+ vo\)/\(v - vs\), v = (.+?), vo positive toward source, vs positive toward observer, and calculate fprime$",
            c,
            self.answer(
                self.model(&c[1], &c[3], "0 m/s", &self.speed(&c[2], true)?)?,
                &[Goal::Frequency]
            )
        );
        rule!(
            r"(?i)^a (.+?) source and observer approach each other at (.+?) and (.+?) respectively; with sound speed (.+?) and fprime = f\(v \+ vo\)/\(v - vs\), both direction speeds positive toward the other, find the heard frequency$",
            c,
            self.answer(
                self.model(
                    &c[1],
                    &c[4],
                    &self.speed(&c[3], true)?,
                    &self.speed(&c[2], true)?
                )?,
                &[Goal::Frequency]
            )
        );
        rule!(
            r"(?i)^using fprime = f\(v \+ vo\)/\(v - vs\), with vo positive toward the source and vs positive toward the observer, calculate the frequency for f = (.+?), v = (.+?), vo = (.+?), vs = (.+?)$",
            c,
            self.answer(self.model(&c[1], &c[2], &c[3], &c[4])?, &[Goal::Frequency])
        );
        rule!(
            r"(?i)^a source emitting (.+?) moves away from a stationary observer at (.+?); with sound speed (.+?) and doppler model fprime = f\(v \+ vo\)/\(v - vs\), use vo positive toward source and vs positive toward observer, and find fprime$",
            c,
            self.answer(
                self.model(&c[1], &c[3], "0 m/s", &self.speed(&c[2], false)?)?,
                &[Goal::Frequency]
            )
        );
        rule!(
            r"(?i)^a (.+?) source moves toward an observer at (.+?) while the observer moves away from it at (.+?); use v = (.+?) and fprime = f\(v \+ vo\)/\(v - vs\), with vo positive toward source and vs positive toward observer$",
            c,
            self.answer(
                self.model(
                    &c[1],
                    &c[4],
                    &self.speed(&c[3], false)?,
                    &self.speed(&c[2], true)?
                )?,
                &[Goal::Frequency]
            )
        );
        rule!(
            r"(?i)^an observer approaches a stationary source at (.+?) and hears (.+?); sound speed is (.+?), use fprime = f\(v \+ vo\)/\(v - vs\), vo positive toward source and vs positive toward observer, to infer source frequency$",
            c,
            self.answer(
                self.model(&c[2], &c[3], &self.speed(&c[1], true)?, "0 m/s")?,
                &[Goal::Source]
            )
        );
        rule!(
            r"(?i)^a (.+?) source approaches at (.+?) and an observer approaches at (.+?); with sound speed (.+?) and fprime = f\(v \+ vo\)/\(v - vs\), directions positive toward each other, calculate heard frequency and shift from emitted frequency$",
            c,
            self.answer(
                self.model(
                    &c[1],
                    &c[4],
                    &self.speed(&c[3], true)?,
                    &self.speed(&c[2], true)?
                )?,
                &[Goal::Frequency, Goal::Shift]
            )
        );
        rule!(
            r"(?i)^a (.+?) tone comes from a source receding at (.+?) while an observer approaches at (.+?); with v = (.+?) and the stated signed-speed convention, calculate observed frequency, frequency difference, and percentage change$",
            c,
            self.answer(
                self.model(
                    &c[1],
                    &c[4],
                    &self.speed(&c[3], true)?,
                    &self.speed(&c[2], false)?
                )?,
                &[Goal::Frequency, Goal::Shift, Goal::PercentChange]
            )
        );
        rule!(
            r"(?i)^a source emits (.+?) and moves toward a stationary observer at (.+?); with sound speed (.+?), find heard frequency, frequency increase, and the heard-to-emitted ratio$",
            c,
            self.answer(
                self.model(&c[1], &c[3], "0 m/s", &self.speed(&c[2], true)?)?,
                &[Goal::Frequency, Goal::Increase, Goal::Ratio]
            )
        );
        rule!(
            r"(?i)^a stationary source emits (.+?); an observer approaches at (.+?) with sound speed (.+?); calculate observed frequency, frequency increase, and wavelength of the observed sound in the stationary air$",
            c,
            self.answer(
                self.model(&c[1], &c[3], &self.speed(&c[2], true)?, "0 m/s")?,
                &[Goal::Frequency, Goal::Increase, Goal::Wavelength]
            )
        );
        rule!(
            r"(?i)^a (.+?) source approaches a stationary observer at (.+?) in sound speed (.+?); calculate fprime, period of the heard tone, and percentage frequency increase$",
            c,
            self.answer(
                self.model(&c[1], &c[3], "0 m/s", &self.speed(&c[2], true)?)?,
                &[Goal::Frequency, Goal::Period, Goal::PercentIncrease]
            )
        );
        rule!(
            r"(?i)^a source emits (.+?) and recedes at (.+?) from a stationary observer; use v = (.+?) and the explicit signed doppler formula to calculate the heard frequency and difference$",
            c,
            self.answer(
                self.model(&c[1], &c[3], "0 m/s", &self.speed(&c[2], false)?)?,
                &[Goal::Frequency, Goal::Shift]
            )
        );
        rule!(
            r"(?i)^a (.+?) source approaches at (.+?) while an observer recedes at (.+?); sound speed is (.+?), use vo positive toward source and vs positive toward observer, and calculate observed frequency$",
            c,
            self.answer(
                self.model(
                    &c[1],
                    &c[4],
                    &self.speed(&c[3], false)?,
                    &self.speed(&c[2], true)?
                )?,
                &[Goal::Frequency]
            )
        );

        // The same roles validate explicit singular and invalid-domain model claims.
        rule!(
            r"(?i)^(?:use|using) fprime = f\(v \+ vo\)/\(v - vs\), with vo positive toward source and vs positive toward observer; the request gives v = (.+?), vs = (.+?), f = (.+?), vo = (.+?) and asks for finite observed frequency$",
            c,
            self.answer(
                self.model(
                    &c[3],
                    &c[1],
                    &if c[4].trim() == "0" {
                        "0 m/s".into()
                    } else {
                        c[4].to_string()
                    },
                    &c[2]
                )?,
                &[Goal::Frequency]
            )
        );
        rule!(
            r"(?i)^for the stated doppler formula fprime = f\(v \+ vo\)/\(v - vs\), with v = (.+?), source speed vs = (.+?) positive toward observer, observer stationary, and f = (.+?), determine whether the model gives a physically valid finite result$",
            c,
            self.answer(
                self.model(&c[3], &c[1], "0 m/s", &self.speed(&c[2], true)?)?,
                &[Goal::Frequency]
            )
        );
        if re!(r"(?i)^a doppler request says a .+? source and observer each move at .+? and asks for the heard frequency, but gives neither sound speed nor whether the motions are toward or away$").is_match(input)
            || re!(r#"(?i)^a source is said to move [“"]toward[”"] the observer at .+?, and the observer [“"]away[”"] at .+?; calculate the doppler shift for a .+? tone without a sound speed$"#).is_match(input)
        {
            return Err(invalid());
        }
        rule!(
            r"(?i)^using fprime = f\(v \+ vo\)/\(v - vs\), with vo positive toward source and vs positive toward observer, f = (.+?), v = (.+?), vs = (.+?), vo = (.+?), and the observer is stationary; calculate observed frequency$",
            c,
            {
                let model = self.model(&c[1], &c[2], &c[4], &c[3])?;
                if !model.wave.vo.value.is_zero() {
                    return Err(physical());
                }
                self.answer(model, &[Goal::Frequency])
            }
        );
        rule!(
            r"(?i)^using fprime = f\(v \+ vo\)/\(v - vs\), with vo positive toward source and vs positive toward observer, f = (.+?), v = (.+?), vo = (.+?), and vs = (.+?); calculate observed frequency$",
            c,
            self.answer(self.model(&c[1], &c[2], &c[3], &c[4])?, &[Goal::Frequency])
        );
        self.motion_clauses(input)
    }
}