Skip to main content

qualia_cli/
science.rs

1// science.rs — CLI runners for domain-science modules:
2//   chem, bio, geo, thermo, geometric algebra, clinical, economics
3
4// ── Chemistry ─────────────────────────────────────────────────────────────────
5
6/// CLI: SMILES parse.
7pub fn run_chem_smiles(smiles: &str) {
8    use qualia_core_db::domains::chemical::organic_chemistry::{
9        compute_descriptors, compute_logp, compute_tpsa, evaluate_lipinski, exact_molecular_weight,
10        formula_string, parse_smiles,
11    };
12    let mol = parse_smiles(smiles);
13    let desc = compute_descriptors(&mol);
14    println!("SMILES: {smiles}");
15    println!("  Formula  : {}", formula_string(&mol));
16    println!("  Exact MW : {:.4} Da", exact_molecular_weight(&mol));
17    println!("  LogP     : {:.4}", compute_logp(&mol));
18    println!("  TPSA     : {:.4} Ų", compute_tpsa(&mol));
19    println!("  HBA      : {}", desc.hb_acceptors);
20    println!("  HBD      : {}", desc.hb_donors);
21    println!("  Rot bonds: {}", desc.rotatable_bonds);
22    let lip = evaluate_lipinski(&desc);
23    println!(
24        "  Lipinski : {} (violations: {})",
25        if lip.passes { "PASS" } else { "FAIL" },
26        lip.violations
27    );
28}
29
30/// CLI: thermodynamics.
31pub fn run_chem_thermo(reaction: &str, a: f64, b: f64, c: f64) {
32    use qualia_core_db::domains::chemical::organic_chemistry::{
33        arrhenius_rate, gibbs_free_energy, henderson_hasselbalch,
34    };
35    match reaction.to_ascii_lowercase().as_str() {
36        "arrhenius" => {
37            // a = pre-exponential factor, b = activation energy (J/mol), c = temp (K)
38            let rate = arrhenius_rate(a, b, c);
39            println!("Arrhenius rate: k = {rate:.6e} s⁻¹");
40            println!("  A={a:.3e}, Ea={b:.3e} J/mol, T={c} K");
41        }
42        "gibbs" => {
43            // a = ΔH (kJ/mol), b = ΔS (J/mol·K), c = temp (K)
44            let dg = gibbs_free_energy(a * 1000.0, b, c);
45            println!(
46                "Gibbs free energy: ΔG = {dg:.4} J/mol ({:.4} kJ/mol)",
47                dg / 1000.0
48            );
49            println!("  ΔH={a} kJ/mol, ΔS={b} J/mol·K, T={c} K");
50            println!(
51                "  Spontaneous: {}",
52                if dg < 0.0 {
53                    "yes (ΔG < 0)"
54                } else {
55                    "no (ΔG ≥ 0)"
56                }
57            );
58        }
59        "henderson-hasselbalch" | "hh" => {
60            // a = pKa, b = [base] (M), c = [acid] (M)
61            let ph = henderson_hasselbalch(a, b, c);
62            println!("Henderson-Hasselbalch: pH = {ph:.4}");
63            println!("  pKa={a}, [base]={b} M, [acid]={c} M");
64        }
65        other => {
66            eprintln!("Unknown reaction '{other}'. Use: arrhenius | gibbs | henderson-hasselbalch")
67        }
68    }
69}
70
71/// CLI: drug-likeness.
72pub fn run_chem_druglike(smiles: &str) {
73    use qualia_core_db::domains::chemical::organic_chemistry::{
74        compute_descriptors, compute_logp, compute_tpsa, evaluate_egan, evaluate_ghose,
75        evaluate_lipinski, evaluate_veber, parse_smiles, predict_bbb_permeation,
76    };
77    let mol = parse_smiles(smiles);
78    let desc = compute_descriptors(&mol);
79    let logp = compute_logp(&mol);
80    let tpsa = compute_tpsa(&mol);
81    let lip = evaluate_lipinski(&desc);
82    let veb = evaluate_veber(&desc);
83    let gho = evaluate_ghose(&desc);
84    let ega = evaluate_egan(&desc);
85    let bbb = predict_bbb_permeation(desc.molecular_weight, logp, tpsa, desc.hb_donors);
86    println!("Drug-likeness for SMILES: {smiles}");
87    println!(
88        "  Lipinski : {} (violations: {})",
89        if lip.passes { "PASS" } else { "FAIL" },
90        lip.violations
91    );
92    println!("  Veber    : {}", if veb.passes { "PASS" } else { "FAIL" });
93    println!("  Ghose    : {}", if gho.passes { "PASS" } else { "FAIL" });
94    println!("  Egan     : {}", if ega.passes { "PASS" } else { "FAIL" });
95    println!(
96        "  BBB      : {} (MPO score: {})",
97        if bbb.is_cns_penetrant {
98            "CNS-penetrant"
99        } else {
100            "non-penetrant"
101        },
102        bbb.clark_score
103    );
104}
105
106/// CLI: pKa/Henderson-Hasselbalch.
107pub fn run_chem_pka(pka: f64, conc_base: f64, conc_acid: f64) {
108    use qualia_core_db::domains::chemical::organic_chemistry::{
109        henderson_hasselbalch, ionisation_fraction,
110    };
111    let ph = henderson_hasselbalch(pka, conc_base, conc_acid);
112    let frac = ionisation_fraction(ph, pka);
113    println!("Henderson-Hasselbalch:");
114    println!("  pKa={pka}, [A⁻]={conc_base} M, [HA]={conc_acid} M");
115    println!("  pH              = {ph:.4}");
116    println!("  Ionised fraction= {frac:.4}");
117}
118
119// ── Biology ───────────────────────────────────────────────────────────────────
120
121/// CLI: sequence alignment.
122pub fn run_bio_align(query: &str, target: &str, mode: &str) {
123    use qualia_core_db::domains::biological::bioinformatics::{align_nucleotide, align_protein};
124    let q = query.as_bytes();
125    let t = target.as_bytes();
126    let result = match mode.to_ascii_lowercase().as_str() {
127        "protein" | "aa" => align_protein(q, t),
128        _ => align_nucleotide(q, t),
129    };
130    println!("Sequence alignment ({mode}):");
131    println!("  Query  : {query}");
132    println!("  Target : {target}");
133    println!("  Score  : {}", result.score);
134    println!("  Aligned: {}", result.aligned_query.len());
135    println!("  Gaps   : {}", result.num_gaps);
136    println!("  Matches: {}", result.num_matches);
137}
138
139/// CLI: k-mer analysis.
140pub fn run_bio_kmer(sequence: &str, k: usize) {
141    use qualia_core_db::domains::biological::bioinformatics::kmer_frequencies;
142    let freqs = kmer_frequencies(sequence.as_bytes(), k);
143    println!(
144        "k-mer frequencies (k={k}) for sequence len={}:",
145        sequence.len()
146    );
147    println!("  Distinct k-mers: {}", freqs.len());
148    for (hash, count) in freqs.iter().take(8) {
149        println!("  0x{hash:016x} → {count}");
150    }
151    if freqs.len() > 8 {
152        println!("  … ({} total)", freqs.len());
153    }
154}
155
156/// CLI: DNA translate.
157pub fn run_bio_translate(dna: &str) {
158    use qualia_core_db::domains::biological::bioinformatics::translate_dna_to_protein;
159    let dna_bytes = dna.as_bytes();
160    let mut protein_buf = vec![0u8; dna_bytes.len() / 3 + 1];
161    let n = translate_dna_to_protein(dna_bytes, &mut protein_buf);
162    let protein = std::str::from_utf8(&protein_buf[..n]).unwrap_or("(invalid UTF-8)");
163    println!("DNA → protein translation:");
164    println!("  DNA    : {}", &dna[..dna.len().min(60)]);
165    println!("  Protein: {protein}  ({n} aa)");
166}
167
168/// CLI: isoelectric point.
169pub fn run_bio_isoelectric(protein: &str) {
170    use qualia_core_db::domains::biological::bioinformatics::calculate_isoelectric_point;
171    let pi = calculate_isoelectric_point(protein.as_bytes());
172    println!(
173        "Isoelectric point for protein '{}':",
174        &protein[..protein.len().min(20)]
175    );
176    println!("  pI = {pi:.4}");
177}
178
179/// CLI: Jaccard sketch.
180pub fn run_bio_jaccard(sketch_a: &str, sketch_b: &str) {
181    use qualia_core_db::domains::biological::bioinformatics::jaccard_similarity;
182    let parse_hashes = |s: &str| -> Vec<u64> {
183        s.split(',')
184            .filter_map(|t| {
185                let t = t.trim();
186                if t.starts_with("0x") || t.starts_with("0X") {
187                    u64::from_str_radix(&t[2..], 16).ok()
188                } else {
189                    t.parse::<u64>().ok()
190                }
191            })
192            .collect()
193    };
194    let a = parse_hashes(sketch_a);
195    let b = parse_hashes(sketch_b);
196    let j = jaccard_similarity(&a, &b);
197    println!("Jaccard similarity:");
198    println!("  |sketch A| = {}, |sketch B| = {}", a.len(), b.len());
199    println!("  J(A,B)     = {j:.6}");
200}
201
202/// CLI: MinHash sketch.
203pub fn run_bio_minhash(sequence: &str, k: usize, sketch_size: usize) {
204    use qualia_core_db::domains::biological::bioinformatics::minhash_sketch;
205    let sketch = minhash_sketch(sequence.as_bytes(), k, sketch_size);
206    println!("MinHash sketch (k={k}, size={sketch_size}):");
207    println!("  Sequence len: {}", sequence.len());
208    for h in sketch.iter().take(5) {
209        println!("  0x{h:016x}");
210    }
211    if sketch.len() > 5 {
212        println!("  … ({} total)", sketch.len());
213    }
214}
215
216// ── Geospatial ────────────────────────────────────────────────────────────────
217
218/// CLI: .
219pub fn run_geo_embed_h3(index: u64) {
220    use qualia_core_db::domains::geospatial::spatial::embed_h3_context;
221    let context = embed_h3_context(index, 0, 0);
222    println!("H3 index embedding:");
223    println!("  Input  : 0x{index:016x}");
224    println!("  Context: 0x{context:016x}");
225}
226
227// ── Thermodynamics ────────────────────────────────────────────────────────────
228
229/// CLI: .
230pub fn run_thermo_gibbs(enthalpy: f64, entropy: f64, temp: f64) {
231    use qualia_core_db::domains::physical::thermodynamics::ThermodynamicSampler;
232    let sampler = ThermodynamicSampler::new(temp, 1);
233    let dg = sampler.calculate_gibbs_free_energy(enthalpy, entropy);
234    println!("Gibbs free energy:");
235    println!("  H={enthalpy:.4} J, S={entropy:.4} J/K, T={temp:.1} K");
236    println!("  ΔG = H - TS = {dg:.6} J");
237    println!("  Spontaneous: {}", if dg < 0.0 { "yes" } else { "no" });
238}
239
240/// CLI: .
241pub fn run_thermo_anneal(initial_temp: f64, particles: usize, proposed_energy: f64, random: f64) {
242    use qualia_core_db::domains::physical::thermodynamics::ThermodynamicSampler;
243    let mut sampler = ThermodynamicSampler::new(initial_temp, particles);
244    let accepted = sampler.metropolis_step(proposed_energy, random);
245    println!("Metropolis-Hastings step:");
246    println!("  T_init={initial_temp} K,  particles={particles}");
247    println!("  Proposed ΔE = {proposed_energy:.6}");
248    println!("  Uniform u   = {random:.6}");
249    println!("  Accepted    : {accepted}");
250}
251
252// ── Geometric algebra ─────────────────────────────────────────────────────────
253
254fn parse_vec3(s: &str) -> Option<[f32; 3]> {
255    let v: Vec<f32> = s.split(',').filter_map(|t| t.trim().parse().ok()).collect();
256    if v.len() >= 3 {
257        Some([v[0], v[1], v[2]])
258    } else {
259        eprintln!(
260            "Need 3 comma-separated values for a vector, got {}.",
261            v.len()
262        );
263        None
264    }
265}
266
267/// CLI: .
268pub fn run_geometric_cross(a_str: &str, b_str: &str) {
269    use qualia_core_db::geometric_algebra::utils::{cross_product, dot_product};
270    let (Some(a), Some(b)) = (parse_vec3(a_str), parse_vec3(b_str)) else {
271        return;
272    };
273    let cross = cross_product(&a, &b);
274    let dot = dot_product(&a, &b);
275    println!("Geometric algebra:");
276    println!("  a = [{:.4}, {:.4}, {:.4}]", a[0], a[1], a[2]);
277    println!("  b = [{:.4}, {:.4}, {:.4}]", b[0], b[1], b[2]);
278    println!(
279        "  a×b = [{:.6}, {:.6}, {:.6}]",
280        cross[0], cross[1], cross[2]
281    );
282    println!("  a·b = {dot:.6}");
283}
284
285/// CLI: .
286pub fn run_geometric_angle(a_str: &str, b_str: &str) {
287    use qualia_core_db::geometric_algebra::utils::{angle_between_vectors, rad_to_deg};
288    let (Some(a), Some(b)) = (parse_vec3(a_str), parse_vec3(b_str)) else {
289        return;
290    };
291    let angle_rad = angle_between_vectors(&a, &b);
292    let angle_deg = rad_to_deg(angle_rad);
293    println!("Angle between vectors:");
294    println!("  a = [{:.4}, {:.4}, {:.4}]", a[0], a[1], a[2]);
295    println!("  b = [{:.4}, {:.4}, {:.4}]", b[0], b[1], b[2]);
296    println!("  θ = {angle_rad:.6} rad  ({angle_deg:.4}°)");
297}
298
299// ── Clinical ──────────────────────────────────────────────────────────────────
300
301/// CLI: .
302pub fn run_clinical_framingham(
303    age: u8,
304    sex_male: bool,
305    total_chol: f64,
306    hdl_chol: f64,
307    systolic_bp: f64,
308    bp_treated: bool,
309    smoker: bool,
310    diabetic: bool,
311) {
312    use qualia_core_db::clinical_engine::{framingham_10yr_risk, FraminghamInput};
313    let input = FraminghamInput {
314        age,
315        sex_male,
316        total_cholesterol_mmol: total_chol,
317        hdl_cholesterol_mmol: hdl_chol,
318        systolic_bp,
319        bp_treated,
320        current_smoker: smoker,
321        diabetic,
322    };
323    let r = framingham_10yr_risk(&input);
324    println!("Framingham 10-year CVD risk:");
325    println!(
326        "  Age={age}, sex={}, TC={total_chol:.2} mmol/L, HDL={hdl_chol:.2}, SBP={systolic_bp:.0}",
327        if sex_male { "M" } else { "F" }
328    );
329    println!("  Treated={bp_treated}, Smoker={smoker}, Diabetic={diabetic}");
330    println!("  Risk     : {:.1}%", r.risk_10yr * 100.0);
331    println!("  Category : {:?}", r.category);
332    println!("  Log score: {:.4}", r.log_score);
333}
334
335/// CLI: .
336pub fn run_clinical_sofa(
337    pao2_fio2: f64,
338    platelets: f64,
339    bilirubin: f64,
340    map: f64,
341    gcs: u8,
342    creatinine: f64,
343) {
344    use qualia_core_db::clinical_engine::{sofa_score, SofaInput};
345    let input = SofaInput {
346        pao2_fio2_ratio: pao2_fio2,
347        platelets_10_9_l: platelets,
348        bilirubin_mg_dl: bilirubin,
349        map_mmhg: map,
350        dopamine_dose: 0.0,
351        epinephrine_dose: 0.0,
352        norepinephrine_dose: 0.0,
353        glasgow_coma_scale: gcs,
354        creatinine_mg_dl: creatinine,
355        urine_output_ml_d: 500.0,
356    };
357    let score = sofa_score(&input);
358    println!("SOFA score (Sequential Organ Failure Assessment):");
359    println!("  PaO₂/FiO₂={pao2_fio2}, Platelets={platelets}×10⁹/L");
360    println!("  Bilirubin={bilirubin} mg/dL, MAP={map} mmHg, GCS={gcs}");
361    println!("  Creatinine={creatinine} mg/dL");
362    println!("  SOFA score: {score}/24");
363    let mortality = match score {
364        0..=1 => "<10%",
365        2..=3 => "~10%",
366        4..=5 => "~20%",
367        6..=7 => "~20–30%",
368        8..=9 => "~40%",
369        10..=11 => "~40–50%",
370        12..=14 => ">50%",
371        _ => ">80%",
372    };
373    println!("  Est. mortality: {mortality}");
374}
375
376/// CLI: .
377pub fn run_clinical_ckd(age: u8, sex_male: bool, weight_kg: f64, creatinine: f64) {
378    use qualia_core_db::clinical_engine::{ckd_epi_egfr, cockcroft_gault_crcl, RenalInput};
379    let input = RenalInput {
380        age,
381        sex_male,
382        weight_kg,
383        serum_creatinine: creatinine,
384    };
385    let crcl = cockcroft_gault_crcl(&input);
386    let egfr = ckd_epi_egfr(&input);
387    println!("Renal function:");
388    println!(
389        "  Age={age}, sex={}, weight={weight_kg} kg, Cr={creatinine} mg/dL",
390        if sex_male { "M" } else { "F" }
391    );
392    println!("  CrCl (Cockcroft-Gault) : {crcl:.1} mL/min");
393    println!("  eGFR (CKD-EPI 2021)    : {egfr:.1} mL/min/1.73m²");
394    let stage = match egfr as u32 {
395        90..=u32::MAX => "G1 (normal)",
396        60..=89 => "G2 (mildly decreased)",
397        45..=59 => "G3a (mild-moderate)",
398        30..=44 => "G3b (moderate-severe)",
399        15..=29 => "G4 (severe)",
400        _ => "G5 (kidney failure)",
401    };
402    println!("  CKD stage              : {stage}");
403}
404
405/// CLI: .
406pub fn run_clinical_pk(dose_mg: f64, vd_l: f64, cl_l_hr: f64, time_hr: f64) {
407    use qualia_core_db::clinical_engine::{one_compartment_pk_model, PkOneCompartmentInput};
408    let input = PkOneCompartmentInput {
409        dose_mg,
410        volume_distribution_l: vd_l,
411        clearance_l_hr: cl_l_hr,
412        time_hr,
413    };
414    let r = one_compartment_pk_model(&input);
415    println!("1-compartment PK model (IV bolus):");
416    println!("  Dose={dose_mg} mg, Vd={vd_l} L, CL={cl_l_hr} L/hr");
417    println!("  C(t={time_hr}h) = {:.4} mg/L", r.concentration);
418    println!("  Half-life      = {:.4} hr", r.half_life_hr);
419}
420
421/// CLI: .
422pub fn run_clinical_drug_interactions(drug_names: &str) {
423    use qualia_core_db::clinical_engine::check_drug_interactions;
424    use qualia_core_db::mini_parser::hash_token;
425    let hashes: Vec<u64> = drug_names
426        .split(',')
427        .map(|s| hash_token(s.trim()))
428        .collect();
429    let interactions = check_drug_interactions(&hashes);
430    println!("Drug interaction screening for: {drug_names}");
431    if interactions.is_empty() {
432        println!("  No known interactions found.");
433    } else {
434        for ix in &interactions {
435            println!(
436                "  [{:?}] 0x{:x} ↔ 0x{:x}: {}",
437                ix.severity, ix.drug_a, ix.drug_b, ix.mechanism
438            );
439        }
440    }
441}
442
443// ── Economics ─────────────────────────────────────────────────────────────────
444
445/// CLI: .
446pub fn run_economics_gbm(price: f64, drift: f64, vol: f64, horizon: f64, steps: usize) {
447    use qualia_core_db::domains::financial::economics::simulate_gbm_path;
448    let final_price = simulate_gbm_path(price, drift, vol, horizon, steps);
449    println!("Geometric Brownian Motion path:");
450    println!("  S₀={price}, μ={drift}, σ={vol}, T={horizon}, steps={steps}");
451    println!("  S(T) ≈ {final_price:.4}");
452    let expected = price * (drift * horizon).exp();
453    println!("  E[S(T)] = {expected:.4}  (drift-only estimate)");
454}
455
456/// CLI: .
457pub fn run_economics_var(
458    price: f64,
459    drift: f64,
460    vol: f64,
461    horizon: f64,
462    steps: usize,
463    paths: usize,
464) {
465    use qualia_core_db::domains::financial::economics::run_monte_carlo_var;
466    println!("Monte Carlo VaR (paths={paths}, steps={steps})…");
467    let (mean, var95) = run_monte_carlo_var(price, drift, vol, horizon, steps, paths);
468    println!("  S₀={price}, μ={drift}, σ={vol}, T={horizon}");
469    println!("  Mean end value : {mean:.4}");
470    println!("  95% VaR (loss) : {var95:.4}");
471}
472
473/// CLI: .
474pub fn run_economics_macro(
475    m0: f64,
476    p0: f64,
477    velocity: f64,
478    real_gdp: f64,
479    horizon: f64,
480    steps: usize,
481) {
482    use qualia_core_db::domains::financial::economics::simulate_macroeconomic_flow;
483    let state = simulate_macroeconomic_flow(m0, p0, velocity, real_gdp, horizon, steps);
484    println!("Macroeconomic flow (M×V = P×Q):");
485    println!("  M₀={m0}, P₀={p0}, V={velocity}, Q={real_gdp}, T={horizon}");
486    if state.values.len() >= 2 {
487        println!("  M(T) = {:.4}", state.values[0]);
488        println!("  P(T) = {:.4}", state.values[1]);
489        println!(
490            "  Implied Q = {:.4}",
491            (state.values[0] * velocity) / state.values[1]
492        );
493    }
494}
495
496/// CLI: .
497pub fn run_economics_bond(face: f64, coupon_rate: f64, y: f64, n: u32) {
498    use qualia_core_db::specialized_libs::computational_economics::fixed_income::coupon_bond_price;
499    match coupon_bond_price(face, coupon_rate, y, n as f64, 1) {
500        Ok(p) => {
501            println!("Coupon bond price (face={face}, c={coupon_rate}, y={y}, n={n}): {p:.4}");
502            println!("  (clean price, par=100 equivalent would be face)");
503        }
504        Err(_) => println!("Bond pricing failed (invalid inputs)."),
505    }
506}
507
508/// CLI: .
509pub fn run_economics_paper(qty: f64, last: f64) {
510    use qualia_core_db::specialized_libs::computational_economics::paper_trading::{
511        simulate_fills_against_snapshots, submit_paper_order, Fill, MarketSnapshot, OrderType,
512        PaperOrder, Side,
513    };
514    let mut book: [PaperOrder; 8] = [PaperOrder {
515        id: 0,
516        side: Side::Buy,
517        order_type: OrderType::Market,
518        qty: 0.0,
519        limit_price: 0.0,
520        stop_price: 0.0,
521        filled_qty: 0.0,
522        avg_fill_price: 0.0,
523        status: 0,
524    }; 8];
525    let mut next_id = 1u64;
526    if submit_paper_order(
527        &mut book,
528        &mut next_id,
529        Side::Buy,
530        OrderType::Market,
531        qty,
532        0.0,
533        0.0,
534    )
535    .is_ok()
536    {
537        let snaps = [MarketSnapshot {
538            bid: last - 0.1,
539            ask: last + 0.1,
540            last,
541            volume: 500.0,
542        }];
543        let mut fills: [Fill; 8] = [Fill {
544            order_id: 0,
545            qty: 0.0,
546            price: 0.0,
547            fee: 0.0,
548        }; 8];
549        let _ = simulate_fills_against_snapshots(&mut book, &snaps, 0.001, &mut fills);
550        println!("Paper trade demo: market buy {qty} @~{last}");
551        println!("  (simulation only; no real execution or ledger mutation)");
552    } else {
553        println!("Paper order submit failed.");
554    }
555}
556
557/// CLI: .
558pub fn run_economics_welfare(incomes_str: &str) {
559    use qualia_core_db::specialized_libs::computational_economics::welfare::{
560        atkinson_inequality, gini_coefficient,
561    };
562    let incomes: Vec<f64> = incomes_str
563        .split(',')
564        .filter_map(|s| s.trim().parse().ok())
565        .collect();
566    if incomes.is_empty() {
567        println!("Invalid incomes");
568        return;
569    }
570    if let Ok(g) = gini_coefficient(&incomes) {
571        println!("Gini: {g:.4}");
572    }
573    if let Ok(a) = atkinson_inequality(&incomes, 1.0) {
574        println!("Atkinson (eps=1): {a:.4}");
575    }
576}
577
578/// CLI: .
579pub fn run_economics_game(a: f64) {
580    use qualia_core_db::specialized_libs::computational_economics::game_theory::cournot_duopoly;
581    match cournot_duopoly(a, 1.0, 1.0, 1.0) {
582        Ok((q1, q2, p)) => {
583            // Profits: pi_i = (p - c_i) * q_i, with c1 = c2 = 1.0.
584            let pi1 = (p - 1.0) * q1;
585            let pi2 = (p - 1.0) * q2;
586            println!(
587                "Cournot duopoly (a={a}): q1={q1:.2} q2={q2:.2} p={p:.2} pi1={pi1:.2} pi2={pi2:.2}"
588            );
589        }
590        Err(e) => println!("Cournot duopoly (a={a}): no equilibrium ({e:?})"),
591    }
592}