Skip to main content

symbolica_integrate/
lib.rs

1//! Rule-based integration for Symbolica.
2//!
3//! This crate implements Rubi's rule-based integration
4//! system for Symbolica expressions. Rubi was created by Albert D. Rich,
5//! with later assistance from Patrick Scheibe, Nasser M. Abbasi and others.
6//!
7//! See the [Rubi project website](https://rulebasedintegration.org/) for more information.
8//!
9//! # Example
10//! ```
11//! use symbolica::prelude::*;
12//! use symbolica_integrate::Integrate;
13//!
14//! let x = symbol!("x");
15//! let r = parse!("x*cos(x)").integrate(x);
16//! assert_eq!(r.unwrap(), parse!("cos(x)+x*sin(x)"));
17//! ```
18
19#![cfg_attr(docsrs, feature(doc_cfg))]
20#![deny(clippy::disallowed_methods)]
21#![warn(missing_docs)]
22
23use std::{
24    cell::{Cell, RefCell},
25    cmp::Ordering,
26    collections::BTreeMap,
27    sync::{
28        Arc, LazyLock, Mutex,
29        atomic::{AtomicBool, Ordering as AtomicOrdering},
30    },
31};
32
33#[cfg(feature = "trace")]
34use std::sync::{
35    RwLock,
36    atomic::{AtomicU64, AtomicUsize},
37};
38
39#[cfg(all(feature = "steps", feature = "compressed-step-metadata"))]
40use std::sync::OnceLock;
41
42use symbolica::domains::{
43    float::Complex,
44    integer::{Integer, IntegerRing},
45    rational::Rational,
46};
47use symbolica::prelude::*;
48
49/// Global Rubi tracing settings.
50#[cfg(feature = "trace")]
51pub struct RubiSettings {
52    /// Print each integration call and its result.
53    pub trace_rules: AtomicBool,
54    /// Periodically print the number of rules scanned for an integral.
55    pub trace_scan_progress: AtomicBool,
56    /// Number of scanned rules between progress messages.
57    pub trace_scan_progress_interval: AtomicUsize,
58    /// Number of rules to scan before the first progress message.
59    pub trace_scan_progress_start: AtomicUsize,
60    /// Report time spent in the major phases of rule dispatch.
61    pub trace_rule_phase_timings: AtomicBool,
62    /// Minimum rule-phase duration, in milliseconds, to report.
63    pub trace_rule_phase_timing_ms: AtomicU64,
64    /// Print rules whose conditions and actions are accepted.
65    pub trace_accepted: AtomicBool,
66    /// Include the input expression when printing an accepted rule.
67    pub trace_accepted_inputs: AtomicBool,
68    /// Report the total time spent evaluating individual rules.
69    pub trace_rule_timings: AtomicBool,
70    /// Minimum per-rule duration, in milliseconds, to report.
71    pub trace_rule_timing_ms: AtomicU64,
72    /// Report time spent in pattern matching for individual rules.
73    pub trace_match_timings: AtomicBool,
74    /// Minimum match duration, in milliseconds, to report.
75    pub trace_match_timing_ms: AtomicU64,
76    /// Print calls to selected Rubi helper functions.
77    pub trace_helpers: AtomicBool,
78    /// Print helper-rule scan activity.
79    pub trace_helper_scan: AtomicBool,
80    /// Print candidate rules produced by pattern matching.
81    pub trace_candidates: AtomicBool,
82    /// Print wildcard bindings for candidate rules.
83    pub trace_bindings: AtomicBool,
84    /// Report time spent evaluating rule conditions.
85    pub trace_condition_timings: AtomicBool,
86    /// Minimum condition duration, in milliseconds, to report.
87    pub trace_condition_timing_ms: AtomicU64,
88    /// Print fallback integration paths when they are attempted.
89    pub trace_fallbacks: AtomicBool,
90    /// Optional substring used to restrict trace output to matching rule IDs.
91    pub trace_rule_filter: RwLock<Option<String>>,
92}
93
94/// Global Rubi tracing settings.
95#[cfg(feature = "trace")]
96pub static RUBI_SETTINGS: RubiSettings = RubiSettings {
97    trace_rules: AtomicBool::new(false),
98    trace_scan_progress: AtomicBool::new(false),
99    trace_scan_progress_interval: AtomicUsize::new(500),
100    trace_scan_progress_start: AtomicUsize::new(0),
101    trace_rule_phase_timings: AtomicBool::new(false),
102    trace_rule_phase_timing_ms: AtomicU64::new(10),
103    trace_accepted: AtomicBool::new(false),
104    trace_accepted_inputs: AtomicBool::new(false),
105    trace_rule_timings: AtomicBool::new(false),
106    trace_rule_timing_ms: AtomicU64::new(10),
107    trace_match_timings: AtomicBool::new(false),
108    trace_match_timing_ms: AtomicU64::new(10),
109    trace_helpers: AtomicBool::new(false),
110    trace_helper_scan: AtomicBool::new(false),
111    trace_candidates: AtomicBool::new(false),
112    trace_bindings: AtomicBool::new(false),
113    trace_condition_timings: AtomicBool::new(false),
114    trace_condition_timing_ms: AtomicU64::new(10),
115    trace_fallbacks: AtomicBool::new(false),
116    trace_rule_filter: RwLock::new(None),
117};
118
119#[cfg(feature = "trace")]
120fn rubi_trace_rule_matches(rule: &RubiRule) -> bool {
121    RUBI_SETTINGS
122        .trace_rule_filter
123        .read()
124        .unwrap_or_else(|poison| poison.into_inner())
125        .as_deref()
126        .is_none_or(|filter| rule.id.contains(filter))
127}
128
129#[cfg(feature = "trace")]
130impl RubiSettings {
131    /// Load the legacy `RUBI_TRACE_*` environment variables once during
132    /// Symbolica/Rubi initialization. Programmatic changes to the public
133    /// settings remain possible afterwards.
134    pub fn load_trace_environment(&self) {
135        fn enable_from_env(name: &str, setting: &AtomicBool) {
136            if std::env::var_os(name).is_some() {
137                setting.store(true, AtomicOrdering::Relaxed);
138            }
139        }
140
141        fn usize_from_env(name: &str, setting: &AtomicUsize) {
142            if let Some(value) = std::env::var(name)
143                .ok()
144                .and_then(|value| value.parse::<usize>().ok())
145            {
146                setting.store(value, AtomicOrdering::Relaxed);
147            }
148        }
149
150        fn u64_from_env(name: &str, setting: &AtomicU64) {
151            if let Some(value) = std::env::var(name)
152                .ok()
153                .and_then(|value| value.parse::<u64>().ok())
154            {
155                setting.store(value, AtomicOrdering::Relaxed);
156            }
157        }
158
159        enable_from_env("RUBI_TRACE_RULES", &self.trace_rules);
160        enable_from_env("RUBI_TRACE_SCAN_PROGRESS", &self.trace_scan_progress);
161        enable_from_env(
162            "RUBI_TRACE_RULE_PHASE_TIMINGS",
163            &self.trace_rule_phase_timings,
164        );
165        enable_from_env("RUBI_TRACE_ACCEPTED", &self.trace_accepted);
166        enable_from_env("RUBI_TRACE_ACCEPTED_INPUTS", &self.trace_accepted_inputs);
167        enable_from_env("RUBI_TRACE_RULE_TIMINGS", &self.trace_rule_timings);
168        enable_from_env("RUBI_TRACE_MATCH_TIMINGS", &self.trace_match_timings);
169        enable_from_env("RUBI_TRACE_HELPERS", &self.trace_helpers);
170        enable_from_env("RUBI_TRACE_HELPER_SCAN", &self.trace_helper_scan);
171        enable_from_env("RUBI_TRACE_CANDIDATES", &self.trace_candidates);
172        enable_from_env("RUBI_TRACE_BINDINGS", &self.trace_bindings);
173        enable_from_env(
174            "RUBI_TRACE_CONDITION_TIMINGS",
175            &self.trace_condition_timings,
176        );
177        enable_from_env("RUBI_TRACE_FALLBACKS", &self.trace_fallbacks);
178
179        usize_from_env(
180            "RUBI_TRACE_SCAN_PROGRESS_INTERVAL",
181            &self.trace_scan_progress_interval,
182        );
183        usize_from_env(
184            "RUBI_TRACE_SCAN_PROGRESS_START",
185            &self.trace_scan_progress_start,
186        );
187        u64_from_env(
188            "RUBI_TRACE_RULE_PHASE_TIMING_MS",
189            &self.trace_rule_phase_timing_ms,
190        );
191        u64_from_env("RUBI_TRACE_RULE_TIMING_MS", &self.trace_rule_timing_ms);
192        u64_from_env("RUBI_TRACE_MATCH_TIMING_MS", &self.trace_match_timing_ms);
193        u64_from_env(
194            "RUBI_TRACE_CONDITION_TIMING_MS",
195            &self.trace_condition_timing_ms,
196        );
197
198        if let Ok(filter) = std::env::var("RUBI_TRACE_RULE_FILTER") {
199            *self
200                .trace_rule_filter
201                .write()
202                .unwrap_or_else(|poison| poison.into_inner()) = Some(filter);
203        }
204    }
205}
206
207symbolica::initialize!(|| {
208    let _ = rubi_symbols();
209    #[cfg(feature = "trace")]
210    RUBI_SETTINGS.load_trace_environment();
211});
212
213/// Compute a best-effort antiderivative with scoped cancellation state.
214///
215/// Cancellation is checked at integration call boundaries, including recursive
216/// rule calls. A completed primitive is returned as `Some(Ok(_))`;
217/// `Some(Err(_))` carries an unfinished primitive for an unsupported integrand.
218pub fn integrate_with_abort<T: AtomCore>(expr: T, x: Symbol) -> Option<Result<Atom, Atom>> {
219    let abort = AtomicBool::new(false);
220    integrate_with_abort_impl(expr, x, &abort)
221}
222
223/// Internal cancellation-aware integration entry point used by watchdogs.
224#[doc(hidden)]
225pub fn integrate_with_abort_impl<T: AtomCore>(
226    expr: T,
227    x: Symbol,
228    abort: &AtomicBool,
229) -> Option<Result<Atom, Atom>> {
230    let _abort_signal = AbortSignal::push(abort);
231    if rubi_abort_requested() {
232        return None;
233    }
234
235    let result = integrate(expr.as_atom_view(), x);
236    (!rubi_abort_requested()).then_some(result)
237}
238
239/// Compute a best-effort antiderivative of `expr` with respect to `x`.
240///
241/// This is the main public entry point for the Symbolica-native Rubi rule
242/// layer.
243///
244/// # Examples
245///
246/// ```
247/// use symbolica_integrate::Integrate;
248/// use symbolica::prelude::*;
249///
250/// let x = symbol!("x");
251/// let integrand = parse!("x*sin(x)");
252/// let antiderivative = integrand.integrate(x).expect("rule should apply");
253/// let residual = (antiderivative.derivative(x) - integrand).expand();
254///
255/// assert!(residual.is_zero());
256/// ```
257///
258/// ```
259/// use symbolica_integrate::Integrate;
260/// use symbolica::prelude::*;
261///
262/// let x = symbol!("x");
263/// let integrand = parse!("1/(1 + exp(x))^2");
264/// let antiderivative = integrand.integrate(x).expect("rule should apply");
265/// let residual = (antiderivative.derivative(x) - integrand)
266///     .expand()
267///     .together();
268///
269/// assert!(residual.is_zero());
270/// ```
271pub(crate) fn integrate<T: AtomCore>(expr: T, x: Symbol) -> Result<Atom, Atom> {
272    let expr = expr.as_atom_view();
273    if let Some(attempt) = integrate_internal(expr, x) {
274        return if rubi_finished_primitive_q(&attempt) {
275            Ok(attempt)
276        } else {
277            Err(attempt)
278        };
279    }
280
281    Err(rubi_unintegrable(expr.to_owned(), x))
282}
283
284/// One accepted Rubi transformation in an integration derivation.
285///
286/// This type is available only with the `steps` feature because retaining
287/// the upstream rule sources and descriptions substantially increases binary
288/// size.
289#[cfg(feature = "steps")]
290#[allow(clippy::disallowed_methods)]
291#[derive(Clone, Debug)]
292pub struct IntegrationStep {
293    /// Rubi's downvalue number for the applied rule, when one is available.
294    pub rule: Option<u16>,
295    /// Zero-based depth of this transformation in the recursive integration tree.
296    pub depth: usize,
297    /// Rubi's notebook derivation, or a fallback transformation description.
298    pub description: &'static str,
299    /// Bibliographic references listed for this rule in the upstream notebook.
300    /// - **G&R** — *Table of Integrals, Series, and Products*, fifth edition,
301    ///   I. S. Gradshteyn, I. M. Ryzhik, and Alan Jeffrey, editors.
302    /// - **CRC** — *CRC Standard Mathematical Tables and Formulae*, 29th edition,
303    ///   William H. Beyer, editor.
304    /// - **A&S** — *Handbook of Mathematical Functions*, Milton Abramowitz and
305    ///   Irene A. Stegun, editors.
306    pub references: &'static [&'static str],
307    /// The original Mathematica rule or pattern from the Rubi distribution.
308    pub source: &'static str,
309    /// The integrand to which the rule was applied.
310    pub input: Atom,
311    /// The immediate right-hand side produced by the rule.
312    ///
313    /// Recursive integrals remain structurally represented as
314    /// `rubi_int(integrand, variable)` instead of being replaced by their
315    /// eventual antiderivatives. The default printer renders them as
316    /// `∫ integrand dvariable`.
317    pub output: Atom,
318}
319
320/// The result and ordered Rubi rule derivation of an integration attempt.
321///
322/// Steps are ordered from the outer transformation to its recursively solved
323/// subintegrals, matching the presentation order of Rubi's `ShowSteps` mode.
324#[cfg(feature = "steps")]
325#[allow(clippy::disallowed_methods)]
326#[derive(Clone, Debug)]
327pub struct IntegrationExplanation {
328    /// The same best-effort result returned by [`Integrate::integrate`].
329    pub result: Result<Atom, Atom>,
330    /// Transformations taken while computing `result`.
331    pub steps: Vec<IntegrationStep>,
332}
333
334#[cfg(feature = "steps")]
335impl std::fmt::Display for IntegrationExplanation {
336    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
337        for (index, step) in self.steps.iter().enumerate() {
338            if index != 0 {
339                formatter.write_str("\n")?;
340            }
341            for _ in 0..step.depth {
342                formatter.write_str("  ")?;
343            }
344            write!(formatter, "{} = {}", step.input, step.output)?;
345        }
346        if !self.steps.is_empty() {
347            formatter.write_str("\n")?;
348        }
349        let result = match &self.result {
350            Ok(result) | Err(result) => result,
351        };
352        write!(formatter, "= {result}")?;
353        Ok(())
354    }
355}
356
357macro_rules! unary_integration_symbol_methods {
358    ($(
359        $(#[$meta:meta])*
360        $method:ident => $symbol:ident;
361    )*) => {
362        $(
363            $(#[$meta])*
364            fn $method(&self) -> Atom {
365                unary_integration_symbol(self, rubi_symbols().$symbol)
366            }
367        )*
368    };
369}
370
371/// Convenience methods for the function symbols provided by this crate.
372///
373/// This extension trait is implemented for every type that implements
374/// [`AtomCore`]. Import it to construct expressions such as `x.fresnel_s()`,
375/// `x.exp_integral_e(n)`, and `x.product_log()` without spelling the
376/// `symbolica_integrate` namespace explicitly.
377///
378/// # Example
379///
380/// ```
381/// use symbolica::prelude::*;
382/// use symbolica_integrate::IntegralFunctions;
383///
384/// let x = parse!("x");
385/// assert_eq!(
386///     x.fresnel_s(),
387///     parse!("symbolica_integrate::fresnel_s(x)"),
388/// );
389/// ```
390pub trait IntegralFunctions: AtomCore {
391    unary_integration_symbol_methods! {
392        /// Apply the complementary error function.
393        erfc => erfc;
394        /// Apply the imaginary error function.
395        erfi => erfi;
396        /// Apply the Fresnel sine integral.
397        fresnel_s => fresnel_s;
398        /// Apply the Fresnel cosine integral.
399        fresnel_c => fresnel_c;
400        /// Apply the exponential integral Ei.
401        exp_integral_ei => exp_integral_ei;
402        /// Apply the logarithmic integral.
403        log_integral => log_integral;
404        /// Apply the sine integral.
405        sin_integral => sin_integral;
406        /// Apply the cosine integral.
407        cos_integral => cos_integral;
408        /// Apply the hyperbolic sine integral.
409        sinh_integral => sinh_integral;
410        /// Apply the hyperbolic cosine integral.
411        cosh_integral => cosh_integral;
412        /// Apply the product logarithm (Lambert W function).
413        product_log => product_log;
414        /// Apply the logarithm of the gamma function.
415        log_gamma => log_gamma;
416        /// Apply the factorial function.
417        factorial => factorial;
418    }
419
420    /// Apply the generalized exponential integral `E_n(self)`.
421    fn exp_integral_e<T: FunctionArgument>(&self, n: T) -> Atom {
422        rubi_symbols().exp_integral_e.call((n, self.as_atom_view()))
423    }
424
425    /// Apply the upper incomplete gamma function `Gamma(a, self)`.
426    fn rubi_gamma<T: FunctionArgument>(&self, a: T) -> Atom {
427        rubi_symbols().gamma.call((a, self.as_atom_view()))
428    }
429
430    /// Apply the incomplete elliptic integral of the second kind `E(self, m)`.
431    fn elliptic_e<T: FunctionArgument>(&self, m: T) -> Atom {
432        rubi_symbols().elliptic_e.call((self.as_atom_view(), m))
433    }
434
435    /// Apply the incomplete elliptic integral of the first kind `F(self, m)`.
436    fn elliptic_f<T: FunctionArgument>(&self, m: T) -> Atom {
437        rubi_symbols().elliptic_f.call((self.as_atom_view(), m))
438    }
439
440    /// Apply the incomplete elliptic integral of the third kind `Pi(n, self, m)`.
441    fn elliptic_pi<N, M>(&self, n: N, m: M) -> Atom
442    where
443        N: FunctionArgument,
444        M: FunctionArgument,
445    {
446        rubi_symbols().elliptic_pi.call((n, self.as_atom_view(), m))
447    }
448
449    /// Apply the Gauss hypergeometric function `2F1(a, b; c; self)`.
450    fn hypergeometric_2f1<A, B, C>(&self, a: A, b: B, c: C) -> Atom
451    where
452        A: FunctionArgument,
453        B: FunctionArgument,
454        C: FunctionArgument,
455    {
456        rubi_symbols()
457            .hypergeometric2f1
458            .call((a, b, c, self.as_atom_view()))
459    }
460
461    /// Apply Appell's first hypergeometric function `F1(a,b1,b2;c;self,y)`.
462    fn appell_f1<A, B1, B2, C, Y>(&self, a: A, b1: B1, b2: B2, c: C, y: Y) -> Atom
463    where
464        A: FunctionArgument,
465        B1: FunctionArgument,
466        B2: FunctionArgument,
467        C: FunctionArgument,
468        Y: FunctionArgument,
469    {
470        rubi_symbols()
471            .appell_f1
472            .call((a, b1, b2, c, self.as_atom_view(), y))
473    }
474}
475
476impl<T: AtomCore> IntegralFunctions for T {}
477
478fn unary_integration_symbol<T: AtomCore>(argument: &T, symbol: Symbol) -> Atom {
479    symbol.call(argument.as_atom_view())
480}
481
482/// Integrate an expression and retain the Rubi transformations that solved it.
483///
484/// Rubi's Mathematica implementation displays a rule number, condition, and
485/// exact left-to-right transformation rather than storing prose for every
486/// downvalue. This port retains that exact source formula together with the
487/// notebook's derivation and bibliographic references when available.
488///
489/// This function is available only with the `steps` feature.
490#[cfg(feature = "steps")]
491pub(crate) fn integrate_with_steps(expr: AtomView<'_>, x: Symbol) -> IntegrationExplanation {
492    let collector = RubiExplanationCollector::push();
493    let result = integrate(expr, x);
494    let steps = collector.finish();
495    IntegrationExplanation { result, steps }
496}
497
498/// Add Rubi integration to every Symbolica expression type implementing [`AtomCore`].
499pub trait Integrate: AtomCore {
500    /// Compute an antiderivative with respect to `x`.
501    /// # Example
502    ///
503    /// ```
504    /// use symbolica::prelude::*;
505    /// use symbolica_integrate::Integrate;
506    ///
507    /// let x = symbol!("x");
508    /// let r = parse!("x*cos(x)").integrate(x);
509    /// assert_eq!(r.unwrap(), parse!("cos(x)+x*sin(x)"));
510    /// ```
511    fn integrate(&self, x: Symbol) -> Result<Atom, Atom> {
512        integrate(self.as_atom_view(), x)
513    }
514
515    /// Integrate by parts using `self` as `u` and `v_prime` as `v'`.
516    ///
517    /// # Example
518    ///
519    /// ```
520    /// use symbolica::prelude::*;
521    /// use symbolica_integrate::Integrate;
522    ///
523    /// let x = symbol!("x");
524    /// let u = parse!("x");
525    /// let v_prime = parse!("sin(x)");
526    /// let antiderivative = u
527    ///     .integrate_by_parts(&v_prime, x)
528    ///     .expect("split should integrate");
529    /// let residual = (antiderivative.derivative(x) - u * v_prime).expand();
530    ///
531    /// assert!(residual.is_zero());
532    /// ```
533    fn integrate_by_parts<V: AtomCore>(&self, v_prime: &V, x: Symbol) -> Result<Atom, Atom> {
534        integration_by_parts(self.as_atom_view(), v_prime.as_atom_view(), x)
535    }
536
537    /// Integrate with respect to `x` and returns the transformation steps.
538    ///
539    /// # Example
540    ///
541    /// ```
542    /// use symbolica::prelude::*;
543    /// use symbolica_integrate::Integrate;
544    ///
545    /// let x = symbol!("x");
546    /// let explanation = parse!("x/(x+1)").integrate_with_steps(x);
547    /// ```
548    ///
549    /// yields
550    ///
551    /// ```log
552    /// ∫ x/(1+x) dx = ∫ 1-1/(1+x) dx
553    ///   ∫ 1-1/(1+x) dx = ∫ 1 dx+∫ 1/(-1-x) dx
554    ///       ∫ 1 dx = x
555    ///       ∫ -1/(1+x) dx = -log(1+x)
556    ///   = x-log(1+x)
557    /// ```
558    ///
559    /// Detailed rule walkthrough including bibliographic references
560    /// can be obtained from the [IntegrationExplanation] object.
561    ///
562    /// This method is available only with the `steps` feature.
563    #[cfg(feature = "steps")]
564    fn integrate_with_steps(&self, x: Symbol) -> IntegrationExplanation {
565        integrate_with_steps(self.as_atom_view(), x)
566    }
567}
568
569impl<T: AtomCore> Integrate for T {}
570
571/// Convenience constructors for functions applied to a Symbolica symbol.
572trait RubiSymbolAtomOps {
573    fn log(&self) -> Atom;
574    fn sqrt(&self) -> Atom;
575}
576
577impl RubiSymbolAtomOps for Symbol {
578    fn log(&self) -> Atom {
579        Atom::var(*self).log()
580    }
581
582    fn sqrt(&self) -> Atom {
583        Atom::var(*self).sqrt()
584    }
585}
586
587/// Converts values accepted by translated Rubi rules into Symbolica atoms.
588trait RubiAtomArgument {
589    fn rubi_atom(&self) -> Atom;
590
591    fn into_rubi_atom(self) -> Atom
592    where
593        Self: Sized,
594    {
595        self.rubi_atom()
596    }
597
598    fn rubi_atom_or_view(&self) -> AtomOrView<'_> {
599        self.rubi_atom().into()
600    }
601}
602
603impl RubiAtomArgument for Atom {
604    fn rubi_atom(&self) -> Atom {
605        self.to_owned()
606    }
607
608    fn into_rubi_atom(self) -> Atom {
609        self
610    }
611
612    fn rubi_atom_or_view(&self) -> AtomOrView<'_> {
613        AtomOrView::View(self.as_view())
614    }
615}
616
617impl RubiAtomArgument for AtomView<'_> {
618    fn rubi_atom(&self) -> Atom {
619        self.to_owned()
620    }
621
622    fn rubi_atom_or_view(&self) -> AtomOrView<'_> {
623        AtomOrView::View(*self)
624    }
625}
626
627impl RubiAtomArgument for Symbol {
628    fn rubi_atom(&self) -> Atom {
629        Atom::var(*self)
630    }
631
632    fn rubi_atom_or_view(&self) -> AtomOrView<'_> {
633        (*self).into()
634    }
635}
636
637impl<T: RubiAtomArgument + ?Sized> RubiAtomArgument for &T {
638    fn rubi_atom(&self) -> Atom {
639        (*self).rubi_atom()
640    }
641
642    fn rubi_atom_or_view(&self) -> AtomOrView<'_> {
643        (*self).rubi_atom_or_view()
644    }
645}
646
647/// Implements conversion of primitive integer types to Rubi atoms.
648macro_rules! impl_rubi_atom_argument_for_integer {
649    ($($integer:ty),* $(,)?) => {
650        $(
651            impl RubiAtomArgument for $integer {
652                fn rubi_atom(&self) -> Atom {
653                    Atom::num(*self)
654                }
655            }
656        )*
657    };
658}
659
660impl_rubi_atom_argument_for_integer!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
661
662impl<T: RubiAtomArgument, U: RubiAtomArgument> RubiAtomArgument for (T, U) {
663    fn rubi_atom(&self) -> Atom {
664        self.0.rubi_atom() / self.1.rubi_atom()
665    }
666}
667
668fn integrate_deferred(expr: AtomView<'_>, x: Symbol) -> Option<Atom> {
669    integrate_internal(expr, x)
670}
671
672fn integrate_internal(expr: AtomView<'_>, x: Symbol) -> Option<Atom> {
673    if rubi_abort_requested() {
674        return None;
675    }
676
677    let is_root = active_integral_stack_empty();
678    if is_root {
679        clear_integral_cache();
680    } else if let Some(cached) = cached_integral(expr, x) {
681        return cached;
682    }
683
684    if active_integral_hit(expr, x) {
685        #[cfg(feature = "trace")]
686        if RUBI_SETTINGS.trace_rules.load(AtomicOrdering::Relaxed) {
687            eprintln!("Int[{expr}, {}] = <recursive cycle>", Atom::var(x));
688        }
689        return None;
690    }
691    let _active_integral = ActiveIntegral::push(expr, x);
692
693    #[cfg(feature = "trace")]
694    let result = if RUBI_SETTINGS.trace_rules.load(AtomicOrdering::Relaxed) {
695        RUBI_TRACE_DEPTH.with(|depth| {
696            let current_depth = depth.get();
697            let indent = "  ".repeat(current_depth);
698            eprintln!("{indent}Int[{expr}, {}]", Atom::var(x));
699            depth.set(current_depth + 1);
700            let result = integrate_view(expr, x);
701            depth.set(current_depth);
702            match &result {
703                Some(primitive) => eprintln!("{indent}= {primitive}"),
704                None => eprintln!("{indent}= <unmatched>"),
705            }
706            result
707        })
708    } else {
709        integrate_view(expr, x)
710    };
711    #[cfg(not(feature = "trace"))]
712    let result = integrate_view(expr, x);
713
714    if rubi_abort_requested() {
715        return None;
716    }
717    // A root result cannot be reused: the next root clears this cache.
718    // Keep recursive entries, but avoid cloning the root key and primitive.
719    if !is_root {
720        cache_integral(expr, x, result.to_owned());
721    }
722    result
723}
724
725/// Integrate `u*v_prime` by parts using the user-provided split.
726///
727/// This applies `∫ u*v' dx = u*v - ∫ v* u' dx`, where `v` is obtained
728/// by integrating `v'`. The function returns the unfinished inner integral
729/// if either `v'` or the by-parts remainder cannot be integrated completely.
730pub(crate) fn integration_by_parts(
731    u: AtomView<'_>,
732    v_prime: AtomView<'_>,
733    x: Symbol,
734) -> Result<Atom, Atom> {
735    let v = integrate(v_prime, x)?;
736    let u_prime = u.derivative(x);
737    let remainder_integrand = v.as_view() * u_prime.as_view();
738    let remainder = integrate(remainder_integrand.as_view(), x)?;
739
740    Ok(u * v.as_view() - remainder)
741}
742
743/// Differentiate an expression containing Rubi function heads.
744///
745/// This wraps Symbolica's derivative and normalizes the formal derivatives
746/// that can remain when a Rubi function head, such as `product_log` or
747/// `sin_integral`, was parsed before this crate could register its custom
748/// derivative attributes.
749#[doc(hidden)]
750pub fn rubi_differentiate(expr: &Atom, x: Symbol) -> Atom {
751    let derivative = expr.derivative(x);
752    let derivative = rubi_normalize_euler_logs(derivative.as_view());
753    let derivative = rubi_normalize_product_log_exponentials(&derivative);
754    let derivative = rubi_normalize_atanh_logs(&derivative);
755    let derivative = rubi_normalize_inverse_trig_exponentials(derivative.as_view());
756    rubi_normalize_inverse_trig_trig(derivative.as_view())
757}
758
759fn integrate_view(expr: AtomView<'_>, x: Symbol) -> Option<Atom> {
760    let expr_atom = expr.to_owned();
761    if let Some(evaluated) = rubi_mathematica_evaluate_integrand(&expr_atom)
762        && evaluated != expr_atom
763    {
764        return integrate_internal(evaluated.as_view(), x);
765    }
766
767    let scanned_deferred = match integrate_view_scan_rules(expr, x) {
768        Some(primitive) if rubi_finished_primitive_q(&primitive) => {
769            return Some(rubi_reduce_builtin_trig_pi_shifts(&rubi_activate_trig(
770                &primitive,
771            )));
772        }
773        scanned => scanned,
774    };
775
776    if rubi_abort_requested() {
777        return None;
778    }
779
780    if rubi_function_of_trig_of_linear_q(&expr_atom, x) {
781        let deactivated = rubi_deactivate_trig(&expr_atom, x);
782        if deactivated != expr_atom
783            && let Some(primitive) = integrate_internal(deactivated.as_view(), x)
784        {
785            let primitive = rubi_reduce_builtin_trig_pi_shifts(&rubi_activate_trig(&primitive));
786            if rubi_finished_primitive_q(&primitive) {
787                return Some(primitive);
788            }
789        }
790    }
791
792    if scanned_deferred
793        .as_ref()
794        .is_some_and(rubi_finished_primitive_q)
795    {
796        return scanned_deferred;
797    }
798
799    if let Some(primitive) = rubi_symbolica_rational_integral(&expr_atom, x) {
800        return Some(primitive);
801    }
802
803    scanned_deferred.filter(|primitive| rubi_rule_deferred_primitive_q(primitive, &expr_atom, x))
804}
805
806fn rubi_symbolica_rational_integral(expr: &Atom, x: Symbol) -> Option<Atom> {
807    if !rubi_rational_function_q(expr, x) {
808        return None;
809    }
810
811    let var_map: Arc<Vec<PolyVariable>> = Arc::new(vec![x.into()]);
812    let rational = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
813        expr.try_to_rational_polynomial::<_, _, u8>(&Q, &Z, Some(var_map))
814    }))
815    .ok()?
816    .ok()?;
817    let integral = rational.integrate(0);
818    let z = rubi_symbols().rootsum_z;
819    let rootsum = rubi_symbols().rootsum;
820
821    let mut primitive = integral
822        .rational_parts
823        .into_iter()
824        .map(|part| part.to_expression())
825        .fold(Atom::num(0), |sum, part| sum + part);
826
827    for part in integral.logarithmic_parts {
828        primitive += rubi_symbolica_logarithmic_integral_term(part, z, rootsum)?;
829    }
830
831    Some(primitive)
832}
833
834fn rubi_symbolica_logarithmic_integral_term(
835    part: LogarithmicIntegralTerm<IntegerRing, u8>,
836    z: Symbol,
837    rootsum: Symbol,
838) -> Option<Atom> {
839    if rubi_symbolica_rational_polynomial_has_temporary(&part.coefficient) {
840        let coefficient = rubi_symbolica_rational_polynomial_rename_temporary(&part.coefficient, z);
841        let argument = rubi_symbolica_rational_polynomial_rename_temporary(&part.argument, z);
842        let z_atom = Atom::var(z);
843        return Some(rootsum.call_args([
844            z_atom.to_owned(),
845            coefficient.to_expression(),
846            z_atom * argument.to_expression().log(),
847        ]));
848    }
849
850    Some(part.coefficient.to_expression() * part.argument.to_expression().log())
851}
852
853fn rubi_symbolica_rational_polynomial_has_temporary(
854    polynomial: &RationalPolynomial<IntegerRing, u8>,
855) -> bool {
856    polynomial
857        .get_variables()
858        .iter()
859        .any(|variable| matches!(variable, PolyVariable::Temporary(_)))
860}
861
862fn rubi_symbolica_rational_polynomial_rename_temporary(
863    polynomial: &RationalPolynomial<IntegerRing, u8>,
864    z: Symbol,
865) -> RationalPolynomial<IntegerRing, u8> {
866    let mut polynomial = polynomial.to_owned();
867    let temporary_variables = polynomial
868        .get_variables()
869        .iter()
870        .filter(|variable| matches!(variable, PolyVariable::Temporary(_)))
871        .cloned()
872        .collect::<Vec<_>>();
873    let z = z.into();
874    for variable in temporary_variables {
875        polynomial.numerator.rename_variable(&variable, &z);
876        polynomial.denominator.rename_variable(&variable, &z);
877    }
878    polynomial
879}
880
881fn integrate_view_scan_rules(expr: AtomView<'_>, x: Symbol) -> Option<Atom> {
882    #[cfg(feature = "trace")]
883    let trace_scan_progress = RUBI_SETTINGS
884        .trace_scan_progress
885        .load(AtomicOrdering::Relaxed);
886    #[cfg(feature = "trace")]
887    let trace_scan_progress_interval = RUBI_SETTINGS
888        .trace_scan_progress_interval
889        .load(AtomicOrdering::Relaxed)
890        .max(1);
891    #[cfg(feature = "trace")]
892    let trace_scan_progress_start = RUBI_SETTINGS
893        .trace_scan_progress_start
894        .load(AtomicOrdering::Relaxed);
895    #[cfg(feature = "trace")]
896    let scan_start = trace_scan_progress.then(std::time::Instant::now);
897    let target = rubi_symbols().rubi_int.call((expr, x));
898    let candidate_bounds = RubiCandidateBounds::new(expr, x);
899    #[cfg(feature = "trace")]
900    if trace_scan_progress {
901        eprintln!(
902            "candidate bounds: x_factors={} affine={} polynomial={} common_binomial_exponent={} common_positive_integer_binomial={}",
903            candidate_bounds.top_level_x_factor_count,
904            candidate_bounds.top_level_affine_base_factor_count,
905            candidate_bounds.top_level_polynomial_base_count,
906            candidate_bounds.max_common_binomial_exponent_factor_count,
907            candidate_bounds.max_common_positive_integer_binomial_factor_count,
908        );
909    }
910    #[cfg(feature = "trace")]
911    for (index, rule) in rubi_rules().iter().enumerate() {
912        if let Some(start) = scan_start
913            && index >= trace_scan_progress_start
914            && index % trace_scan_progress_interval == 0
915        {
916            match rule.block {
917                Some(block) => eprintln!(
918                    "scan {} rules {:?}; next {} block {}",
919                    index,
920                    start.elapsed(),
921                    rule.id,
922                    block
923                ),
924                None => eprintln!(
925                    "scan {} rules {:?}; next {}",
926                    index,
927                    start.elapsed(),
928                    rule.id
929                ),
930            }
931        }
932        if let Some(primitive) = matcher_rule_with_target(expr, x, rule, &target, &candidate_bounds)
933        {
934            return Some(primitive);
935        }
936    }
937    #[cfg(not(feature = "trace"))]
938    for rule in rubi_rules() {
939        if let Some(primitive) = matcher_rule_with_target(expr, x, rule, &target, &candidate_bounds)
940        {
941            return Some(primitive);
942        }
943    }
944
945    None
946}
947
948fn rubi_mathematica_evaluate_integrand(expr: &Atom) -> Option<Atom> {
949    rubi_mathematica_builtin_special_function_values(expr)
950        .or_else(|| rubi_mathematica_trig_quotient(expr))
951        .or_else(|| rubi_mathematica_hyperbolic_quotient(expr))
952}
953
954fn rubi_mathematica_builtin_special_function_values(expr: &Atom) -> Option<Atom> {
955    fn normalize(expr: AtomView<'_>) -> Atom {
956        match expr {
957            AtomView::Fun(function) => {
958                let symbol = function.get_symbol();
959                let arguments = function.into_iter().map(normalize).collect::<Vec<_>>();
960                if symbol == symbolica::transcendental::polylog() && arguments.len() == 2 {
961                    let order = integer_i64(&arguments[0]);
962                    let z = &arguments[1];
963                    return match order {
964                        // These are Mathematica built-in evaluations that happen before
965                        // Rubi sees the integrand, including before DownValue 7235.
966                        Some(0) => z / (Atom::num(1) - z),
967                        Some(-1) => z / (Atom::num(1) - z).pow(2),
968                        Some(-2) => (z + z.pow(2)) / (Atom::num(1) - z).pow(3),
969                        _ => symbol.call_args(arguments),
970                    };
971                }
972                symbol.call_args(arguments)
973            }
974            AtomView::Add(add) => add
975                .into_iter()
976                .map(normalize)
977                .fold(Atom::num(0), |sum, term| sum + term),
978            AtomView::Mul(mul) => mul
979                .into_iter()
980                .map(normalize)
981                .fold(Atom::num(1), |product, factor| product * factor),
982            AtomView::Pow(power) => normalize(power.get_base()).pow(normalize(power.get_exp())),
983            AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
984        }
985    }
986
987    let normalized = normalize(expr.as_view());
988    (normalized != *expr).then_some(normalized)
989}
990
991/// A compiled Rubi pattern together with its guards, action, and scan metadata.
992struct RubiRule {
993    #[cfg(any(test, feature = "trace"))]
994    id: &'static str,
995    #[cfg(any(test, feature = "trace"))]
996    block: Option<u16>,
997    downvalue_order: Option<u16>,
998    dispatch_order: Option<u32>,
999    #[cfg(any(test, feature = "steps"))]
1000    source_pattern: Option<&'static str>,
1001    #[cfg(feature = "steps")]
1002    description: Option<&'static str>,
1003    #[cfg(feature = "steps")]
1004    references: &'static [&'static str],
1005    replacement: Replacement,
1006    required: Vec<Symbol>,
1007    required_function_heads: Vec<Symbol>,
1008    can_match_top_level_sum: bool,
1009    max_top_level_term_count: Option<usize>,
1010    max_top_level_factor_count: Option<usize>,
1011    early_x_dependent: Vec<Symbol>,
1012    early_x_free: Vec<Symbol>,
1013    early_x_linear: Vec<Symbol>,
1014    early_not_integration_variable: Vec<Symbol>,
1015    require_repeated_proper_x_dependent_subexpression: bool,
1016    early_numeric_bounds: Vec<(Symbol, RubiEarlyNumericBound)>,
1017    early_positive_integer_or_integer_pairs: Vec<(Symbol, Symbol)>,
1018    early_scaled_equal: Vec<(Symbol, i64, Symbol)>,
1019    early_proportional_affine: Vec<[Symbol; 4]>,
1020    require_proportional_affine_factor_pair: bool,
1021    require_proportional_common_expression_factor_pair: bool,
1022    early_polynomial_derivative_pairs: Vec<(Symbol, Symbol)>,
1023    early_zero: Vec<Symbol>,
1024    require_algebraic_zero_x_free_additive_part: bool,
1025    max_zero_x_free_additive_term_count: Option<usize>,
1026    require_proportional_binomial_base_pair: bool,
1027    require_opposite_binomial_base_pair: bool,
1028    require_negated_binomial_exponent_pair: bool,
1029    required_common_binomial_exponent_factor_count: usize,
1030    required_common_positive_integer_binomial_factor_count: usize,
1031    required_common_polynomial_base_degree_count: usize,
1032    required_noninteger_power_factor_count: usize,
1033    require_even_quadratic_binomial_base: bool,
1034    require_perfect_square_quadratic_base: bool,
1035    require_half_integer_affine_power: bool,
1036    require_positive_integer_affine_power: bool,
1037    require_rational_noninteger_affine_power_below_negative_one: bool,
1038    require_negative_scaled_affine_and_distinct_noninteger_affine: bool,
1039    require_noninteger_affine_exponent_with_positive_difference: bool,
1040    require_x_dependent_exponent_for_x_dependent_candidate: bool,
1041    require_polynomial_complement_of_affine_power: bool,
1042    required_noninteger_affine_power_count: usize,
1043    require_explicit_variable_power_factor: bool,
1044    required_explicit_power_exponents: Vec<Symbol>,
1045    explicit_x_factor_bound: Option<ExplicitPatternXFactorBound>,
1046    condition: RubiCondition,
1047    action: RubiAction,
1048}
1049
1050#[cfg(all(feature = "steps", feature = "compressed-step-metadata"))]
1051include!(concat!(env!("OUT_DIR"), "/rubi_rule_texts.rs"));
1052
1053#[cfg(all(feature = "steps", feature = "compressed-step-metadata"))]
1054struct RubiRuleTextCatalog {
1055    decoded: Box<[u8]>,
1056}
1057
1058#[cfg(all(feature = "steps", feature = "compressed-step-metadata"))]
1059impl RubiRuleTextCatalog {
1060    fn decode() -> Self {
1061        let mut decoder = brotli::Decompressor::new(RUBI_RULE_TEXT_COMPRESSED, 4096);
1062        let mut decoded = Vec::new();
1063        std::io::Read::read_to_end(&mut decoder, &mut decoded)
1064            .expect("the embedded Rubi rule text catalog should decompress");
1065        assert!(
1066            decoded.len() >= RUBI_RULE_TEXT_DIRECTORY_BYTES,
1067            "the embedded Rubi rule text catalog has a truncated directory"
1068        );
1069        let catalog = Self {
1070            decoded: decoded.into_boxed_slice(),
1071        };
1072        for order in 0..RUBI_RULE_TEXT_RECORD_COUNT {
1073            let _ = catalog.get(order as u16);
1074        }
1075        catalog
1076    }
1077
1078    fn get(&self, order: u16) -> Option<(&str, &str)> {
1079        let order = usize::from(order);
1080        if order >= RUBI_RULE_TEXT_RECORD_COUNT {
1081            return None;
1082        }
1083        let record_start = order * RUBI_RULE_TEXT_RECORD_BYTES;
1084        let record = &self.decoded[record_start..record_start + RUBI_RULE_TEXT_RECORD_BYTES];
1085        let source_offset = u32::from_le_bytes(record[0..4].try_into().unwrap()) as usize;
1086        let description_offset = u32::from_le_bytes(record[4..8].try_into().unwrap()) as usize;
1087        let source_len = u16::from_le_bytes(record[8..10].try_into().unwrap()) as usize;
1088        let description_len = u16::from_le_bytes(record[10..12].try_into().unwrap()) as usize;
1089        if source_len == 0 || description_len == 0 {
1090            return None;
1091        }
1092        let text = &self.decoded[RUBI_RULE_TEXT_DIRECTORY_BYTES..];
1093        let source = text.get(source_offset..source_offset.checked_add(source_len)?)?;
1094        let description =
1095            text.get(description_offset..description_offset.checked_add(description_len)?)?;
1096        Some((
1097            std::str::from_utf8(source).expect("Rubi rule sources should be UTF-8"),
1098            std::str::from_utf8(description).expect("Rubi rule descriptions should be UTF-8"),
1099        ))
1100    }
1101}
1102
1103#[cfg(all(feature = "steps", feature = "compressed-step-metadata"))]
1104static RUBI_RULE_TEXTS: OnceLock<RubiRuleTextCatalog> = OnceLock::new();
1105
1106#[cfg(all(feature = "steps", feature = "compressed-step-metadata"))]
1107fn rubi_rule_text(order: u16) -> Option<(&'static str, &'static str)> {
1108    RUBI_RULE_TEXTS
1109        .get_or_init(RubiRuleTextCatalog::decode)
1110        .get(order)
1111}
1112
1113#[cfg(feature = "steps")]
1114fn rubi_rule_source_pattern(rule: &RubiRule) -> Option<&'static str> {
1115    #[cfg(feature = "compressed-step-metadata")]
1116    {
1117        rule.source_pattern.or_else(|| {
1118            rule.downvalue_order
1119                .and_then(rubi_rule_text)
1120                .map(|(source, _)| source)
1121        })
1122    }
1123    #[cfg(not(feature = "compressed-step-metadata"))]
1124    {
1125        rule.source_pattern
1126    }
1127}
1128
1129#[cfg(feature = "steps")]
1130fn rubi_rule_description(rule: &RubiRule) -> Option<&'static str> {
1131    #[cfg(feature = "compressed-step-metadata")]
1132    {
1133        rule.description.or_else(|| {
1134            if rule.source_pattern.is_some() {
1135                return None;
1136            }
1137            rule.downvalue_order
1138                .and_then(rubi_rule_text)
1139                .map(|(_, description)| description)
1140        })
1141    }
1142    #[cfg(not(feature = "compressed-step-metadata"))]
1143    {
1144        rule.description
1145    }
1146}
1147
1148/// Factor-shape limits derived from a rule that explicitly contains `x`.
1149struct ExplicitPatternXFactorBound {
1150    factor_count: usize,
1151    affine_base_count: usize,
1152    unpowered_affine_factor_count: usize,
1153    polynomial_base_count: usize,
1154    x_factor_symbols: Vec<Symbol>,
1155    non_x_factor_symbols: Vec<Symbol>,
1156}
1157
1158/// Precomputed structural facts used to reject impossible rule candidates cheaply.
1159struct RubiCandidateBounds {
1160    function_heads: Vec<Symbol>,
1161    top_level_is_sum: bool,
1162    top_level_term_count: usize,
1163    top_level_factor_count: usize,
1164    top_level_x_factor_count: usize,
1165    top_level_affine_base_factor_count: usize,
1166    top_level_unpowered_affine_factor_count: usize,
1167    top_level_polynomial_base_count: usize,
1168    has_even_quadratic_binomial_base: bool,
1169    has_perfect_square_quadratic_base: bool,
1170    has_half_integer_affine_power: bool,
1171    has_positive_integer_affine_power: bool,
1172    has_rational_noninteger_affine_power_below_negative_one: bool,
1173    has_negative_scaled_affine_and_distinct_noninteger_affine: bool,
1174    has_noninteger_affine_exponent_with_positive_difference: bool,
1175    has_x_dependent_exponent: bool,
1176    noninteger_affine_power_count: usize,
1177    has_negated_binomial_exponent_pair: bool,
1178    max_common_binomial_exponent_factor_count: usize,
1179    max_common_positive_integer_binomial_factor_count: usize,
1180    max_common_polynomial_base_degree_count: Option<usize>,
1181    top_level_noninteger_power_factor_count: usize,
1182    has_explicit_variable_power_factor: bool,
1183}
1184
1185#[derive(Clone, Copy)]
1186/// A numeric wildcard constraint evaluated before full pattern enumeration.
1187enum RubiEarlyNumericBound {
1188    Integer,
1189    IntegerGreaterThan(i64),
1190    IntegerLessThan(i64),
1191    NumberGreaterThan(i64),
1192    NumberLessThan(i64),
1193}
1194
1195type RubiIntegralCacheEntry = (Atom, Symbol, Option<Atom>);
1196
1197thread_local! {
1198    #[cfg(feature = "trace")]
1199    static CURRENT_RUBI_RULE: Cell<*const RubiRule> = const { Cell::new(std::ptr::null()) };
1200    static RUBI_ABORT_SIGNAL: Cell<*const AtomicBool> = const { Cell::new(std::ptr::null()) };
1201    #[cfg(feature = "trace")]
1202    static RUBI_TRACE_DEPTH: Cell<usize> = const { Cell::new(0) };
1203    static RUBI_ACTIVE_INTEGRALS: RefCell<Vec<(Atom, Symbol)>> = const { RefCell::new(Vec::new()) };
1204    static RUBI_INTEGRAL_CACHE: RefCell<Vec<RubiIntegralCacheEntry>> = const { RefCell::new(Vec::new()) };
1205    static RUBI_SUBSTITUTION_DEPTH: Cell<usize> = const { Cell::new(0) };
1206    static RUBI_REPLACEMENT_CONTEXT: RefCell<Option<(*const RubiRule, Symbol)>> = const { RefCell::new(None) };
1207    #[cfg(feature = "steps")]
1208    static RUBI_EXPLANATION_STEPS: RefCell<Option<Vec<IntegrationStep>>> = const { RefCell::new(None) };
1209    #[cfg(feature = "steps")]
1210    static RUBI_STEPS_ACTIVE: Cell<bool> = const { Cell::new(false) };
1211    #[cfg(feature = "steps")]
1212    static RUBI_CAPTURE_RULE_RHS: Cell<bool> = const { Cell::new(false) };
1213    #[cfg(feature = "steps")]
1214    static RUBI_STEP_DEPTH: Cell<usize> = const { Cell::new(0) };
1215}
1216
1217#[cfg(feature = "steps")]
1218struct RubiExplanationCollector {
1219    previous: Option<Vec<IntegrationStep>>,
1220    previous_active: bool,
1221    previous_depth: usize,
1222    finished: bool,
1223}
1224
1225#[cfg(feature = "steps")]
1226impl RubiExplanationCollector {
1227    fn push() -> Self {
1228        let previous = RUBI_EXPLANATION_STEPS.with(|steps| steps.replace(Some(Vec::new())));
1229        let previous_active = RUBI_STEPS_ACTIVE.with(|active| active.replace(true));
1230        let previous_depth = RUBI_STEP_DEPTH.with(|depth| depth.replace(0));
1231        Self {
1232            previous,
1233            previous_active,
1234            previous_depth,
1235            finished: false,
1236        }
1237    }
1238
1239    fn finish(mut self) -> Vec<IntegrationStep> {
1240        let steps = RUBI_EXPLANATION_STEPS
1241            .with(|current| current.replace(self.previous.take()))
1242            .expect("explanation collector should remain installed");
1243        RUBI_STEPS_ACTIVE.with(|active| active.set(self.previous_active));
1244        RUBI_STEP_DEPTH.with(|depth| depth.set(self.previous_depth));
1245        self.finished = true;
1246        steps
1247    }
1248}
1249
1250#[cfg(feature = "steps")]
1251impl Drop for RubiExplanationCollector {
1252    fn drop(&mut self) {
1253        if !self.finished {
1254            RUBI_EXPLANATION_STEPS.with(|current| {
1255                current.replace(self.previous.take());
1256            });
1257            RUBI_STEPS_ACTIVE.with(|active| active.set(self.previous_active));
1258            RUBI_STEP_DEPTH.with(|depth| depth.set(self.previous_depth));
1259        }
1260    }
1261}
1262
1263#[cfg(feature = "steps")]
1264fn begin_explanation_step(
1265    rule: &RubiRule,
1266    x: Symbol,
1267    input: impl FnOnce() -> Atom,
1268) -> Option<usize> {
1269    RUBI_EXPLANATION_STEPS.with(|steps| {
1270        let mut steps = steps.borrow_mut();
1271        let steps = steps.as_mut()?;
1272        if RUBI_CAPTURE_RULE_RHS.with(Cell::get) {
1273            return None;
1274        }
1275        let source = rubi_rule_source_pattern(rule)?;
1276        let description = rubi_rule_description(rule)?;
1277        let checkpoint = steps.len();
1278        let input = rubi_symbols().rubi_int.call((input(), Atom::var(x)));
1279        steps.push(IntegrationStep {
1280            rule: rule.downvalue_order,
1281            depth: RUBI_STEP_DEPTH.with(Cell::get),
1282            description,
1283            references: rule.references,
1284            source,
1285            input,
1286            output: Atom::num(0),
1287        });
1288        Some(checkpoint)
1289    })
1290}
1291
1292#[cfg(feature = "steps")]
1293struct RubiStepDepth {
1294    previous: usize,
1295}
1296
1297#[cfg(feature = "steps")]
1298impl RubiStepDepth {
1299    fn push() -> Self {
1300        let previous = RUBI_STEP_DEPTH.with(|depth| {
1301            let previous = depth.get();
1302            depth.set(previous + 1);
1303            previous
1304        });
1305        Self { previous }
1306    }
1307}
1308
1309#[cfg(feature = "steps")]
1310impl Drop for RubiStepDepth {
1311    fn drop(&mut self) {
1312        RUBI_STEP_DEPTH.with(|depth| depth.set(self.previous));
1313    }
1314}
1315
1316#[cfg(feature = "steps")]
1317struct RubiRhsCapture {
1318    previous: bool,
1319}
1320
1321#[cfg(feature = "steps")]
1322impl RubiRhsCapture {
1323    fn push() -> Self {
1324        let previous = RUBI_CAPTURE_RULE_RHS.with(|capture| capture.replace(true));
1325        Self { previous }
1326    }
1327}
1328
1329#[cfg(feature = "steps")]
1330impl Drop for RubiRhsCapture {
1331    fn drop(&mut self) {
1332        RUBI_CAPTURE_RULE_RHS.with(|capture| capture.set(self.previous));
1333    }
1334}
1335
1336#[cfg(feature = "steps")]
1337fn capture_rule_rhs(
1338    rule: &RubiRule,
1339    matches: &symbolica::id::MatchStack<'_>,
1340    x: Symbol,
1341) -> Option<Atom> {
1342    let _capture = RubiRhsCapture::push();
1343    rule.apply(matches, x)
1344}
1345
1346#[cfg(feature = "steps")]
1347fn finish_explanation_step(
1348    checkpoint: Option<usize>,
1349    immediate_output: Option<&Atom>,
1350    final_output: Option<&Atom>,
1351) {
1352    let Some(checkpoint) = checkpoint else {
1353        return;
1354    };
1355    RUBI_EXPLANATION_STEPS.with(|steps| {
1356        let mut steps = steps.borrow_mut();
1357        let Some(steps) = steps.as_mut() else {
1358            return;
1359        };
1360        if let Some(final_output) = final_output {
1361            steps[checkpoint].output = immediate_output
1362                .cloned()
1363                .unwrap_or_else(|| final_output.to_owned());
1364        } else {
1365            steps.truncate(checkpoint);
1366        }
1367    });
1368}
1369
1370/// Scoped installation of the current thread's cancellation flag.
1371struct AbortSignal {
1372    previous: *const AtomicBool,
1373}
1374
1375impl AbortSignal {
1376    fn push(abort: &AtomicBool) -> Self {
1377        let previous = RUBI_ABORT_SIGNAL.with(|signal| signal.replace(abort));
1378        Self { previous }
1379    }
1380}
1381
1382impl Drop for AbortSignal {
1383    fn drop(&mut self) {
1384        RUBI_ABORT_SIGNAL.with(|signal| signal.set(self.previous));
1385    }
1386}
1387
1388fn rubi_abort_requested() -> bool {
1389    RUBI_ABORT_SIGNAL.with(|signal| {
1390        let abort = signal.get();
1391        if abort.is_null() {
1392            return false;
1393        }
1394
1395        // The pointer is installed by AbortSignal for the duration of the
1396        // cancellation-aware integration call on this thread, then restored on drop.
1397        unsafe { (*abort).load(AtomicOrdering::Relaxed) }
1398    })
1399}
1400
1401/// Stack guard used to detect recursive integration cycles.
1402struct ActiveIntegral;
1403
1404impl ActiveIntegral {
1405    fn push(expr: AtomView<'_>, x: Symbol) -> Self {
1406        RUBI_ACTIVE_INTEGRALS.with(|active| active.borrow_mut().push((expr.to_owned(), x)));
1407        Self
1408    }
1409}
1410
1411impl Drop for ActiveIntegral {
1412    fn drop(&mut self) {
1413        RUBI_ACTIVE_INTEGRALS.with(|active| {
1414            let _ = active
1415                .borrow_mut()
1416                .pop()
1417                .expect("active integral stack should stay balanced");
1418        });
1419    }
1420}
1421
1422/// Scoped rule and variable context used while evaluating a replacement.
1423struct RubiReplacementContext {
1424    previous: Option<(*const RubiRule, Symbol)>,
1425}
1426
1427impl RubiReplacementContext {
1428    fn push(rule: &'static RubiRule, x: Symbol) -> Self {
1429        let previous = RUBI_REPLACEMENT_CONTEXT.with(|context| context.replace(Some((rule, x))));
1430        Self { previous }
1431    }
1432}
1433
1434impl Drop for RubiReplacementContext {
1435    fn drop(&mut self) {
1436        RUBI_REPLACEMENT_CONTEXT.with(|context| {
1437            context.replace(self.previous);
1438        });
1439    }
1440}
1441
1442/// Scoped temporary symbol allocated for a nested substitution.
1443struct FreshSubstitutionSymbol {
1444    symbol: Symbol,
1445}
1446
1447impl FreshSubstitutionSymbol {
1448    fn symbol(&self) -> Symbol {
1449        self.symbol
1450    }
1451}
1452
1453impl Drop for FreshSubstitutionSymbol {
1454    fn drop(&mut self) {
1455        RUBI_SUBSTITUTION_DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));
1456    }
1457}
1458
1459fn fresh_substitution_symbol() -> Option<FreshSubstitutionSymbol> {
1460    RUBI_SUBSTITUTION_DEPTH.with(|depth| {
1461        let current_depth = depth.get();
1462        let symbol = substitution_symbol_at_depth(current_depth)?;
1463        depth.set(current_depth + 1);
1464        Some(FreshSubstitutionSymbol { symbol })
1465    })
1466}
1467
1468fn substitution_symbol_at_depth(depth: usize) -> Option<Symbol> {
1469    let symbols = rubi_symbols();
1470    match depth {
1471        0 => Some(symbols.sub1),
1472        1 => Some(symbols.sub2),
1473        2 => Some(symbols.sub3),
1474        3 => Some(symbols.sub4),
1475        4 => Some(symbols.sub5),
1476        5 => Some(symbols.sub6),
1477        6 => Some(symbols.sub7),
1478        7 => Some(symbols.sub8),
1479        _ => None,
1480    }
1481}
1482
1483#[cfg(feature = "steps")]
1484fn record_explanation_substitution(symbol: Symbol, replacement: &Atom) {
1485    let symbols = rubi_symbols();
1486    let is_temporary = [
1487        symbols.sub1,
1488        symbols.sub2,
1489        symbols.sub3,
1490        symbols.sub4,
1491        symbols.sub5,
1492        symbols.sub6,
1493        symbols.sub7,
1494        symbols.sub8,
1495    ]
1496    .contains(&symbol);
1497    let step_depth = RUBI_STEP_DEPTH.with(Cell::get);
1498    if step_depth == 0 || RUBI_CAPTURE_RULE_RHS.with(Cell::get) {
1499        return;
1500    }
1501
1502    let Some((rule, integration_variable)) = rubi_replacement_context() else {
1503        return;
1504    };
1505    if !rubi_rule_source_pattern(rule).is_some_and(|source| source.contains("Subst[")) {
1506        return;
1507    }
1508
1509    let formal_substitution = integration_variable == symbol;
1510    let display_symbol = if formal_substitution {
1511        let substitution_depth = RUBI_SUBSTITUTION_DEPTH.with(Cell::get);
1512        let Some(display_symbol) = substitution_symbol_at_depth(substitution_depth) else {
1513            return;
1514        };
1515        display_symbol
1516    } else if is_temporary {
1517        symbol
1518    } else {
1519        return;
1520    };
1521
1522    RUBI_EXPLANATION_STEPS.with(|steps| {
1523        let mut steps = steps.borrow_mut();
1524        let Some(steps) = steps.as_mut() else {
1525            return;
1526        };
1527        let step = IntegrationStep {
1528            rule: None,
1529            depth: step_depth,
1530            description: "Variable substitution",
1531            references: &[],
1532            source: "Subst",
1533            input: Atom::var(display_symbol),
1534            output: replacement.to_owned(),
1535        };
1536        let insertion_index = steps
1537            .iter()
1538            .rposition(|existing| existing.depth < step_depth)
1539            .map_or(steps.len(), |parent| {
1540                let mut insertion = parent + 1;
1541                while insertion < steps.len()
1542                    && steps[insertion].depth == step_depth
1543                    && steps[insertion].description == "Variable substitution"
1544                {
1545                    insertion += 1;
1546                }
1547                insertion
1548            });
1549        steps.insert(insertion_index, step);
1550    });
1551}
1552
1553fn active_integral_hit(expr: AtomView<'_>, x: Symbol) -> bool {
1554    RUBI_ACTIVE_INTEGRALS.with(|active| {
1555        active
1556            .borrow()
1557            .iter()
1558            .filter(|(_, active_x)| *active_x == x)
1559            .any(|(active_expr, _)| active_expr.as_view() == expr)
1560    })
1561}
1562
1563fn rubi_int_sum(expr: &Atom, x: Symbol) -> Option<Atom> {
1564    if !matches!(expr.as_view(), AtomView::Add(_)) {
1565        return None;
1566    }
1567
1568    #[cfg(feature = "steps")]
1569    if RUBI_STEPS_ACTIVE.with(Cell::get) {
1570        let AtomView::Add(add) = expr.as_view() else {
1571            unreachable!("the expression was checked to be a sum")
1572        };
1573        return Some(
1574            add.into_iter()
1575                .map(|term| rubi_rhs_int(term.to_owned(), x))
1576                .fold(Atom::num(0), |sum, primitive| sum + primitive),
1577        );
1578    }
1579
1580    let (free_terms, nonfree_terms) = rubi_free_nonfree_terms(expr, x);
1581    let mut primitive = if free_terms.is_zero() {
1582        Atom::num(0)
1583    } else {
1584        rubi_simp(&(free_terms * Atom::var(x)), x)
1585    };
1586
1587    for nonfree_term in nonfree_terms {
1588        if let Some(term_primitive) = rubi_int_term(&nonfree_term, x) {
1589            primitive += term_primitive;
1590            continue;
1591        }
1592
1593        primitive += rubi_int_sum_term(&nonfree_term, x);
1594    }
1595
1596    #[cfg(feature = "trace")]
1597    trace_direct_polynomial_integration("IntSum", expr);
1598    Some(primitive)
1599}
1600
1601fn rubi_log_product_factor_q(expr: &Atom, x: Symbol) -> bool {
1602    let (base, exponent) = rubi_factor_base_exponent(expr);
1603    rubi_log_argument(&base).is_some() && is_free_of(&exponent, x)
1604}
1605
1606fn rubi_int_sum_term(expr: &Atom, x: Symbol) -> Atom {
1607    rubi_int_term(expr, x).unwrap_or_else(|| rubi_rhs_int(expr, x))
1608}
1609
1610fn rubi_int_term(expr: &Atom, x: Symbol) -> Option<Atom> {
1611    if let AtomView::Add(add) = expr.as_view() {
1612        let mut primitive = Atom::num(0);
1613        for term in add {
1614            primitive += rubi_int_term(&term.to_owned(), x)?;
1615        }
1616        return Some(primitive);
1617    }
1618
1619    if let Some((coefficient, linear, exponent)) = rubi_int_term_linear_power(expr, x) {
1620        let linear = rubi_cancel(&linear);
1621        let slope = rubi_coeff(&linear, x, 1)?;
1622        if slope.is_zero() {
1623            return None;
1624        }
1625
1626        if rubi_algebraic_zero_q(&(exponent.to_owned() + Atom::num(1))) {
1627            return Some(rubi_simp(
1628                &(coefficient * rubi_remove_content_linear(&linear, x).log() / slope),
1629                x,
1630            ));
1631        }
1632
1633        if rubi_algebraic_zero_q(&(exponent.to_owned() - Atom::num(1)))
1634            && coefficient == Atom::num(1)
1635            && matches!(linear.as_view(), AtomView::Add(_))
1636        {
1637            return rubi_int_sum(&linear, x);
1638        }
1639
1640        return Some(rubi_simp(
1641            &(coefficient * linear.pow(&(&exponent + Atom::num(1)))
1642                / (slope * (&exponent + Atom::num(1)))),
1643            x,
1644        ));
1645    }
1646
1647    let free = rubi_free_factors(expr, x);
1648    let nonfree = rubi_nonfree_factors(expr, x);
1649    if free == Atom::num(1) || nonfree == Atom::num(1) || nonfree == *expr {
1650        return None;
1651    }
1652
1653    let primitive = rubi_rhs_int(&nonfree, x);
1654    Some(rubi_star(free, primitive))
1655}
1656
1657fn rubi_int_term_linear_power(expr: &Atom, x: Symbol) -> Option<(Atom, Atom, Atom)> {
1658    rubi_int_term_linear_power_product(expr, x)
1659        .or_else(|| rubi_int_term_rational_linear_power(expr, x))
1660}
1661
1662fn rubi_int_term_linear_power_product(expr: &Atom, x: Symbol) -> Option<(Atom, Atom, Atom)> {
1663    let mut coefficient = Atom::num(1);
1664    let mut linear_power = None;
1665
1666    let factors = match expr.as_view() {
1667        AtomView::Mul(mul) => mul
1668            .into_iter()
1669            .map(|factor| factor.to_owned())
1670            .collect::<Vec<_>>(),
1671        _ => vec![expr.to_owned()],
1672    };
1673
1674    for factor in factors {
1675        if is_free_of(&factor, x) {
1676            coefficient *= factor;
1677            continue;
1678        }
1679
1680        if linear_power.is_some() {
1681            return None;
1682        }
1683
1684        if rubi_linear_q(factor.as_view(), x) {
1685            linear_power = Some((factor, Atom::num(1)));
1686            continue;
1687        }
1688
1689        let AtomView::Pow(power) = factor.as_view() else {
1690            return None;
1691        };
1692        let (base, exponent) = power.get_base_exp();
1693        let base = base.to_owned();
1694        let exponent = exponent.to_owned();
1695        if !is_free_of(&exponent, x) || !rubi_linear_q(base.as_view(), x) {
1696            return None;
1697        }
1698        linear_power = Some((base, exponent));
1699    }
1700
1701    let (linear, exponent) = linear_power?;
1702    Some((coefficient, linear, exponent))
1703}
1704
1705fn rubi_int_term_rational_linear_power(expr: &Atom, x: Symbol) -> Option<(Atom, Atom, Atom)> {
1706    let (numerator, denominator) = rational_numerator_denominator(expr)?;
1707    if denominator == Atom::num(1) || !is_free_of(&numerator, x) {
1708        return None;
1709    }
1710
1711    let mut coefficient = numerator;
1712    let denominator = denominator.factor();
1713    let mut linear_power = None;
1714    let factors = match denominator.as_view() {
1715        AtomView::Mul(mul) => mul
1716            .into_iter()
1717            .map(|factor| factor.to_owned())
1718            .collect::<Vec<_>>(),
1719        _ => vec![denominator],
1720    };
1721
1722    for factor in factors {
1723        if is_free_of(&factor, x) {
1724            coefficient /= factor;
1725            continue;
1726        }
1727
1728        if linear_power.is_some() {
1729            return None;
1730        }
1731
1732        if rubi_linear_q(factor.as_view(), x) {
1733            linear_power = Some((factor, Atom::num(-1)));
1734            continue;
1735        }
1736
1737        let AtomView::Pow(power) = factor.as_view() else {
1738            return None;
1739        };
1740        let (base, exponent) = power.get_base_exp();
1741        let base = base.to_owned();
1742        let exponent = exponent.to_owned();
1743        if !is_free_of(&exponent, x) || !rubi_linear_q(base.as_view(), x) {
1744            return None;
1745        }
1746        linear_power = Some((base, -exponent));
1747    }
1748
1749    let (linear, exponent) = linear_power?;
1750    Some((coefficient, linear, exponent))
1751}
1752
1753fn rubi_remove_content_linear(expr: &Atom, x: Symbol) -> Atom {
1754    let Some(slope) = rubi_coeff(expr, x, 1) else {
1755        return expr.to_owned();
1756    };
1757    if slope.is_zero() {
1758        return expr.to_owned();
1759    }
1760
1761    let removed = rubi_cancel(&(expr / slope));
1762    if matches!(removed.as_view(), AtomView::Add(_)) && rubi_first_term_neg_q(&removed) {
1763        -removed
1764    } else {
1765        removed
1766    }
1767}
1768
1769fn active_integral_stack_empty() -> bool {
1770    RUBI_ACTIVE_INTEGRALS.with(|active| active.borrow().is_empty())
1771}
1772
1773fn clear_integral_cache() {
1774    RUBI_INTEGRAL_CACHE.with(|cache| cache.borrow_mut().clear());
1775}
1776
1777fn cached_integral(expr: AtomView<'_>, x: Symbol) -> Option<Option<Atom>> {
1778    RUBI_INTEGRAL_CACHE.with(|cache| {
1779        cache
1780            .borrow()
1781            .iter()
1782            .find(|(cached_expr, cached_x, _)| *cached_x == x && cached_expr.as_view() == expr)
1783            .map(|(_, _, primitive)| primitive.to_owned())
1784    })
1785}
1786
1787fn cache_integral(expr: AtomView<'_>, x: Symbol, primitive: Option<Atom>) {
1788    RUBI_INTEGRAL_CACHE.with(|cache| {
1789        let mut cache = cache.borrow_mut();
1790        if !cache
1791            .iter()
1792            .any(|(cached_expr, cached_x, _)| *cached_x == x && cached_expr.as_view() == expr)
1793        {
1794            cache.push((expr.to_owned(), x, primitive));
1795        }
1796    });
1797}
1798
1799type RubiAction =
1800    for<'stack> fn(&symbolica::id::MatchStack<'stack>, Symbol, &RubiRule) -> Option<Atom>;
1801type RubiCondition =
1802    for<'stack> fn(&symbolica::id::MatchStack<'stack>, Symbol, &RubiRule) -> ConditionResult;
1803
1804/// Extracts values whose presence was established by a Rubi rule condition.
1805trait RubiRhsInvariant<T> {
1806    fn rubi_rhs(self) -> T;
1807}
1808
1809impl<T> RubiRhsInvariant<T> for Option<T> {
1810    #[cfg_attr(any(test, feature = "trace"), track_caller)]
1811    fn rubi_rhs(self) -> T {
1812        self.expect("Rubi RHS invariant was not established by the rule condition")
1813    }
1814}
1815
1816impl<T, E: std::fmt::Debug> RubiRhsInvariant<T> for Result<T, E> {
1817    #[cfg_attr(any(test, feature = "trace"), track_caller)]
1818    fn rubi_rhs(self) -> T {
1819        self.expect("Rubi RHS invariant was not established by the rule condition")
1820    }
1821}
1822
1823// Share Vec growth, the large rule move, and its unwind cleanup across the
1824// generated registration functions without changing their Vec interface.
1825trait RubiRuleRegistry {
1826    fn push_rubi_rule(&mut self, rule: RubiRule);
1827}
1828
1829impl RubiRuleRegistry for Vec<RubiRule> {
1830    #[inline(never)]
1831    fn push_rubi_rule(&mut self, rule: RubiRule) {
1832        self.push(rule);
1833    }
1834}
1835
1836// These wrappers run only while registering rules. Keep the shared
1837// construction and order assignment out of each generated constructor.
1838#[inline(never)]
1839fn build_rubi_rule(
1840    #[cfg(any(test, feature = "trace"))] id: &'static str,
1841    #[cfg(not(any(test, feature = "trace")))] id: (),
1842    downvalue_order: Option<u16>,
1843    pattern: Atom,
1844    required: &[Symbol],
1845    optional: &[Symbol],
1846    condition: RubiCondition,
1847    action: RubiAction,
1848) -> RubiRule {
1849    let mut rule = rubi_rule_with_optional_action(
1850        id,
1851        pattern,
1852        required,
1853        rubi_symbols().rubi_int,
1854        optional,
1855        condition,
1856        action,
1857    );
1858    rule.downvalue_order = downvalue_order;
1859    rule.dispatch_order = downvalue_order.map(rubi_dispatch_order);
1860    rule
1861}
1862
1863#[inline(never)]
1864fn build_rubi_helper_rule(
1865    #[cfg(any(test, feature = "trace"))] id: &'static str,
1866    #[cfg(not(any(test, feature = "trace")))] id: (),
1867    downvalue_order: u16,
1868    pattern: Atom,
1869    head: Symbol,
1870    required: &[Symbol],
1871    optional: &[Symbol],
1872    condition: RubiCondition,
1873    action: RubiAction,
1874) -> RubiRule {
1875    let mut rule =
1876        rubi_rule_with_optional_action(id, pattern, required, head, optional, condition, action);
1877    rule.downvalue_order = Some(downvalue_order);
1878    rule.dispatch_order = Some(rubi_dispatch_order(downvalue_order));
1879    rule
1880}
1881
1882fn rubi_dispatch_order(order: u16) -> u32 {
1883    u32::from(order) * 3 + 1
1884}
1885
1886fn required_rubi_dispatch_order(rule: &RubiRule) -> u32 {
1887    rule.dispatch_order.unwrap_or_else(|| {
1888        #[cfg(any(test, feature = "trace"))]
1889        panic!(
1890            "Rubi integration rule has neither an upstream order nor an explicit dispatch anchor: {}",
1891            rule.id.lines().next().unwrap_or_default()
1892        );
1893        #[cfg(not(any(test, feature = "trace")))]
1894        panic!("Rubi integration rule has neither an upstream order nor an explicit dispatch anchor");
1895    })
1896}
1897
1898#[cfg(test)]
1899fn rubi_inertize_builtin_trig_heads<T: AtomCore>(expr: T) -> Atom {
1900    let expr = expr.as_atom_view();
1901    match expr {
1902        AtomView::Fun(function) => {
1903            let args: Vec<_> = function
1904                .into_iter()
1905                .map(rubi_inertize_builtin_trig_heads)
1906                .collect();
1907            let symbol = rubi_inert_symbol_for_builtin_trig(function.get_symbol())
1908                .unwrap_or_else(|| function.get_symbol());
1909            symbol.call_args(args)
1910        }
1911        AtomView::Add(add) => add
1912            .into_iter()
1913            .map(rubi_inertize_builtin_trig_heads)
1914            .fold(Atom::num(0), |sum, term| sum + term),
1915        AtomView::Mul(mul) => mul
1916            .into_iter()
1917            .map(rubi_inertize_builtin_trig_heads)
1918            .fold(Atom::num(1), |product, factor| product * factor),
1919        AtomView::Pow(power) => rubi_inertize_builtin_trig_heads(power.get_base())
1920            .pow(rubi_inertize_builtin_trig_heads(power.get_exp())),
1921        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
1922    }
1923}
1924
1925fn rubi_inert_symbol_for_builtin_trig(symbol: Symbol) -> Option<Symbol> {
1926    let symbols = rubi_symbols();
1927    match symbol {
1928        s if s == Symbol::SIN => Some(symbols.inert_sin),
1929        s if s == Symbol::COS => Some(symbols.inert_cos),
1930        s if s == symbolica::transcendental::tan() => Some(symbols.inert_tan),
1931        s if s == symbolica::transcendental::cot() => Some(symbols.inert_cot),
1932        s if s == symbolica::transcendental::sec() => Some(symbols.inert_sec),
1933        s if s == symbolica::transcendental::csc() => Some(symbols.inert_csc),
1934        _ => None,
1935    }
1936}
1937
1938fn rubi_builtin_symbol_for_inert_trig(symbol: Symbol) -> Option<Symbol> {
1939    let symbols = rubi_symbols();
1940    match symbol {
1941        s if s == symbols.inert_sin => Some(Symbol::SIN),
1942        s if s == symbols.inert_cos => Some(Symbol::COS),
1943        s if s == symbols.inert_tan => Some(symbolica::transcendental::tan()),
1944        s if s == symbols.inert_cot => Some(symbolica::transcendental::cot()),
1945        s if s == symbols.inert_sec => Some(symbolica::transcendental::sec()),
1946        s if s == symbols.inert_csc => Some(symbolica::transcendental::csc()),
1947        _ => None,
1948    }
1949}
1950
1951fn rubi_active_symbol_for_trig(symbol: Symbol) -> Option<Symbol> {
1952    if let Some(active) = rubi_builtin_symbol_for_inert_trig(symbol) {
1953        return Some(active);
1954    }
1955
1956    match symbol {
1957        s if s == Symbol::SIN || s == Symbol::COS => Some(symbol),
1958        s if s == symbolica::transcendental::tan()
1959            || s == symbolica::transcendental::cot()
1960            || s == symbolica::transcendental::sec()
1961            || s == symbolica::transcendental::csc() =>
1962        {
1963            Some(symbol)
1964        }
1965        _ => None,
1966    }
1967}
1968
1969fn rubi_inert_trig_call(symbol: Symbol, argument: impl symbolica::atom::FunctionArgument) -> Atom {
1970    rubi_inert_symbol_for_builtin_trig(symbol)
1971        .unwrap_or(symbol)
1972        .call((argument,))
1973}
1974
1975#[inline(never)]
1976fn i_sin(argument: impl symbolica::atom::FunctionArgument) -> Atom {
1977    rubi_symbols().inert_sin.call((argument,))
1978}
1979
1980#[inline(never)]
1981fn i_cos(argument: impl symbolica::atom::FunctionArgument) -> Atom {
1982    rubi_symbols().inert_cos.call((argument,))
1983}
1984
1985#[inline(never)]
1986fn i_tan(argument: impl symbolica::atom::FunctionArgument) -> Atom {
1987    rubi_symbols().inert_tan.call((argument,))
1988}
1989
1990#[inline(never)]
1991fn i_cot(argument: impl symbolica::atom::FunctionArgument) -> Atom {
1992    rubi_symbols().inert_cot.call((argument,))
1993}
1994
1995#[inline(never)]
1996fn i_sec(argument: impl symbolica::atom::FunctionArgument) -> Atom {
1997    rubi_symbols().inert_sec.call((argument,))
1998}
1999
2000#[inline(never)]
2001fn i_csc(argument: impl symbolica::atom::FunctionArgument) -> Atom {
2002    rubi_symbols().inert_csc.call((argument,))
2003}
2004
2005fn rubi_builtin_trig_call(symbol: Symbol, argument: Atom) -> Atom {
2006    match rubi_active_symbol_for_trig(symbol).unwrap_or(symbol) {
2007        s if s == Symbol::SIN => argument.sin(),
2008        s if s == Symbol::COS => argument.cos(),
2009        s if s == symbolica::transcendental::tan() => argument.tan(),
2010        s if s == symbolica::transcendental::cot() => argument.cot(),
2011        s if s == symbolica::transcendental::sec() => argument.sec(),
2012        s if s == symbolica::transcendental::csc() => argument.csc(),
2013        s => s.call((argument,)),
2014    }
2015}
2016
2017/// Binds the wildcard representing the integration variable to its actual symbol.
2018macro_rules! rubi_with_integration_symbol {
2019    ($integration_symbol:ident; [$head:ident $(, $tail:ident)*]; $body:block) => {
2020        rubi_with_integration_symbol!(
2021            @is_x $integration_symbol;
2022            [$head] $head;
2023            [$($tail),*];
2024            $body
2025        )
2026    };
2027    (@is_x $integration_symbol:ident; [$x:ident] x_; [$($tail:ident),*]; $body:block) => {{
2028        let $x = $integration_symbol;
2029        let _ = &$x;
2030        $body
2031    }};
2032    (@is_x $integration_symbol:ident; [$head:ident] $not_x:ident; [$($tail:ident),+]; $body:block) => {
2033        rubi_with_integration_symbol!($integration_symbol; [$($tail),+]; $body)
2034    };
2035    (@is_x $integration_symbol:ident; [$head:ident] $not_x:ident; []; $body:block) => {
2036        compile_error!("every Rubi rule must include x_ in its with list")
2037    };
2038}
2039
2040/// Attaches feature-gated explanation metadata to a translated integration rule.
2041macro_rules! with_rubi_rule_explanation {
2042    ($rule:expr, $source:expr, $description:expr, $references:expr) => {{
2043        #[cfg(any(test, not(feature = "compressed-step-metadata")))]
2044        {
2045            with_rubi_rule_explanation!(@inline $rule, $source, $description, $references)
2046        }
2047        #[cfg(all(not(test), feature = "compressed-step-metadata"))]
2048        {
2049            let mut rule = $rule;
2050            rule.references = &$references;
2051            rule
2052        }
2053    }};
2054    // Rules without an upstream order cannot use the compressed catalog.
2055    (@inline $rule:expr, $source:expr, $description:expr, $references:expr) => {{
2056        let rule = $rule;
2057        #[cfg(any(test, feature = "steps"))]
2058        {
2059            let mut rule = rule;
2060            rule.source_pattern = Some($source);
2061            #[cfg(feature = "steps")]
2062            {
2063                rule.description = Some($description);
2064                rule.references = &$references;
2065            }
2066            rule
2067        }
2068        #[cfg(not(any(test, feature = "steps")))]
2069        {
2070            rule
2071        }
2072    }};
2073}
2074
2075#[cfg(any(test, feature = "trace"))]
2076macro_rules! rubi_rule_id {
2077    () => {
2078        concat!(module_path!(), ":", line!())
2079    };
2080}
2081
2082#[cfg(not(any(test, feature = "trace")))]
2083macro_rules! rubi_rule_id {
2084    () => {
2085        ()
2086    };
2087}
2088
2089/// Uses the symbol cached by a generated `push_rules` function. A few helper
2090/// rule modules do not bind the reserved integration wildcard locally.
2091#[cfg(not(test))]
2092macro_rules! rubi_rule_symbol {
2093    (x_) => {
2094        rubi_registration_symbols().x_
2095    };
2096    ($symbol:ident) => {
2097        $symbol
2098    };
2099}
2100
2101// Inline test rules are intentionally concise and do not always introduce
2102// local bindings for every wildcard before invoking `rubi_rule!`.
2103#[cfg(test)]
2104macro_rules! rubi_rule_symbol {
2105    ($symbol:ident) => {
2106        rubi_symbols().$symbol
2107    };
2108}
2109
2110#[inline(never)]
2111fn rubi_integer_condition_symbols() -> &'static RubiSymbols {
2112    rubi_symbols()
2113}
2114
2115/// Builds a generated rule condition, borrowing captures for pure `FreeQ`
2116/// guards and retaining owned captures for general condition expressions.
2117macro_rules! rubi_condition {
2118    ([$($wildcard:ident),*], { freeq!([$($free:ident),+ $(,)?], x_) && integerq!($integer:ident) }) => {
2119        rubi_condition!(@integer [$($wildcard),*] [$($free),+] $integer true)
2120    };
2121    ([$($wildcard:ident),*], { freeq!($free:ident, x_) && integerq!($integer:ident) }) => {
2122        rubi_condition!(@integer [$($wildcard),*] [$free] $integer true)
2123    };
2124    ([$($wildcard:ident),*], { freeq!([$($free:ident),+ $(,)?], x_) && !integerq!($integer:ident) }) => {
2125        rubi_condition!(@integer [$($wildcard),*] [$($free),+] $integer false)
2126    };
2127    ([$($wildcard:ident),*], { freeq!($free:ident, x_) && !integerq!($integer:ident) }) => {
2128        rubi_condition!(@integer [$($wildcard),*] [$free] $integer false)
2129    };
2130    (@integer [$($wildcard:ident),*] [$($free:ident),+] $integer:ident $expected:literal) => {
2131        (|matches, integration_symbol, rule| {
2132            let symbols = rubi_integer_condition_symbols();
2133            if wildcard_captures_are_free_and_integer(
2134                matches,
2135                rule,
2136                &[$(symbols.$free),+],
2137                symbols.$integer,
2138                integration_symbol,
2139                [$(stringify!($wildcard)),*].len(),
2140                $expected,
2141            ) {
2142                ConditionResult::True
2143            } else {
2144                ConditionResult::False
2145            }
2146        }) as RubiCondition
2147    };
2148    ([$($wildcard:ident),*], { freeq!([$($free:ident),+ $(,)?], x_) }) => {
2149        (|matches, integration_symbol, rule| {
2150            let symbols = rubi_symbols();
2151            if wildcard_captures_are_free(
2152                matches,
2153                rule,
2154                &[$(symbols.$free),+],
2155                integration_symbol,
2156            ) {
2157                ConditionResult::True
2158            } else {
2159                ConditionResult::False
2160            }
2161        }) as RubiCondition
2162    };
2163    ([$($wildcard:ident),*], { freeq!($free:ident, x_) }) => {
2164        (|matches, integration_symbol, rule| {
2165            if wildcard_captures_are_free(
2166                matches,
2167                rule,
2168                &[rubi_symbols().$free],
2169                integration_symbol,
2170            ) {
2171                ConditionResult::True
2172            } else {
2173                ConditionResult::False
2174            }
2175        }) as RubiCondition
2176    };
2177    ([$($wildcard:ident),*], $when:block) => {
2178        (|matches, integration_symbol, rule| {
2179            let [$($wildcard),*] =
2180                match required_wildcard_atoms_for_rule(matches, rule) {
2181                    Some(values) => values,
2182                    None => return ConditionResult::False,
2183                };
2184            $(let _ = &$wildcard;)*
2185            if !rubi_with_integration_symbol!(
2186                integration_symbol;
2187                [$($wildcard),*];
2188                $when
2189            ) {
2190                return ConditionResult::False;
2191            }
2192
2193            ConditionResult::True
2194        }) as RubiCondition
2195    };
2196}
2197
2198/// Builds a translated Rubi integration rule and its guarded action.
2199macro_rules! rubi_rule {
2200    (
2201        order: $order:expr,
2202        source: $source:expr,
2203        desc: $desc:expr,
2204        refs: $refs:expr,
2205        pattern: $pattern:expr,
2206        with: [$($wildcard:ident),* $(,)?],
2207        optional: [$($optional:ident),* $(,)?],
2208        x_free: [$($x_free:ident),* $(,)?],
2209        zero: [$($zero:ident),* $(,)?],
2210        scaled: [$(($scaled_left:ident, $scale:literal, $scaled_right:ident)),* $(,)?],
2211        when: $when:tt,
2212        rhs: $rhs:block $(,)?
2213    ) => {
2214        {
2215            let mut rule = rubi_rule!(
2216                order: $order,
2217                source: $source,
2218                desc: $desc,
2219                refs: $refs,
2220                pattern: $pattern,
2221                with: [$($wildcard),*],
2222                optional: [$($optional),*],
2223                x_free: [$($x_free),*],
2224                zero: [$($zero),*],
2225                when: $when,
2226                rhs: $rhs,
2227            );
2228            let symbols = rubi_registration_symbols();
2229            extend_rubi_rule_metadata(
2230                &mut rule.early_scaled_equal,
2231                &[$((symbols.$scaled_left, $scale, symbols.$scaled_right)),*],
2232            );
2233            rule
2234        }
2235    };
2236    (
2237        order: $order:expr,
2238        source: $source:expr,
2239        desc: $desc:expr,
2240        refs: $refs:expr,
2241        pattern: $pattern:expr,
2242        with: [$($wildcard:ident),* $(,)?],
2243        optional: [$($optional:ident),* $(,)?],
2244        x_free: [$($x_free:ident),* $(,)?],
2245        integer: [$($integer:ident),* $(,)?],
2246        scaled: [$(($scaled_left:ident, $scale:literal, $scaled_right:ident)),* $(,)?],
2247        when: $when:tt,
2248        rhs: $rhs:block $(,)?
2249    ) => {
2250        {
2251            let mut rule = rubi_rule!(
2252                order: $order,
2253                source: $source,
2254                desc: $desc,
2255                refs: $refs,
2256                pattern: $pattern,
2257                with: [$($wildcard),*],
2258                optional: [$($optional),*],
2259                x_free: [$($x_free),*],
2260                integer: [$($integer),*],
2261                when: $when,
2262                rhs: $rhs,
2263            );
2264            let symbols = rubi_registration_symbols();
2265            extend_rubi_rule_metadata(
2266                &mut rule.early_scaled_equal,
2267                &[$((symbols.$scaled_left, $scale, symbols.$scaled_right)),*],
2268            );
2269            rule
2270        }
2271    };
2272    (
2273        order: $order:expr,
2274        source: $source:expr,
2275        desc: $desc:expr,
2276        refs: $refs:expr,
2277        pattern: $pattern:expr,
2278        with: [$($wildcard:ident),* $(,)?],
2279        optional: [$($optional:ident),* $(,)?],
2280        x_free: [$($x_free:ident),* $(,)?],
2281        integer_gt: [$(($integer_gt:ident, $integer_gt_bound:literal)),* $(,)?],
2282        scaled: [$(($scaled_left:ident, $scale:literal, $scaled_right:ident)),* $(,)?],
2283        when: $when:tt,
2284        rhs: $rhs:block $(,)?
2285    ) => {
2286        {
2287            let mut rule = rubi_rule!(
2288                order: $order,
2289                source: $source,
2290                desc: $desc,
2291                refs: $refs,
2292                pattern: $pattern,
2293                with: [$($wildcard),*],
2294                optional: [$($optional),*],
2295                x_free: [$($x_free),*],
2296                integer_gt: [$(($integer_gt, $integer_gt_bound)),*],
2297                when: $when,
2298                rhs: $rhs,
2299            );
2300            let symbols = rubi_registration_symbols();
2301            extend_rubi_rule_metadata(
2302                &mut rule.early_scaled_equal,
2303                &[$((symbols.$scaled_left, $scale, symbols.$scaled_right)),*],
2304            );
2305            rule
2306        }
2307    };
2308    (
2309        order: $order:expr,
2310        source: $source:expr,
2311        desc: $desc:expr,
2312        refs: $refs:expr,
2313        pattern: $pattern:expr,
2314        with: [$($wildcard:ident),* $(,)?],
2315        optional: [$($optional:ident),* $(,)?],
2316        x_free: [$($x_free:ident),* $(,)?],
2317        integer_lt: [$(($integer_lt:ident, $integer_lt_bound:literal)),* $(,)?],
2318        scaled: [$(($scaled_left:ident, $scale:literal, $scaled_right:ident)),* $(,)?],
2319        when: $when:tt,
2320        rhs: $rhs:block $(,)?
2321    ) => {
2322        {
2323            let mut rule = rubi_rule!(
2324                order: $order,
2325                source: $source,
2326                desc: $desc,
2327                refs: $refs,
2328                pattern: $pattern,
2329                with: [$($wildcard),*],
2330                optional: [$($optional),*],
2331                x_free: [$($x_free),*],
2332                integer_lt: [$(($integer_lt, $integer_lt_bound)),*],
2333                when: $when,
2334                rhs: $rhs,
2335            );
2336            let symbols = rubi_registration_symbols();
2337            extend_rubi_rule_metadata(
2338                &mut rule.early_scaled_equal,
2339                &[$((symbols.$scaled_left, $scale, symbols.$scaled_right)),*],
2340            );
2341            rule
2342        }
2343    };
2344    (
2345        order: $order:expr,
2346        source: $source:expr,
2347        desc: $desc:expr,
2348        refs: $refs:expr,
2349        pattern: $pattern:expr,
2350        with: [$($wildcard:ident),* $(,)?],
2351        optional: [$($optional:ident),* $(,)?],
2352        x_free: [$($x_free:ident),* $(,)?],
2353        scaled: [$(($scaled_left:ident, $scale:literal, $scaled_right:ident)),* $(,)?],
2354        when: $when:tt,
2355        rhs: $rhs:block $(,)?
2356    ) => {
2357        {
2358            let mut rule = rubi_rule!(
2359                order: $order,
2360                source: $source,
2361                desc: $desc,
2362                refs: $refs,
2363                pattern: $pattern,
2364                with: [$($wildcard),*],
2365                optional: [$($optional),*],
2366                x_free: [$($x_free),*],
2367                when: $when,
2368                rhs: $rhs,
2369            );
2370            let symbols = rubi_registration_symbols();
2371            extend_rubi_rule_metadata(
2372                &mut rule.early_scaled_equal,
2373                &[$((symbols.$scaled_left, $scale, symbols.$scaled_right)),*],
2374            );
2375            rule
2376        }
2377    };
2378    (
2379        order: $order:expr,
2380        source: $source:expr,
2381        desc: $desc:expr,
2382        refs: $refs:expr,
2383        pattern: $pattern:expr,
2384        with: [$($wildcard:ident),* $(,)?],
2385        optional: [$($optional:ident),* $(,)?],
2386        x_free: [$($x_free:ident),* $(,)?],
2387        integer: [$($integer:ident),* $(,)?],
2388        when: $when:tt,
2389        rhs: $rhs:block $(,)?
2390    ) => {
2391        {
2392            let mut rule = rubi_rule!(
2393                order: $order,
2394                source: $source,
2395                desc: $desc,
2396                refs: $refs,
2397                pattern: $pattern,
2398                with: [$($wildcard),*],
2399                optional: [$($optional),*],
2400                x_free: [$($x_free),*],
2401                when: $when,
2402                rhs: $rhs,
2403            );
2404            let symbols = rubi_registration_symbols();
2405            extend_rubi_rule_metadata(
2406                &mut rule.early_numeric_bounds,
2407                &[$((symbols.$integer, RubiEarlyNumericBound::Integer)),*],
2408            );
2409            rule
2410        }
2411    };
2412    (
2413        order: $order:expr,
2414        source: $source:expr,
2415        desc: $desc:expr,
2416        refs: $refs:expr,
2417        pattern: $pattern:expr,
2418        with: [$($wildcard:ident),* $(,)?],
2419        optional: [$($optional:ident),* $(,)?],
2420        x_free: [$($x_free:ident),* $(,)?],
2421        integer_gt: [$(($integer_gt:ident, $integer_gt_bound:literal)),* $(,)?],
2422        when: $when:tt,
2423        rhs: $rhs:block $(,)?
2424    ) => {
2425        {
2426            let mut rule = rubi_rule!(
2427                order: $order,
2428                source: $source,
2429                desc: $desc,
2430                refs: $refs,
2431                pattern: $pattern,
2432                with: [$($wildcard),*],
2433                optional: [$($optional),*],
2434                x_free: [$($x_free),*],
2435                when: $when,
2436                rhs: $rhs,
2437            );
2438            let symbols = rubi_registration_symbols();
2439            extend_rubi_rule_metadata(
2440                &mut rule.early_numeric_bounds,
2441                &[$((symbols.$integer_gt, RubiEarlyNumericBound::IntegerGreaterThan($integer_gt_bound))),*],
2442            );
2443            rule
2444        }
2445    };
2446    (
2447        order: $order:expr,
2448        source: $source:expr,
2449        desc: $desc:expr,
2450        refs: $refs:expr,
2451        pattern: $pattern:expr,
2452        with: [$($wildcard:ident),* $(,)?],
2453        optional: [$($optional:ident),* $(,)?],
2454        x_free: [$($x_free:ident),* $(,)?],
2455        integer_lt: [$(($integer_lt:ident, $integer_lt_bound:literal)),* $(,)?],
2456        when: $when:tt,
2457        rhs: $rhs:block $(,)?
2458    ) => {
2459        {
2460            let mut rule = rubi_rule!(
2461                order: $order,
2462                source: $source,
2463                desc: $desc,
2464                refs: $refs,
2465                pattern: $pattern,
2466                with: [$($wildcard),*],
2467                optional: [$($optional),*],
2468                x_free: [$($x_free),*],
2469                when: $when,
2470                rhs: $rhs,
2471            );
2472            let symbols = rubi_registration_symbols();
2473            extend_rubi_rule_metadata(
2474                &mut rule.early_numeric_bounds,
2475                &[$((symbols.$integer_lt, RubiEarlyNumericBound::IntegerLessThan($integer_lt_bound))),*],
2476            );
2477            rule
2478        }
2479    };
2480    (
2481        order: $order:expr,
2482        source: $source:expr,
2483        desc: $desc:expr,
2484        refs: $refs:expr,
2485        pattern: $pattern:expr,
2486        with: [$($wildcard:ident),* $(,)?],
2487        optional: [$($optional:ident),* $(,)?],
2488        x_free: [$($x_free:ident),* $(,)?],
2489        derivative_pair: [$(($polynomial:ident, $derivative:ident)),* $(,)?],
2490        when: $when:tt,
2491        rhs: $rhs:block $(,)?
2492    ) => {
2493        {
2494            let mut rule = rubi_rule!(
2495                order: $order,
2496                source: $source,
2497                desc: $desc,
2498                refs: $refs,
2499                pattern: $pattern,
2500                with: [$($wildcard),*],
2501                optional: [$($optional),*],
2502                x_free: [$($x_free),*],
2503                when: $when,
2504                rhs: $rhs,
2505            );
2506            let symbols = rubi_registration_symbols();
2507            extend_rubi_rule_metadata(
2508                &mut rule.early_polynomial_derivative_pairs,
2509                &[$((symbols.$polynomial, symbols.$derivative)),*],
2510            );
2511            rule
2512        }
2513    };
2514    (
2515        order: $order:expr,
2516        source: $source:expr,
2517        desc: $desc:expr,
2518        refs: $refs:expr,
2519        pattern: $pattern:expr,
2520        with: [$($wildcard:ident),* $(,)?],
2521        optional: [$($optional:ident),* $(,)?],
2522        x_free: [$($x_free:ident),* $(,)?],
2523        proportional_common: [$(($a:ident, $b:ident, $c:ident, $d:ident)),* $(,)?],
2524        when: $when:tt,
2525        rhs: $rhs:block $(,)?
2526    ) => {
2527        {
2528            let mut rule = rubi_rule!(
2529                order: $order,
2530                source: $source,
2531                desc: $desc,
2532                refs: $refs,
2533                pattern: $pattern,
2534                with: [$($wildcard),*],
2535                optional: [$($optional),*],
2536                x_free: [$($x_free),*],
2537                when: $when,
2538                rhs: $rhs,
2539            );
2540            let symbols = rubi_registration_symbols();
2541            $(rule = rule.with_early_proportional_common_expression([
2542                symbols.$a,
2543                symbols.$b,
2544                symbols.$c,
2545                symbols.$d,
2546            ]);)*
2547            rule
2548        }
2549    };
2550    (
2551        order: $order:expr,
2552        source: $source:expr,
2553        desc: $desc:expr,
2554        refs: $refs:expr,
2555        pattern: $pattern:expr,
2556        with: [$($wildcard:ident),* $(,)?],
2557        optional: [$($optional:ident),* $(,)?],
2558        x_free: [$($x_free:ident),* $(,)?],
2559        proportional: [$(($a:ident, $b:ident, $c:ident, $d:ident)),* $(,)?],
2560        when: $when:tt,
2561        rhs: $rhs:block $(,)?
2562    ) => {
2563        {
2564            let mut rule = rubi_rule!(
2565                order: $order,
2566                source: $source,
2567                desc: $desc,
2568                refs: $refs,
2569                pattern: $pattern,
2570                with: [$($wildcard),*],
2571                optional: [$($optional),*],
2572                x_free: [$($x_free),*],
2573                when: $when,
2574                rhs: $rhs,
2575            );
2576            let symbols = rubi_registration_symbols();
2577            $(rule = rule.with_early_proportional_affine([
2578                symbols.$a,
2579                symbols.$b,
2580                symbols.$c,
2581                symbols.$d,
2582            ]);)*
2583            rule
2584        }
2585    };
2586    (
2587        source: $source:expr,
2588        desc: $desc:expr,
2589        refs: $refs:expr,
2590        pattern: $pattern:expr,
2591        with: [$($wildcard:ident),* $(,)?],
2592        optional: [$($optional:ident),* $(,)?],
2593        x_dep: [$($x_dependent:ident),* $(,)?],
2594        x_free: [$($x_free:ident),* $(,)?],
2595        x_linear: [$($x_linear:ident),* $(,)?],
2596        when: $when:tt,
2597        rhs: $rhs:block $(,)?
2598    ) => {
2599        {
2600            let mut rule = rubi_rule!(
2601                source: $source,
2602                desc: $desc,
2603                refs: $refs,
2604                pattern: $pattern,
2605                with: [$($wildcard),*],
2606                optional: [$($optional),*],
2607                x_dep: [$($x_dependent),*],
2608                x_free: [$($x_free),*],
2609                when: $when,
2610                rhs: $rhs,
2611            );
2612            let symbols = rubi_registration_symbols();
2613            extend_rubi_rule_metadata(
2614                &mut rule.early_x_linear,
2615                &[$(symbols.$x_linear),*],
2616            );
2617            rule
2618        }
2619    };
2620    (
2621        order: $order:expr,
2622        source: $source:expr,
2623        desc: $desc:expr,
2624        refs: $refs:expr,
2625        pattern: $pattern:expr,
2626        with: [$($wildcard:ident),* $(,)?],
2627        optional: [$($optional:ident),* $(,)?],
2628        x_dep: [$($x_dependent:ident),* $(,)?],
2629        x_free: [$($x_free:ident),* $(,)?],
2630        x_linear: [$($x_linear:ident),* $(,)?],
2631        when: $when:tt,
2632        rhs: $rhs:block $(,)?
2633    ) => {
2634        {
2635            let mut rule = rubi_rule!(
2636                order: $order,
2637                source: $source,
2638                desc: $desc,
2639                refs: $refs,
2640                pattern: $pattern,
2641                with: [$($wildcard),*],
2642                optional: [$($optional),*],
2643                x_dep: [$($x_dependent),*],
2644                x_free: [$($x_free),*],
2645                when: $when,
2646                rhs: $rhs,
2647            );
2648            let symbols = rubi_registration_symbols();
2649            extend_rubi_rule_metadata(
2650                &mut rule.early_x_linear,
2651                &[$(symbols.$x_linear),*],
2652            );
2653            rule
2654        }
2655    };
2656    (
2657        order: $order:expr,
2658        source: $source:expr,
2659        desc: $desc:expr,
2660        refs: $refs:expr,
2661        pattern: $pattern:expr,
2662        with: [$($wildcard:ident),* $(,)?],
2663        optional: [$($optional:ident),* $(,)?],
2664        x_free: [$($x_free:ident),* $(,)?],
2665        zero: [$($zero:ident),* $(,)?],
2666        when: $when:tt,
2667        rhs: $rhs:block $(,)?
2668    ) => {
2669        {
2670            let mut rule = rubi_rule!(
2671                order: $order,
2672                source: $source,
2673                desc: $desc,
2674                refs: $refs,
2675                pattern: $pattern,
2676                with: [$($wildcard),*],
2677                optional: [$($optional),*],
2678                x_free: [$($x_free),*],
2679                when: $when,
2680                rhs: $rhs,
2681            );
2682            let symbols = rubi_registration_symbols();
2683            extend_rubi_rule_metadata(
2684                &mut rule.early_zero,
2685                &[$(symbols.$zero),*],
2686            );
2687            rule
2688        }
2689    };
2690    (
2691        order: $order:expr,
2692        source: $source:expr,
2693        desc: $desc:expr,
2694        refs: $refs:expr,
2695        pattern: $pattern:expr,
2696        with: [$($wildcard:ident),* $(,)?],
2697        x_free: [$($x_free:ident),* $(,)?],
2698        when: $when:tt,
2699        rhs: $rhs:block $(,)?
2700    ) => {
2701        rubi_rule!(
2702            order: $order,
2703            source: $source,
2704            desc: $desc,
2705            refs: $refs,
2706            pattern: $pattern,
2707            with: [$($wildcard),*],
2708            optional: [],
2709            x_free: [$($x_free),*],
2710            when: $when,
2711            rhs: $rhs,
2712        )
2713    };
2714    (
2715        order: $order:expr,
2716        source: $source:expr,
2717        desc: $desc:expr,
2718        refs: $refs:expr,
2719        pattern: $pattern:expr,
2720        with: [$($wildcard:ident),* $(,)?],
2721        optional: [$($optional:ident),* $(,)?],
2722        x_free: [$($x_free:ident),* $(,)?],
2723        when: $when:tt,
2724        rhs: $rhs:block $(,)?
2725    ) => {
2726        {
2727            let mut rule = rubi_rule!(
2728                order: $order,
2729                source: $source,
2730                desc: $desc,
2731                refs: $refs,
2732                pattern: $pattern,
2733                with: [$($wildcard),*],
2734                optional: [$($optional),*],
2735                when: $when,
2736                rhs: $rhs,
2737            );
2738            let symbols = rubi_registration_symbols();
2739            extend_rubi_rule_metadata(
2740                &mut rule.early_x_free,
2741                &[$(symbols.$x_free),*],
2742            );
2743            rule
2744        }
2745    };
2746    (
2747        source: $source:expr,
2748        desc: $desc:expr,
2749        refs: $refs:expr,
2750        pattern: $pattern:expr,
2751        with: [$($wildcard:ident),* $(,)?],
2752        x_free: [$($x_free:ident),* $(,)?],
2753        when: $when:tt,
2754        rhs: $rhs:block $(,)?
2755    ) => {
2756        rubi_rule!(
2757            source: $source,
2758            desc: $desc,
2759            refs: $refs,
2760            pattern: $pattern,
2761            with: [$($wildcard),*],
2762            optional: [],
2763            x_free: [$($x_free),*],
2764            when: $when,
2765            rhs: $rhs,
2766        )
2767    };
2768    (
2769        source: $source:expr,
2770        desc: $desc:expr,
2771        refs: $refs:expr,
2772        pattern: $pattern:expr,
2773        with: [$($wildcard:ident),* $(,)?],
2774        optional: [$($optional:ident),* $(,)?],
2775        x_free: [$($x_free:ident),* $(,)?],
2776        when: $when:tt,
2777        rhs: $rhs:block $(,)?
2778    ) => {
2779        {
2780            let mut rule = rubi_rule!(
2781                source: $source,
2782                desc: $desc,
2783                refs: $refs,
2784                pattern: $pattern,
2785                with: [$($wildcard),*],
2786                optional: [$($optional),*],
2787                when: $when,
2788                rhs: $rhs,
2789            );
2790            let symbols = rubi_registration_symbols();
2791            extend_rubi_rule_metadata(
2792                &mut rule.early_x_free,
2793                &[$(symbols.$x_free),*],
2794            );
2795            rule
2796        }
2797    };
2798    (
2799        order: $order:expr,
2800        source: $source:expr,
2801        desc: $desc:expr,
2802        refs: $refs:expr,
2803        pattern: $pattern:expr,
2804        with: [$($wildcard:ident),* $(,)?],
2805        x_dep: [$($x_dependent:ident),* $(,)?],
2806        x_free: [$($x_free:ident),* $(,)?],
2807        when: $when:tt,
2808        rhs: $rhs:block $(,)?
2809    ) => {
2810        rubi_rule!(
2811            order: $order,
2812            source: $source,
2813            desc: $desc,
2814            refs: $refs,
2815            pattern: $pattern,
2816            with: [$($wildcard),*],
2817            optional: [],
2818            x_dep: [$($x_dependent),*],
2819            x_free: [$($x_free),*],
2820            when: $when,
2821            rhs: $rhs,
2822        )
2823    };
2824    (
2825        order: $order:expr,
2826        source: $source:expr,
2827        desc: $desc:expr,
2828        refs: $refs:expr,
2829        pattern: $pattern:expr,
2830        with: [$($wildcard:ident),* $(,)?],
2831        optional: [$($optional:ident),* $(,)?],
2832        x_dep: [$($x_dependent:ident),* $(,)?],
2833        x_free: [$($x_free:ident),* $(,)?],
2834        when: $when:tt,
2835        rhs: $rhs:block $(,)?
2836    ) => {
2837        {
2838            let mut rule = rubi_rule!(
2839                order: $order,
2840                source: $source,
2841                desc: $desc,
2842                refs: $refs,
2843                pattern: $pattern,
2844                with: [$($wildcard),*],
2845                optional: [$($optional),*],
2846                when: $when,
2847                rhs: $rhs,
2848            );
2849            let symbols = rubi_registration_symbols();
2850            extend_rubi_rule_metadata(
2851                &mut rule.early_x_dependent,
2852                &[$(symbols.$x_dependent),*],
2853            );
2854            extend_rubi_rule_metadata(
2855                &mut rule.early_x_free,
2856                &[$(symbols.$x_free),*],
2857            );
2858            rule
2859        }
2860    };
2861    (
2862        source: $source:expr,
2863        desc: $desc:expr,
2864        refs: $refs:expr,
2865        pattern: $pattern:expr,
2866        with: [$($wildcard:ident),* $(,)?],
2867        x_dep: [$($x_dependent:ident),* $(,)?],
2868        x_free: [$($x_free:ident),* $(,)?],
2869        when: $when:tt,
2870        rhs: $rhs:block $(,)?
2871    ) => {
2872        rubi_rule!(
2873            source: $source,
2874            desc: $desc,
2875            refs: $refs,
2876            pattern: $pattern,
2877            with: [$($wildcard),*],
2878            optional: [],
2879            x_dep: [$($x_dependent),*],
2880            x_free: [$($x_free),*],
2881            when: $when,
2882            rhs: $rhs,
2883        )
2884    };
2885    (
2886        source: $source:expr,
2887        desc: $desc:expr,
2888        refs: $refs:expr,
2889        pattern: $pattern:expr,
2890        with: [$($wildcard:ident),* $(,)?],
2891        optional: [$($optional:ident),* $(,)?],
2892        x_dep: [$($x_dependent:ident),* $(,)?],
2893        x_free: [$($x_free:ident),* $(,)?],
2894        when: $when:tt,
2895        rhs: $rhs:block $(,)?
2896    ) => {
2897        {
2898            let mut rule = rubi_rule!(
2899                source: $source,
2900                desc: $desc,
2901                refs: $refs,
2902                pattern: $pattern,
2903                with: [$($wildcard),*],
2904                optional: [$($optional),*],
2905                when: $when,
2906                rhs: $rhs,
2907            );
2908            let symbols = rubi_registration_symbols();
2909            extend_rubi_rule_metadata(
2910                &mut rule.early_x_dependent,
2911                &[$(symbols.$x_dependent),*],
2912            );
2913            extend_rubi_rule_metadata(
2914                &mut rule.early_x_free,
2915                &[$(symbols.$x_free),*],
2916            );
2917            rule
2918        }
2919    };
2920    (
2921        order: $order:expr,
2922        source: $source:expr,
2923        desc: $desc:expr,
2924        refs: $refs:expr,
2925        pattern: $pattern:expr,
2926        with: [$($wildcard:ident),* $(,)?],
2927        when: $when:tt,
2928        rhs: $rhs:block $(,)?
2929    ) => {
2930        rubi_rule!(
2931            order: $order,
2932            source: $source,
2933            desc: $desc,
2934            refs: $refs,
2935            pattern: $pattern,
2936            with: [$($wildcard),*],
2937            optional: [],
2938            when: $when,
2939            rhs: $rhs,
2940        )
2941    };
2942    (
2943        order: $order:expr,
2944        source: $source:expr,
2945        desc: $desc:expr,
2946        refs: $refs:expr,
2947        pattern: $pattern:expr,
2948        with: [$($wildcard:ident),* $(,)?],
2949        optional: [$($optional:ident),* $(,)?],
2950        noninteger_power_factors: $noninteger_power_factors:literal,
2951        when: $when:tt,
2952        rhs: $rhs:block $(,)?
2953    ) => {
2954        rubi_rule!(
2955            order: $order,
2956            source: $source,
2957            desc: $desc,
2958            refs: $refs,
2959            pattern: $pattern,
2960            with: [$($wildcard),*],
2961            optional: [$($optional),*],
2962            when: $when,
2963            rhs: $rhs,
2964        )
2965        .with_noninteger_power_factor_count($noninteger_power_factors)
2966    };
2967    (
2968        order: $order:expr,
2969        source: $source:expr,
2970        desc: $desc:expr,
2971        refs: $refs:expr,
2972        pattern: $pattern:expr,
2973        with: [$($wildcard:ident),* $(,)?],
2974        optional: [$($optional:ident),* $(,)?],
2975        when: $when:tt,
2976        rhs: $rhs:block $(,)?
2977    ) => {
2978        with_rubi_rule_explanation!(build_rubi_rule(
2979            rubi_rule_id!(),
2980            Some($order),
2981            $pattern,
2982            &[$(rubi_rule_symbol!($wildcard)),*],
2983            &[$(rubi_rule_symbol!($optional)),*],
2984            rubi_condition!([$($wildcard),*], $when),
2985            (|matches, integration_symbol, rule| {
2986                let [$($wildcard),*] =
2987                    required_wildcard_atoms_for_rule(matches, rule)?;
2988                $(let _ = &$wildcard;)*
2989                // The closure deliberately scopes `return` inside a generated rule RHS.
2990                #[allow(clippy::redundant_closure_call)]
2991                let rhs = (|| -> Atom {
2992                    rubi_with_integration_symbol!(
2993                        integration_symbol;
2994                        [$($wildcard),*];
2995                        $rhs
2996                    )
2997                })();
2998                Some(rhs)
2999            }) as RubiAction,
3000        ), $source, $desc, $refs)
3001    };
3002    (
3003        source: $source:expr,
3004        desc: $desc:expr,
3005        refs: $refs:expr,
3006        pattern: $pattern:expr,
3007        with: [$($wildcard:ident),* $(,)?],
3008        when: $when:tt,
3009        rhs: $rhs:block $(,)?
3010    ) => {
3011        rubi_rule!(
3012            source: $source,
3013            desc: $desc,
3014            refs: $refs,
3015            pattern: $pattern,
3016            with: [$($wildcard),*],
3017            optional: [],
3018            when: $when,
3019            rhs: $rhs,
3020        )
3021    };
3022    (
3023        source: $source:expr,
3024        desc: $desc:expr,
3025        refs: $refs:expr,
3026        pattern: $pattern:expr,
3027        with: [$($wildcard:ident),* $(,)?],
3028        optional: [$($optional:ident),* $(,)?],
3029        when: $when:tt,
3030        rhs: $rhs:block $(,)?
3031    ) => {
3032        with_rubi_rule_explanation!(@inline build_rubi_rule(
3033            rubi_rule_id!(),
3034            None,
3035            $pattern,
3036            &[$(rubi_rule_symbol!($wildcard)),*],
3037            &[$(rubi_rule_symbol!($optional)),*],
3038            rubi_condition!([$($wildcard),*], $when),
3039            (|matches, integration_symbol, rule| {
3040                let [$($wildcard),*] =
3041                    required_wildcard_atoms_for_rule(matches, rule)?;
3042                $(let _ = &$wildcard;)*
3043                // The closure deliberately scopes `return` inside a generated rule RHS.
3044                #[allow(clippy::redundant_closure_call)]
3045                let rhs = (|| -> Atom {
3046                    rubi_with_integration_symbol!(
3047                        integration_symbol;
3048                        [$($wildcard),*];
3049                        $rhs
3050                    )
3051                })();
3052                Some(rhs)
3053            }) as RubiAction,
3054        ), $source, $desc, $refs)
3055    };
3056}
3057
3058/// Attaches feature-gated source metadata to a translated helper rule.
3059macro_rules! with_rubi_rule_source {
3060    ($rule:expr, $source:expr) => {{
3061        let rule = $rule;
3062        #[cfg(any(test, feature = "steps"))]
3063        {
3064            let mut rule = rule;
3065            rule.source_pattern = Some($source);
3066            rule
3067        }
3068        #[cfg(not(any(test, feature = "steps")))]
3069        {
3070            rule
3071        }
3072    }};
3073}
3074
3075/// Builds a translated rule for a Rubi helper function.
3076macro_rules! rubi_helper_row {
3077    (
3078        order: $order:expr,
3079        source: $source:expr,
3080        pattern: $pattern:expr,
3081        head: $head:expr,
3082        with: [$($wildcard:ident),* $(,)?],
3083        optional: [$($optional:ident),* $(,)?],
3084        x_dep: [$($x_dependent:ident),* $(,)?],
3085        x_free: [$($x_free:ident),* $(,)?],
3086        noninteger_affine_power_difference: true,
3087        when: $when:tt,
3088        rhs: $rhs:block $(,)?
3089    ) => {
3090        rubi_helper_row!(
3091            order: $order,
3092            source: $source,
3093            pattern: $pattern,
3094            head: $head,
3095            with: [$($wildcard),*],
3096            optional: [$($optional),*],
3097            x_dep: [$($x_dependent),*],
3098            x_free: [$($x_free),*],
3099            when: $when,
3100            rhs: $rhs,
3101        ).with_noninteger_affine_exponent_with_positive_difference()
3102    };
3103    (
3104        order: $order:expr,
3105        source: $source:expr,
3106        pattern: $pattern:expr,
3107        head: $head:expr,
3108        with: [$($wildcard:ident),* $(,)?],
3109        optional: [$($optional:ident),* $(,)?],
3110        x_dep: [$($x_dependent:ident),* $(,)?],
3111        x_free: [$($x_free:ident),* $(,)?],
3112        when: $when:tt,
3113        rhs: $rhs:block $(,)?
3114    ) => {
3115        {
3116            let mut rule = rubi_helper_row!(
3117                order: $order,
3118                source: $source,
3119                pattern: $pattern,
3120                head: $head,
3121                with: [$($wildcard),*],
3122                optional: [$($optional),*],
3123                when: $when,
3124                rhs: $rhs,
3125            );
3126            let symbols = rubi_registration_symbols();
3127            extend_rubi_rule_metadata(
3128                &mut rule.early_x_dependent,
3129                &[$(symbols.$x_dependent),*],
3130            );
3131            extend_rubi_rule_metadata(
3132                &mut rule.early_x_free,
3133                &[$(symbols.$x_free),*],
3134            );
3135            rule
3136        }
3137    };
3138    (
3139        order: $order:expr,
3140        source: $source:expr,
3141        pattern: $pattern:expr,
3142        head: $head:expr,
3143        with: [$($wildcard:ident),* $(,)?],
3144        when: $when:tt,
3145        rhs: $rhs:block $(,)?
3146    ) => {
3147        rubi_helper_row!(
3148            order: $order,
3149            source: $source,
3150            pattern: $pattern,
3151            head: $head,
3152            with: [$($wildcard),*],
3153            optional: [],
3154            when: $when,
3155            rhs: $rhs,
3156        )
3157    };
3158    (
3159        order: $order:expr,
3160        source: $source:expr,
3161        pattern: $pattern:expr,
3162        head: $head:expr,
3163        with: [$($wildcard:ident),* $(,)?],
3164        optional: [$($optional:ident),* $(,)?],
3165        when: $when:tt,
3166        rhs: $rhs:block $(,)?
3167    ) => {
3168        with_rubi_rule_source!(build_rubi_helper_rule(
3169            rubi_rule_id!(),
3170            $order,
3171            $pattern,
3172            $head,
3173            &[$(rubi_rule_symbol!($wildcard)),*],
3174            &[$(rubi_rule_symbol!($optional)),*],
3175            rubi_condition!([$($wildcard),*], $when),
3176            (|matches, integration_symbol, rule| {
3177                let [$($wildcard),*] =
3178                    required_wildcard_atoms_for_rule(matches, rule)?;
3179                $(let _ = &$wildcard;)*
3180                // The closure deliberately scopes `return` inside a generated helper RHS.
3181                #[allow(clippy::redundant_closure_call)]
3182                let rhs = (|| -> Option<Atom> {
3183                    Some(rubi_with_integration_symbol!(
3184                        integration_symbol;
3185                        [$($wildcard),*];
3186                        $rhs
3187                    ))
3188                })();
3189                rhs
3190            }) as RubiAction,
3191        ), $source)
3192    };
3193}
3194
3195/// Evaluates Rubi's `FreeQ` predicate for one or more expressions.
3196macro_rules! freeq {
3197    ([$($expr:expr),+ $(,)?], $x:expr) => {
3198        is_free_of(($(&$expr,)+), $x)
3199    };
3200    ($expr:expr, $x:expr) => {
3201        is_free_of(&$expr, $x)
3202    };
3203}
3204
3205/// Evaluates Rubi's algebraic `EqQ` predicate.
3206macro_rules! eqq {
3207    ($left:expr, $right:expr) => {
3208        rubi_algebraic_eq_q(
3209            RubiAtomArgument::rubi_atom_or_view(&($left)),
3210            RubiAtomArgument::rubi_atom_or_view(&($right)),
3211        )
3212    };
3213}
3214
3215// Borrow captures instead of cloning them for a read-only comparison, and
3216// share subtraction and temporary cleanup across the generated EqQ/NeQ guards.
3217#[inline(never)]
3218fn rubi_algebraic_eq_q(left: AtomOrView<'_>, right: AtomOrView<'_>) -> bool {
3219    rubi_algebraic_zero_q(&(left.as_view() - right.as_view()))
3220}
3221
3222/// Evaluates Rubi's `NeQ` predicate, including its unevaluated unary form.
3223macro_rules! neq {
3224    ($expr:expr) => {{
3225        // Rubi defines only NeQ[u_, v_]. A unary NeQ remains unevaluated and
3226        // therefore cannot satisfy a Mathematica Condition.
3227        let _ = &$expr;
3228        false
3229    }};
3230    ($left:expr, $right:expr) => {
3231        !eqq!($left, $right)
3232    };
3233}
3234
3235/// Evaluates Rubi's numeric `GtQ` predicate.
3236macro_rules! gtq {
3237    ($expr:expr, -$threshold:literal) => {
3238        is_number_greater_than(&$expr, -$threshold)
3239    };
3240    ($expr:expr, $threshold:literal) => {
3241        is_number_greater_than(&$expr, $threshold)
3242    };
3243    ($expr:expr, $threshold:expr) => {
3244        is_number_greater_than_atom(&$expr, &$threshold)
3245    };
3246}
3247
3248/// Evaluates Rubi's numeric `GeQ` predicate.
3249macro_rules! geq {
3250    ($expr:expr, -$threshold:literal) => {
3251        is_number_greater_or_equal(&$expr, -$threshold)
3252    };
3253    ($expr:expr, $threshold:literal) => {
3254        is_number_greater_or_equal(&$expr, $threshold)
3255    };
3256    ($expr:expr, $threshold:expr) => {
3257        is_number_greater_or_equal_atom(&$expr, &$threshold)
3258    };
3259}
3260
3261/// Evaluates Rubi's numeric `LtQ` predicate and chained comparison form.
3262macro_rules! ltq {
3263    ($lower:literal, $expr:expr, $upper:literal) => {
3264        is_number_greater_than(&$expr, $lower) && is_number_less_than(&$expr, $upper)
3265    };
3266    ($lower:literal, $expr:expr, $upper:expr) => {
3267        is_number_greater_than(&$expr, $lower) && is_number_less_than_atom(&$expr, &$upper)
3268    };
3269    ($lower:expr, $expr:expr, $upper:literal) => {
3270        is_number_less_than_atom(&$lower, &$expr) && is_number_less_than(&$expr, $upper)
3271    };
3272    ($expr:expr, $threshold:literal) => {
3273        is_number_less_than(&$expr, $threshold)
3274    };
3275    ($expr:expr, $threshold:expr) => {
3276        is_number_less_than_atom(&$expr, &$threshold)
3277    };
3278}
3279
3280/// Evaluates Rubi's numeric `LeQ` predicate and chained comparison form.
3281macro_rules! leq {
3282    ($lower:literal, $expr:expr, $upper:literal) => {
3283        is_number_greater_or_equal(&$expr, $lower) && is_number_less_or_equal(&$expr, $upper)
3284    };
3285    ($lower:expr, $expr:expr, $upper:expr) => {
3286        leq!($lower, $expr) && leq!($expr, $upper)
3287    };
3288    ($left:literal, $right:expr) => {
3289        is_number_greater_or_equal(&$right, $left)
3290    };
3291    ($expr:expr, $threshold:literal) => {
3292        is_number_less_or_equal(&$expr, $threshold)
3293    };
3294    ($expr:expr, $threshold:expr) => {
3295        is_number_less_or_equal_atom(&$expr, &$threshold)
3296    };
3297}
3298
3299/// Extracts the integer denominator used by translated Rubi guards.
3300macro_rules! denominator {
3301    ($expr:expr) => {
3302        rational_denominator(&$expr).unwrap_or(0)
3303    };
3304}
3305
3306/// Evaluates Rubi's canonical negativity predicate.
3307macro_rules! negq {
3308    ($expr:expr) => {
3309        rubi_neg_q(&$expr)
3310    };
3311}
3312
3313/// Evaluates Rubi's canonical positivity predicate.
3314macro_rules! posq {
3315    ($expr:expr) => {
3316        rubi_pos_q(&$expr)
3317    };
3318}
3319
3320/// Evaluates Rubi's integer predicate.
3321macro_rules! integerq {
3322    ($expr:expr) => {
3323        integer_q(&$expr)
3324    };
3325}
3326
3327/// Evaluates Rubi's integer predicate for a list of expressions.
3328macro_rules! integersq {
3329    ([$($expr:expr),+ $(,)?]) => {
3330        integers_q(&[$(AsRef::<Atom>::as_ref(&($expr))),+])
3331    };
3332}
3333
3334/// Tests whether an expression is an exact non-integer rational number.
3335macro_rules! fractionq {
3336    ($expr:expr) => {
3337        is_fraction_number(&$expr)
3338    };
3339}
3340
3341/// Evaluates Rubi's rational predicate for one or more expressions.
3342macro_rules! rationalq {
3343    ([$($expr:expr),+ $(,)?]) => {
3344        true $(&& rational_q(&$expr))+
3345    };
3346    ($expr:expr) => {
3347        rational_q(&$expr)
3348    };
3349}
3350
3351/// Tests whether an expression is an integer above a bound.
3352macro_rules! igtq {
3353    ($expr:expr, $threshold:expr) => {
3354        is_integer_greater_than_bound(&$expr, $threshold)
3355    };
3356}
3357
3358/// Tests whether an expression is an integer at or above a bound.
3359macro_rules! igeq {
3360    ($expr:expr, $threshold:expr) => {
3361        integerq!($expr) && geq!($expr, $threshold)
3362    };
3363}
3364
3365/// Tests whether an expression is an integer below a bound.
3366macro_rules! iltq {
3367    ($expr:expr, $threshold:expr) => {
3368        is_integer_less_than_bound(&$expr, $threshold)
3369    };
3370}
3371
3372/// Tests whether an expression is an integer at or below a bound.
3373macro_rules! ileq {
3374    ($expr:expr, $threshold:expr) => {
3375        is_integer_less_or_equal(&$expr, $threshold)
3376    };
3377}
3378
3379/// Evaluates Rubi's sum-complexity comparison after applying a shift.
3380macro_rules! sum_simplerq {
3381    ($expr:expr, $shift:expr) => {
3382        rubi_sum_simpler(&$expr, $shift)
3383    };
3384}
3385
3386/// Evaluates Rubi's structural simplicity ordering.
3387macro_rules! simplerq {
3388    ($left:expr, $right:expr) => {
3389        rubi_simpler_q(&$left, &$right)
3390    };
3391}
3392
3393/// Applies Rubi's integrand simplifier with respect to a variable.
3394macro_rules! simp {
3395    ($expr:expr, $x:expr) => {
3396        rubi_simp(&$expr, $x)
3397    };
3398}
3399
3400/// Evaluates Rubi's exponent guard for products of two linear powers.
3401macro_rules! int_linearq {
3402    ($a:expr, $b:expr, $c:expr, $d:expr, $m:expr, $n:expr, $x:expr) => {{
3403        let _ = (&$a, &$b, &$c, &$d, $x);
3404        int_linear_q(&$m, &$n)
3405    }};
3406}
3407
3408/// Introduces local bindings for symbols from the shared Rubi symbol table.
3409macro_rules! rubi_symb {
3410    ($symbols:ident; $($name:ident),+ $(,)?) => {
3411        let $symbols = rubi_registration_symbols();
3412        $(#[allow(unused_variables)] let $name = $symbols.$name;)+
3413    };
3414    ($($name:ident),+ $(,)?) => {
3415        let symbols = rubi_registration_symbols();
3416        $(let $name = symbols.$name;)+
3417    };
3418}
3419
3420// Nested guard matchers bind symbols while evaluating a rule, so keep their
3421// access on the existing hot path rather than the registration helper.
3422macro_rules! rubi_runtime_symb {
3423    ($($name:ident),+ $(,)?) => {
3424        let symbols = rubi_symbols();
3425        $(let $name = symbols.$name;)+
3426    };
3427}
3428
3429mod rules;
3430
3431#[derive(Clone, Copy)]
3432/// Interned symbols used by translated Rubi patterns and helper functions.
3433struct RubiSymbols {
3434    capital_a_: Symbol,
3435    capital_a__: Symbol,
3436    capital_b_: Symbol,
3437    capital_b__: Symbol,
3438    capital_c_: Symbol,
3439    capital_c__: Symbol,
3440    capital_f_: Symbol,
3441    capital_f__: Symbol,
3442    capital_g_: Symbol,
3443    capital_h_: Symbol,
3444    afx__: Symbol,
3445    a_: Symbol,
3446    a__: Symbol,
3447    a1__: Symbol,
3448    a2__: Symbol,
3449    b__: Symbol,
3450    b1__: Symbol,
3451    b2__: Symbol,
3452    c_: Symbol,
3453    c__: Symbol,
3454    d_: Symbol,
3455    d__: Symbol,
3456    d1__: Symbol,
3457    d2__: Symbol,
3458    e__: Symbol,
3459    e1__: Symbol,
3460    e2__: Symbol,
3461    f_: Symbol,
3462    f__: Symbol,
3463    fx__: Symbol,
3464    f1__: Symbol,
3465    f2__: Symbol,
3466    g_: Symbol,
3467    g__: Symbol,
3468    g1__: Symbol,
3469    g2__: Symbol,
3470    h__: Symbol,
3471    i_: Symbol,
3472    i__: Symbol,
3473    j_: Symbol,
3474    j__: Symbol,
3475    jn_: Symbol,
3476    k_: Symbol,
3477    k__: Symbol,
3478    l__: Symbol,
3479    m_: Symbol,
3480    mm_: Symbol,
3481    m1_: Symbol,
3482    m2_: Symbol,
3483    mn_: Symbol,
3484    mn2_: Symbol,
3485    n_: Symbol,
3486    n__: Symbol,
3487    n1_: Symbol,
3488    nn_: Symbol,
3489    n2_: Symbol,
3490    n3_: Symbol,
3491    non2_: Symbol,
3492    p_: Symbol,
3493    pm_: Symbol,
3494    pp__: Symbol,
3495    p2__: Symbol,
3496    p2x__: Symbol,
3497    p3__: Symbol,
3498    p4__: Symbol,
3499    p4x__: Symbol,
3500    p6__: Symbol,
3501    pn__: Symbol,
3502    pq_: Symbol,
3503    pq__: Symbol,
3504    polyx__: Symbol,
3505    pr__: Symbol,
3506    px_: Symbol,
3507    px__: Symbol,
3508    rgx__: Symbol,
3509    rfx__: Symbol,
3510    rn__: Symbol,
3511    qq_: Symbol,
3512    qr__: Symbol,
3513    q6_: Symbol,
3514    qn_: Symbol,
3515    qx_: Symbol,
3516    qx__: Symbol,
3517    q_: Symbol,
3518    q1_: Symbol,
3519    q2_: Symbol,
3520    r_: Symbol,
3521    r__: Symbol,
3522    rr_: Symbol,
3523    s_: Symbol,
3524    s__: Symbol,
3525    t_: Symbol,
3526    t__: Symbol,
3527    trig_: Symbol,
3528    u_: Symbol,
3529    u__: Symbol,
3530    v_: Symbol,
3531    v__: Symbol,
3532    w_: Symbol,
3533    w__: Symbol,
3534    x_: Symbol,
3535    y_: Symbol,
3536    y__: Symbol,
3537    z_: Symbol,
3538    z__: Symbol,
3539    inert_sin: Symbol,
3540    inert_cos: Symbol,
3541    inert_tan: Symbol,
3542    inert_cot: Symbol,
3543    inert_sec: Symbol,
3544    inert_csc: Symbol,
3545    sub1: Symbol,
3546    sub2: Symbol,
3547    sub3: Symbol,
3548    sub4: Symbol,
3549    sub5: Symbol,
3550    sub6: Symbol,
3551    sub7: Symbol,
3552    sub8: Symbol,
3553    elliptic_e: Symbol,
3554    elliptic_f: Symbol,
3555    elliptic_pi: Symbol,
3556    erfc: Symbol,
3557    erfi: Symbol,
3558    fresnel_s: Symbol,
3559    fresnel_c: Symbol,
3560    hypergeometric2f1: Symbol,
3561    hypergeometric_pfq: Symbol,
3562    appell_f1: Symbol,
3563    exp_integral_e: Symbol,
3564    exp_integral_ei: Symbol,
3565    log_integral: Symbol,
3566    sin_integral: Symbol,
3567    cos_integral: Symbol,
3568    sinh_integral: Symbol,
3569    cosh_integral: Symbol,
3570    product_log: Symbol,
3571    gamma: Symbol,
3572    log_gamma: Symbol,
3573    factorial: Symbol,
3574    unintegrable: Symbol,
3575    rootsum: Symbol,
3576    rootsum_z: Symbol,
3577    rubi_int: Symbol,
3578    rubi_deactivate_trig: Symbol,
3579    rubi_expand_integrand: Symbol,
3580    rubi_fix_inert_trig_function: Symbol,
3581    rubi_unify_inert_trig_function: Symbol,
3582}
3583
3584// Rule constructors are called once. Share the lazy-initialization check here
3585// without adding a function call to symbol accesses during integration.
3586#[inline(never)]
3587fn rubi_registration_symbols() -> &'static RubiSymbols {
3588    rubi_symbols()
3589}
3590
3591fn rubi_symbols() -> &'static RubiSymbols {
3592    static SYMBOLS: LazyLock<RubiSymbols> = LazyLock::new(|| RubiSymbols {
3593        capital_a_: symbol!("A_"),
3594        capital_a__: symbol!("A__"),
3595        capital_b_: symbol!("B_"),
3596        capital_b__: symbol!("B__"),
3597        capital_c_: symbol!("C_"),
3598        capital_c__: symbol!("C__"),
3599        capital_f_: symbol!("F_"),
3600        capital_f__: symbol!("F__"),
3601        capital_g_: symbol!("G_"),
3602        capital_h_: symbol!("H_"),
3603        afx__: symbol!("AFx__"),
3604        a_: symbol!("a_"),
3605        a__: symbol!("a__"),
3606        a1__: symbol!("a1__"),
3607        a2__: symbol!("a2__"),
3608        b__: symbol!("b__"),
3609        b1__: symbol!("b1__"),
3610        b2__: symbol!("b2__"),
3611        c_: symbol!("c_"),
3612        c__: symbol!("c__"),
3613        d_: symbol!("d_"),
3614        d__: symbol!("d__"),
3615        d1__: symbol!("d1__"),
3616        d2__: symbol!("d2__"),
3617        e__: symbol!("e__"),
3618        e1__: symbol!("e1__"),
3619        e2__: symbol!("e2__"),
3620        f_: symbol!("f_"),
3621        f__: symbol!("f__"),
3622        fx__: symbol!("Fx__"),
3623        f1__: symbol!("f1__"),
3624        f2__: symbol!("f2__"),
3625        g_: symbol!("g_"),
3626        g__: symbol!("g__"),
3627        g1__: symbol!("g1__"),
3628        g2__: symbol!("g2__"),
3629        h__: symbol!("h__"),
3630        i_: symbol!("i_"),
3631        i__: symbol!("i__"),
3632        j_: symbol!("j_"),
3633        j__: symbol!("j__"),
3634        jn_: symbol!("jn_"),
3635        k_: symbol!("k_"),
3636        k__: symbol!("k__"),
3637        l__: symbol!("l__"),
3638        m_: symbol!("m_"),
3639        mm_: symbol!("mm_"),
3640        m1_: symbol!("m1_"),
3641        m2_: symbol!("m2_"),
3642        mn_: symbol!("mn_"),
3643        mn2_: symbol!("mn2_"),
3644        n_: symbol!("n_"),
3645        n__: symbol!("n__"),
3646        n1_: symbol!("n1_"),
3647        nn_: symbol!("nn_"),
3648        n2_: symbol!("n2_"),
3649        n3_: symbol!("n3_"),
3650        non2_: symbol!("non2_"),
3651        p_: symbol!("p_"),
3652        pm_: symbol!("Pm_"),
3653        pp__: symbol!("Pp__"),
3654        p2__: symbol!("P2__"),
3655        p2x__: symbol!("P2x__"),
3656        p3__: symbol!("P3__"),
3657        p4__: symbol!("P4__"),
3658        p4x__: symbol!("P4x__"),
3659        p6__: symbol!("P6__"),
3660        pn__: symbol!("Pn__"),
3661        pq_: symbol!("Pq_"),
3662        pq__: symbol!("Pq__"),
3663        polyx__: symbol!("Polyx__"),
3664        pr__: symbol!("Pr__"),
3665        px_: symbol!("Px_"),
3666        px__: symbol!("Px__"),
3667        rgx__: symbol!("RGx__"),
3668        rfx__: symbol!("RFx__"),
3669        rn__: symbol!("Rn__"),
3670        qq_: symbol!("Qq_"),
3671        qr__: symbol!("Qr__"),
3672        q6_: symbol!("Q6_"),
3673        qn_: symbol!("Qn_"),
3674        qx_: symbol!("Qx_"),
3675        qx__: symbol!("Qx__"),
3676        q_: symbol!("q_"),
3677        q1_: symbol!("q1_"),
3678        q2_: symbol!("q2_"),
3679        r_: symbol!("r_"),
3680        r__: symbol!("r__"),
3681        rr_: symbol!("Rr_"),
3682        s_: symbol!("s_"),
3683        s__: symbol!("s__"),
3684        t_: symbol!("t_"),
3685        t__: symbol!("t__"),
3686        trig_: symbol!("trig_"),
3687        u_: symbol!("u_"),
3688        u__: symbol!("u__"),
3689        v_: symbol!("v_"),
3690        v__: symbol!("v__"),
3691        w_: symbol!("w_"),
3692        w__: symbol!("w__"),
3693        x_: symbol!("x_"),
3694        y_: symbol!("y_"),
3695        y__: symbol!("y__"),
3696        z_: symbol!("z_"),
3697        z__: symbol!("z__"),
3698        inert_sin: symbol!("rubi_sin"),
3699        inert_cos: symbol!("rubi_cos"),
3700        inert_tan: symbol!("rubi_tan"),
3701        inert_cot: symbol!("rubi_cot"),
3702        inert_sec: symbol!("rubi_sec"),
3703        inert_csc: symbol!("rubi_csc"),
3704        sub1: symbol!("sub1"),
3705        sub2: symbol!("sub2"),
3706        sub3: symbol!("sub3"),
3707        sub4: symbol!("sub4"),
3708        sub5: symbol!("sub5"),
3709        sub6: symbol!("sub6"),
3710        sub7: symbol!("sub7"),
3711        sub8: symbol!("sub8"),
3712        elliptic_e: symbol!(
3713            "elliptic_e",
3714            aliases = ["EllipticE"],
3715            norm = |_f, _out| {},
3716            der = |f, index, out| {
3717                if index != 0 {
3718                    return;
3719                }
3720                let f = f
3721                    .as_fun_view()
3722                    .expect("EllipticE derivative should receive a function");
3723                if f.get_nargs() != 2 {
3724                    return;
3725                }
3726                let phi = f.get(0).to_owned();
3727                let m = f.get(1).to_owned();
3728                **out = (Atom::num(1) - m * phi.sin().pow(2)).sqrt();
3729            }
3730        ),
3731        elliptic_f: symbol!(
3732            "elliptic_f",
3733            aliases = ["EllipticF"],
3734            norm = |_f, _out| {},
3735            der = |f, index, out| {
3736                if index != 0 {
3737                    return;
3738                }
3739                let f = f
3740                    .as_fun_view()
3741                    .expect("EllipticF derivative should receive a function");
3742                if f.get_nargs() != 2 {
3743                    return;
3744                }
3745                let phi = f.get(0).to_owned();
3746                let m = f.get(1).to_owned();
3747                **out = Atom::num(1) / (Atom::num(1) - m * phi.sin().pow(2)).sqrt();
3748            }
3749        ),
3750        elliptic_pi: symbol!(
3751            "elliptic_pi",
3752            aliases = ["EllipticPi"],
3753            norm = |_f, _out| {},
3754            der = |f, index, out| {
3755                if index != 1 {
3756                    return;
3757                }
3758                let f = f
3759                    .as_fun_view()
3760                    .expect("EllipticPi derivative should receive a function");
3761                if f.get_nargs() != 3 {
3762                    return;
3763                }
3764                let n = f.get(0).to_owned();
3765                let phi = f.get(1).to_owned();
3766                let m = f.get(2).to_owned();
3767                **out = Atom::num(1)
3768                    / ((Atom::num(1) - n * phi.sin().pow(2))
3769                        * (Atom::num(1) - m * phi.sin().pow(2)).sqrt());
3770            }
3771        ),
3772        erfc: symbol!("erfc", aliases = ["Erfc"]),
3773        erfi: symbol!(
3774            "erfi",
3775            aliases = ["Erfi"],
3776            norm = |_f, _out| {},
3777            der = |f, index, out| {
3778                if index != 0 {
3779                    return;
3780                }
3781                let f = f
3782                    .as_fun_view()
3783                    .expect("Erfi derivative should receive a function");
3784                if f.get_nargs() != 1 {
3785                    return;
3786                }
3787                let z = f.get(0).to_owned();
3788                **out = Atom::num(2) * z.pow(2).exp() / Atom::var(Symbol::PI).sqrt();
3789            }
3790        ),
3791        fresnel_s: symbol!(
3792            "fresnel_s",
3793            aliases = ["FresnelS"],
3794            norm = |_f, _out| {},
3795            der = |f, index, out| {
3796                if index != 0 {
3797                    return;
3798                }
3799                let f = f
3800                    .as_fun_view()
3801                    .expect("FresnelS derivative should receive a function");
3802                if f.get_nargs() != 1 {
3803                    return;
3804                }
3805                let z = f.get(0).to_owned();
3806                **out = (Atom::var(Symbol::PI) * z.pow(2) / 2).sin();
3807            }
3808        ),
3809        fresnel_c: symbol!(
3810            "fresnel_c",
3811            aliases = ["FresnelC"],
3812            norm = |_f, _out| {},
3813            der = |f, index, out| {
3814                if index != 0 {
3815                    return;
3816                }
3817                let f = f
3818                    .as_fun_view()
3819                    .expect("FresnelC derivative should receive a function");
3820                if f.get_nargs() != 1 {
3821                    return;
3822                }
3823                let z = f.get(0).to_owned();
3824                **out = (Atom::var(Symbol::PI) * z.pow(2) / 2).cos();
3825            }
3826        ),
3827        hypergeometric2f1: symbol!(
3828            "hypergeometric_2f1",
3829            aliases = ["Hypergeometric2F1"],
3830            norm = |f, out| {
3831                let f = f
3832                    .as_fun_view()
3833                    .expect("Hypergeometric2F1 normalization should receive a function");
3834                if f.get_nargs() != 4 {
3835                    return;
3836                }
3837
3838                let a = f.get(0).to_owned();
3839                let b = f.get(1).to_owned();
3840                let c = f.get(2).to_owned();
3841                let z = f.get(3).to_owned();
3842                let a_norm = a.expand().cancel();
3843                let b_norm = b.expand().cancel();
3844                let c_norm = c.expand().cancel();
3845                if a_norm.is_zero() || b_norm.is_zero() || z.is_zero() {
3846                    **out = Atom::num(1);
3847                } else if let Some(value) =
3848                    terminating_hypergeometric2f1(&a_norm, &b_norm, &c_norm, &z)
3849                {
3850                    **out = value;
3851                } else if let Some(value) =
3852                    terminating_hypergeometric2f1(&b_norm, &a_norm, &c_norm, &z)
3853                {
3854                    **out = value;
3855                } else if (&b_norm - &c_norm).expand().is_zero() {
3856                    **out = (Atom::num(1) - z).pow(-a_norm);
3857                } else if (&a_norm - &c_norm).expand().is_zero() {
3858                    **out = (Atom::num(1) - z).pow(-b_norm);
3859                } else if a_norm == Atom::num(1) / Atom::num(2)
3860                    && b_norm == Atom::num(1) / Atom::num(2)
3861                    && c_norm == Atom::num(3) / Atom::num(2)
3862                {
3863                    if let Some(sqrt_neg_z) = hypergeometric2f1_asinh_quadratic_argument(&z) {
3864                        **out = sqrt_neg_z.asinh() / sqrt_neg_z;
3865                    } else {
3866                        let sqrt_z =
3867                            hypergeometric2f1_atanh_linear_argument(&z).unwrap_or_else(|| z.sqrt());
3868                        **out = sqrt_z.atanh() / sqrt_z;
3869                    }
3870                } else if ((a_norm == Atom::num(1) && b_norm == Atom::num(1) / Atom::num(2))
3871                    || (a_norm == Atom::num(1) / Atom::num(2) && b_norm == Atom::num(1)))
3872                    && c_norm == Atom::num(3) / Atom::num(2)
3873                {
3874                    let sqrt_z =
3875                        hypergeometric2f1_atanh_linear_argument(&z).unwrap_or_else(|| z.sqrt());
3876                    **out = sqrt_z.atanh() / sqrt_z;
3877                } else if a_norm == Atom::num(2)
3878                    && (&c_norm - &b_norm - Atom::num(1)).expand().is_zero()
3879                {
3880                    **out = &b_norm / (&z * (Atom::num(1) - &z))
3881                        - &b_norm / &z
3882                            * f.get_symbol().call((
3883                                Atom::num(1),
3884                                b_norm - Atom::num(1),
3885                                c_norm - Atom::num(1),
3886                                z,
3887                            ));
3888                } else if ((a_norm == Atom::num(2) && b_norm == Atom::num(3) / Atom::num(2))
3889                    || (a_norm == Atom::num(3) / Atom::num(2) && b_norm == Atom::num(2)))
3890                    && c_norm == Atom::num(5) / Atom::num(2)
3891                {
3892                    let sqrt_z = z.sqrt();
3893                    **out = Atom::num(3) / (Atom::num(2) * &z * (Atom::num(1) - &z))
3894                        - Atom::num(3) * sqrt_z.atanh()
3895                            / (Atom::num(2) * z.pow(Atom::num(3) / Atom::num(2)));
3896                }
3897            },
3898            der = |f, index, out| {
3899                if index != 3 {
3900                    return;
3901                }
3902                let f = f
3903                    .as_fun_view()
3904                    .expect("Hypergeometric2F1 derivative should receive a function");
3905                let a = f.get(0).to_owned();
3906                let b = f.get(1).to_owned();
3907                let c = f.get(2).to_owned();
3908                let z = f.get(3).to_owned();
3909                **out = &a * &b / &c
3910                    * f.get_symbol().call((
3911                        a + Atom::num(1),
3912                        b + Atom::num(1),
3913                        c + Atom::num(1),
3914                        z,
3915                    ));
3916            }
3917        ),
3918        hypergeometric_pfq: symbol!("hypergeometric_pfq", aliases = ["HypergeometricPFQ"]),
3919        appell_f1: symbol!(
3920            "appell_f1",
3921            aliases = ["AppellF1"],
3922            norm = |_f, _out| {},
3923            der = |f, index, out| {
3924                if index != 4 && index != 5 {
3925                    return;
3926                }
3927                let f = f
3928                    .as_fun_view()
3929                    .expect("AppellF1 derivative should receive a function");
3930                if f.get_nargs() != 6 {
3931                    return;
3932                }
3933                let a = f.get(0).to_owned();
3934                let b1 = f.get(1).to_owned();
3935                let b2 = f.get(2).to_owned();
3936                let c = f.get(3).to_owned();
3937                let x = f.get(4).to_owned();
3938                let y = f.get(5).to_owned();
3939                if index == 4 {
3940                    **out = &a * &b1 / &c
3941                        * f.get_symbol().call((
3942                            a + Atom::num(1),
3943                            b1 + Atom::num(1),
3944                            b2,
3945                            c + Atom::num(1),
3946                            x,
3947                            y,
3948                        ));
3949                } else {
3950                    **out = &a * &b2 / &c
3951                        * f.get_symbol().call((
3952                            a + Atom::num(1),
3953                            b1,
3954                            b2 + Atom::num(1),
3955                            c + Atom::num(1),
3956                            x,
3957                            y,
3958                        ));
3959                }
3960            }
3961        ),
3962        exp_integral_e: symbol!(
3963            "exp_integral_e",
3964            aliases = ["ExpIntegralE"],
3965            norm = |f, out| {
3966                let f = f
3967                    .as_fun_view()
3968                    .expect("ExpIntegralE normalization should receive a function");
3969                if f.get_nargs() != 2 || !f.get(0).to_owned().is_zero() {
3970                    return;
3971                }
3972                let z = f.get(1).to_owned();
3973                **out = (-z.to_owned()).exp() / z;
3974            },
3975            der = |f, index, out| {
3976                if index != 1 {
3977                    return;
3978                }
3979                let f = f
3980                    .as_fun_view()
3981                    .expect("ExpIntegralE derivative should receive a function");
3982                if f.get_nargs() != 2 {
3983                    return;
3984                }
3985                let n = f.get(0).to_owned();
3986                let z = f.get(1).to_owned();
3987                **out = -f.get_symbol().call((n - Atom::num(1), z));
3988            }
3989        ),
3990        exp_integral_ei: symbol!(
3991            "exp_integral_ei",
3992            aliases = ["ExpIntegralEi"],
3993            norm = |_f, _out| {},
3994            der = |f, index, out| {
3995                if index != 0 {
3996                    return;
3997                }
3998                let f = f
3999                    .as_fun_view()
4000                    .expect("ExpIntegralEi derivative should receive a function");
4001                if f.get_nargs() != 1 {
4002                    return;
4003                }
4004                let z = f.get(0).to_owned();
4005                **out = z.exp() / z;
4006            }
4007        ),
4008        log_integral: symbol!(
4009            "log_integral",
4010            aliases = ["LogIntegral"],
4011            norm = |_f, _out| {},
4012            der = |f, index, out| {
4013                if index != 0 {
4014                    return;
4015                }
4016                let f = f
4017                    .as_fun_view()
4018                    .expect("LogIntegral derivative should receive a function");
4019                if f.get_nargs() != 1 {
4020                    return;
4021                }
4022                let z = f.get(0).to_owned();
4023                **out = Atom::num(1) / z.log();
4024            }
4025        ),
4026        sin_integral: symbol!(
4027            "sin_integral",
4028            aliases = ["SinIntegral"],
4029            norm = |_f, _out| {},
4030            der = |f, index, out| {
4031                if index == 0
4032                    && let Some(f) = f.as_fun_view()
4033                    && f.get_nargs() == 1
4034                {
4035                    let z = f.get(0).to_owned();
4036                    **out = z.sin() / z;
4037                }
4038            }
4039        ),
4040        cos_integral: symbol!(
4041            "cos_integral",
4042            aliases = ["CosIntegral"],
4043            norm = |_f, _out| {},
4044            der = |f, index, out| {
4045                if index == 0
4046                    && let Some(f) = f.as_fun_view()
4047                    && f.get_nargs() == 1
4048                {
4049                    let z = f.get(0).to_owned();
4050                    **out = z.cos() / z;
4051                }
4052            }
4053        ),
4054        sinh_integral: symbol!(
4055            "sinh_integral",
4056            aliases = ["SinhIntegral"],
4057            norm = |_f, _out| {},
4058            der = |f, index, out| {
4059                if index == 0
4060                    && let Some(f) = f.as_fun_view()
4061                    && f.get_nargs() == 1
4062                {
4063                    let z = f.get(0).to_owned();
4064                    **out = z.sinh() / z;
4065                }
4066            }
4067        ),
4068        cosh_integral: symbol!(
4069            "cosh_integral",
4070            aliases = ["CoshIntegral"],
4071            norm = |_f, _out| {},
4072            der = |f, index, out| {
4073                if index == 0
4074                    && let Some(f) = f.as_fun_view()
4075                    && f.get_nargs() == 1
4076                {
4077                    let z = f.get(0).to_owned();
4078                    **out = z.cosh() / z;
4079                }
4080            }
4081        ),
4082        product_log: symbol!(
4083            "product_log",
4084            aliases = ["ProductLog"],
4085            norm = |_f, _out| {},
4086            der = |f, index, out| {
4087                if index != 0 {
4088                    return;
4089                }
4090                let f = f
4091                    .as_fun_view()
4092                    .expect("ProductLog derivative should receive a function");
4093                if f.get_nargs() != 1 {
4094                    return;
4095                }
4096                let z = f.get(0).to_owned();
4097                let product_log = f.get_symbol().call((z.to_owned(),));
4098                **out = product_log.to_owned() / (z * (Atom::num(1) + product_log));
4099            }
4100        ),
4101        gamma: symbol!(
4102            "rubi_gamma",
4103            aliases = ["Gamma"],
4104            norm = |f, out| {
4105                if let Some(f) = f.as_fun_view()
4106                    && f.get_nargs() == 2
4107                    && f.get(0).to_owned().is_one()
4108                {
4109                    **out = (-f.get(1).to_owned()).exp();
4110                }
4111            },
4112            der = |f, index, out| {
4113                let Some(f) = f.as_fun_view() else {
4114                    return;
4115                };
4116                if f.get_nargs() == 1 && index == 0 {
4117                    let z = f.get(0).to_owned();
4118                    **out = f.get_symbol().call((z.to_owned(),)) * z.polygamma(Atom::num(0));
4119                } else if f.get_nargs() == 2 && index == 1 {
4120                    let a = f.get(0).to_owned();
4121                    let z = f.get(1).to_owned();
4122                    **out = -z.pow(a - Atom::num(1)) * (-z).exp();
4123                }
4124            }
4125        ),
4126        log_gamma: symbol!(
4127            "log_gamma",
4128            aliases = ["LogGamma"],
4129            norm = |_f, _out| {},
4130            der = |f, index, out| {
4131                if index != 0 {
4132                    return;
4133                }
4134                let f = f
4135                    .as_fun_view()
4136                    .expect("LogGamma derivative should receive a function");
4137                if f.get_nargs() != 1 {
4138                    return;
4139                }
4140                let z = f.get(0).to_owned();
4141                **out = z.polygamma(Atom::num(0));
4142            }
4143        ),
4144        factorial: symbol!("Factorial"),
4145        unintegrable: symbol!(
4146            "unintegrable",
4147            aliases = ["Unintegrable"],
4148            norm = |_f, _out| {},
4149            der = |_f, _index, _out| {}
4150        ),
4151        rootsum: symbol!("rootsum"),
4152        rootsum_z: symbol!("z"),
4153        rubi_int: symbol!(
4154            "rubi_int",
4155            print = |atom, options, state| {
4156                let AtomView::Fun(function) = atom else {
4157                    return None;
4158                };
4159                if function.get_nargs() != 2 {
4160                    return None;
4161                }
4162
4163                let (prefix, differential) = if options.mode.is_symbolica() {
4164                    ("∫ ", " d")
4165                } else if options.mode.is_latex() {
4166                    ("\\int ", "\\,\\mathrm{d}")
4167                } else if options.mode.is_typst() {
4168                    ("integral ", " dif ")
4169                } else {
4170                    return None;
4171                };
4172
4173                let mut output = String::new();
4174
4175                let parenthesize = state.in_product || state.in_exp || state.in_exp_base;
4176                let mut state = state.clone();
4177
4178                if parenthesize {
4179                    AtomPrinter::format_bracket('(', &mut output, options, state).ok()?;
4180                    state.bracket_level += 1;
4181                }
4182
4183                output.push_str(prefix);
4184                function
4185                    .get(0)
4186                    .format(&mut output, options, state.step(false, false, false, false))
4187                    .ok()?;
4188                output.push_str(differential);
4189                function
4190                    .get(1)
4191                    .format(&mut output, options, state.step(false, false, false, false))
4192                    .ok()?;
4193
4194                if parenthesize {
4195                    state.bracket_level -= 1;
4196                    AtomPrinter::format_bracket(')', &mut output, options, state).ok()?;
4197                }
4198
4199                Some(output)
4200            }
4201        ),
4202        rubi_deactivate_trig: symbol!("rubi_deactivate_trig"),
4203        rubi_expand_integrand: symbol!("rubi_expand_integrand"),
4204        rubi_fix_inert_trig_function: symbol!("rubi_fix_inert_trig_function"),
4205        rubi_unify_inert_trig_function: symbol!("rubi_unify_inert_trig_function"),
4206    });
4207    &SYMBOLS
4208}
4209
4210fn rubi_hypergeometric2f1(
4211    a: impl symbolica::atom::FunctionArgument,
4212    b: impl symbolica::atom::FunctionArgument,
4213    c: impl symbolica::atom::FunctionArgument,
4214    z: impl symbolica::atom::FunctionArgument,
4215) -> Atom {
4216    rubi_symbols().hypergeometric2f1.call((a, b, c, z))
4217}
4218
4219fn hypergeometric2f1_atanh_linear_argument(z: &Atom) -> Option<Atom> {
4220    let mut candidates = Vec::new();
4221    for symbol in z.get_all_symbols(false) {
4222        let variable = Atom::var(symbol);
4223        let coefficient = rubi_simplify(&(z / variable.pow(2)));
4224        if is_free_of(&coefficient, symbol) {
4225            candidates.push(coefficient.sqrt() * variable);
4226        }
4227    }
4228
4229    match candidates.as_slice() {
4230        [candidate] => Some(candidate.to_owned()),
4231        _ => None,
4232    }
4233}
4234
4235fn hypergeometric2f1_asinh_quadratic_argument(z: &Atom) -> Option<Atom> {
4236    let mut candidates = Vec::new();
4237    for symbol in z.get_all_symbols(false) {
4238        let variable = Atom::var(symbol);
4239        let coefficient = rubi_simplify(&(z / variable.pow(2)));
4240        if is_free_of(&coefficient, symbol) && rubi_negative_form_q(&coefficient) {
4241            candidates.push((-coefficient).sqrt() * variable);
4242        }
4243    }
4244
4245    match candidates.as_slice() {
4246        [candidate] => Some(candidate.to_owned()),
4247        _ => None,
4248    }
4249}
4250
4251fn terminating_hypergeometric2f1(a: &Atom, b: &Atom, c: &Atom, z: &Atom) -> Option<Atom> {
4252    let degree = -integer_i64(a)?;
4253    if degree <= 0 {
4254        return None;
4255    }
4256
4257    let mut term = Atom::num(1);
4258    let mut sum = Atom::num(1);
4259    for k in 1..=degree {
4260        let shift = Atom::num(k - 1);
4261        term *= (a + &shift) * (b + &shift) * z / ((c + shift) * Atom::num(k));
4262        sum += &term;
4263    }
4264
4265    Some(sum.expand().cancel())
4266}
4267
4268fn rubi_appell_f1(
4269    a: impl symbolica::atom::FunctionArgument,
4270    b1: impl symbolica::atom::FunctionArgument,
4271    b2: impl symbolica::atom::FunctionArgument,
4272    c: impl symbolica::atom::FunctionArgument,
4273    x: impl symbolica::atom::FunctionArgument,
4274    y: impl symbolica::atom::FunctionArgument,
4275) -> Atom {
4276    rubi_symbols().appell_f1.call((a, b1, b2, c, x, y))
4277}
4278
4279#[inline(never)]
4280fn rubi_erfi(z: impl symbolica::atom::FunctionArgument) -> Atom {
4281    rubi_symbols().erfi.call((z,))
4282}
4283
4284fn rubi_erf(z: impl RubiAtomArgument) -> Atom {
4285    z.into_rubi_atom().erf()
4286}
4287
4288#[inline(never)]
4289fn rubi_erfc(z: impl symbolica::atom::FunctionArgument) -> Atom {
4290    rubi_symbols().erfc.call((z,))
4291}
4292
4293#[inline(never)]
4294fn rubi_fresnel_s(z: impl symbolica::atom::FunctionArgument) -> Atom {
4295    rubi_symbols().fresnel_s.call((z,))
4296}
4297
4298#[inline(never)]
4299fn rubi_fresnel_c(z: impl symbolica::atom::FunctionArgument) -> Atom {
4300    rubi_symbols().fresnel_c.call((z,))
4301}
4302
4303fn rubi_exp_integral_e(
4304    n: impl symbolica::atom::FunctionArgument,
4305    z: impl symbolica::atom::FunctionArgument,
4306) -> Atom {
4307    rubi_symbols().exp_integral_e.call((n, z))
4308}
4309
4310#[inline(never)]
4311fn rubi_exp_integral_ei(z: impl symbolica::atom::FunctionArgument) -> Atom {
4312    rubi_symbols().exp_integral_ei.call((z,))
4313}
4314
4315#[inline(never)]
4316fn rubi_log_integral(z: impl symbolica::atom::FunctionArgument) -> Atom {
4317    rubi_symbols().log_integral.call((z,))
4318}
4319
4320fn rubi_zeta(
4321    s: impl symbolica::atom::FunctionArgument,
4322    z: impl symbolica::atom::FunctionArgument,
4323) -> Atom {
4324    symbolica::transcendental::zeta().call((s, z))
4325}
4326
4327#[inline(never)]
4328fn rubi_sin_integral(z: impl symbolica::atom::FunctionArgument) -> Atom {
4329    rubi_symbols().sin_integral.call((z,))
4330}
4331
4332#[inline(never)]
4333fn rubi_cos_integral(z: impl symbolica::atom::FunctionArgument) -> Atom {
4334    rubi_symbols().cos_integral.call((z,))
4335}
4336
4337#[inline(never)]
4338fn rubi_sinh_integral(z: impl symbolica::atom::FunctionArgument) -> Atom {
4339    rubi_symbols().sinh_integral.call((z,))
4340}
4341
4342#[inline(never)]
4343fn rubi_cosh_integral(z: impl symbolica::atom::FunctionArgument) -> Atom {
4344    rubi_symbols().cosh_integral.call((z,))
4345}
4346
4347#[inline(never)]
4348fn rubi_product_log(z: impl RubiAtomArgument) -> Atom {
4349    rubi_symbols().product_log.call((z.into_rubi_atom(),))
4350}
4351
4352fn rubi_gamma(
4353    a: impl symbolica::atom::FunctionArgument,
4354    z: impl symbolica::atom::FunctionArgument,
4355) -> Atom {
4356    rubi_symbols().gamma.call((a, z))
4357}
4358
4359fn rubi_gamma_unary(z: impl symbolica::atom::FunctionArgument) -> Atom {
4360    rubi_symbols().gamma.call((z,))
4361}
4362
4363fn rubi_log_gamma(z: impl symbolica::atom::FunctionArgument) -> Atom {
4364    rubi_symbols().log_gamma.call((z,))
4365}
4366
4367fn rubi_factorial(z: impl symbolica::atom::FunctionArgument) -> Atom {
4368    rubi_symbols().factorial.call((z,))
4369}
4370
4371fn rubi_hypergeometric_pfq_2_2(
4372    a1: impl symbolica::atom::FunctionArgument,
4373    a2: impl symbolica::atom::FunctionArgument,
4374    b1: impl symbolica::atom::FunctionArgument,
4375    b2: impl symbolica::atom::FunctionArgument,
4376    z: impl symbolica::atom::FunctionArgument,
4377) -> Atom {
4378    rubi_symbols().hypergeometric_pfq.call((a1, a2, b1, b2, z))
4379}
4380
4381fn rubi_hypergeometric_pfq_3_2(
4382    a1: impl symbolica::atom::FunctionArgument,
4383    a2: impl symbolica::atom::FunctionArgument,
4384    a3: impl symbolica::atom::FunctionArgument,
4385    b1: impl symbolica::atom::FunctionArgument,
4386    b2: impl symbolica::atom::FunctionArgument,
4387    z: impl symbolica::atom::FunctionArgument,
4388) -> Atom {
4389    rubi_symbols()
4390        .hypergeometric_pfq
4391        .call((a1, a2, a3, b1, b2, z))
4392}
4393
4394fn rubi_hypergeometric_pfq_3_3(
4395    a1: impl symbolica::atom::FunctionArgument,
4396    a2: impl symbolica::atom::FunctionArgument,
4397    a3: impl symbolica::atom::FunctionArgument,
4398    b1: impl symbolica::atom::FunctionArgument,
4399    b2: impl symbolica::atom::FunctionArgument,
4400    b3: impl symbolica::atom::FunctionArgument,
4401    z: impl symbolica::atom::FunctionArgument,
4402) -> Atom {
4403    rubi_symbols()
4404        .hypergeometric_pfq
4405        .call((a1, a2, a3, b1, b2, b3, z))
4406}
4407
4408#[inline(never)]
4409fn rubi_elliptic_e(
4410    phi: impl symbolica::atom::FunctionArgument,
4411    m: impl symbolica::atom::FunctionArgument,
4412) -> Atom {
4413    rubi_symbols().elliptic_e.call((phi, m))
4414}
4415
4416#[inline(never)]
4417fn rubi_elliptic_f(
4418    phi: impl symbolica::atom::FunctionArgument,
4419    m: impl symbolica::atom::FunctionArgument,
4420) -> Atom {
4421    rubi_symbols().elliptic_f.call((phi, m))
4422}
4423
4424fn rubi_elliptic_pi(
4425    n: impl symbolica::atom::FunctionArgument,
4426    phi: impl symbolica::atom::FunctionArgument,
4427    m: impl symbolica::atom::FunctionArgument,
4428) -> Atom {
4429    rubi_symbols().elliptic_pi.call((n, phi, m))
4430}
4431
4432fn rubi_sign(expr: impl symbolica::atom::FunctionArgument) -> Atom {
4433    symbol!("Sign").call((expr,))
4434}
4435
4436fn rubi_unintegrable(expr: Atom, x: Symbol) -> Atom {
4437    rubi_symbols().unintegrable.call((expr, Atom::var(x)))
4438}
4439
4440fn rubi_contains_unintegrable(expr: &Atom) -> bool {
4441    let unintegrable = rubi_symbols().unintegrable;
4442    let mut contains_unintegrable = false;
4443    expr.visitor(&mut |atom| {
4444        contains_unintegrable |=
4445            matches!(atom, AtomView::Fun(function) if function.get_symbol() == unintegrable);
4446        !contains_unintegrable
4447    });
4448    contains_unintegrable
4449}
4450
4451fn rubi_i() -> Atom {
4452    Atom::num(Complex::new(Rational::zero(), Rational::one()))
4453}
4454
4455fn rubi_exp_i_pi_multiple(multiple: &Atom) -> Atom {
4456    if let Some(twice_multiple) = integer_i64(&(Atom::num(2) * multiple)) {
4457        return match twice_multiple.rem_euclid(4) {
4458            0 => Atom::num(1),
4459            1 => rubi_i(),
4460            2 => -Atom::num(1),
4461            3 => -rubi_i(),
4462            _ => unreachable!("rem_euclid(4) is in 0..4"),
4463        };
4464    }
4465
4466    (rubi_i() * Atom::var(Symbol::PI) * multiple).exp()
4467}
4468
4469fn rubi_exp_two_i_pi_multiple(multiple: &Atom) -> Atom {
4470    rubi_exp_i_pi_multiple(&(Atom::num(2) * multiple))
4471}
4472
4473fn rubi_complex_free_q<T: AtomCore>(expr: T) -> bool {
4474    let expr = expr.as_atom_view();
4475    match expr {
4476        AtomView::Num(number) => number.get_coeff_view().is_real(),
4477        AtomView::Var(_) => true,
4478        AtomView::Fun(function) => function.into_iter().all(rubi_complex_free_q),
4479        AtomView::Add(add) => add.into_iter().all(rubi_complex_free_q),
4480        AtomView::Mul(mul) => mul.into_iter().all(rubi_complex_free_q),
4481        AtomView::Pow(power) => {
4482            rubi_complex_free_q(power.get_base()) && rubi_complex_free_q(power.get_exp())
4483        }
4484    }
4485}
4486
4487fn starts_with_opaque_rubi_function(expr: AtomView<'_>) -> bool {
4488    if let AtomView::Fun(function) = expr {
4489        let s = function.get_symbol();
4490        let rubi_symbols = rubi_symbols();
4491        s == rubi_symbols.hypergeometric2f1
4492            || s == rubi_symbols.hypergeometric_pfq
4493            || s == rubi_symbols.elliptic_e
4494            || s == rubi_symbols.elliptic_f
4495            || s == rubi_symbols.elliptic_pi
4496            || s == rubi_symbols.erfc
4497            || s == rubi_symbols.erfi
4498            || s == rubi_symbols.fresnel_s
4499            || s == rubi_symbols.fresnel_c
4500            || s == rubi_symbols.appell_f1
4501            || s == rubi_symbols.exp_integral_e
4502            || s == rubi_symbols.exp_integral_ei
4503            || s == rubi_symbols.log_integral
4504            || s == symbolica::transcendental::zeta()
4505            || s == rubi_symbols.sin_integral
4506            || s == rubi_symbols.cos_integral
4507            || s == rubi_symbols.sinh_integral
4508            || s == rubi_symbols.cosh_integral
4509            || s == rubi_symbols.product_log
4510            || s == rubi_symbols.gamma
4511            || s == rubi_symbols.log_gamma
4512    } else {
4513        false
4514    }
4515}
4516
4517#[allow(non_snake_case)]
4518fn rubi_rules() -> &'static [RubiRule] {
4519    static RULES: LazyLock<Vec<RubiRule>> = LazyLock::new(|| {
4520        let mut rules = Vec::new();
4521        rules::push_rules(&mut rules);
4522        // Sorting must never silently fall back to module insertion order.
4523        // Extensions without an upstream DownValue number must explicitly
4524        // anchor themselves with `dispatch_before`.
4525        for rule in &rules {
4526            required_rubi_dispatch_order(rule);
4527        }
4528        rules.sort_by_key(required_rubi_dispatch_order);
4529        rules
4530    });
4531    RULES.as_slice()
4532}
4533
4534#[inline(never)]
4535fn sort_rubi_helper_rules(rules: &mut [RubiRule]) {
4536    rules.sort_by_key(|rule| rule.downvalue_order);
4537}
4538
4539#[allow(non_snake_case)]
4540fn rubi_expand_integrand_rules() -> &'static [RubiRule] {
4541    static RULES: LazyLock<Vec<RubiRule>> = LazyLock::new(|| {
4542        let mut rules = Vec::new();
4543        rules::push_expand_integrand_rules(&mut rules);
4544        sort_rubi_helper_rules(&mut rules);
4545        rules
4546    });
4547    RULES.as_slice()
4548}
4549
4550#[allow(non_snake_case)]
4551fn rubi_deactivate_trig_rules() -> &'static [RubiRule] {
4552    static RULES: LazyLock<Vec<RubiRule>> = LazyLock::new(|| {
4553        let mut rules = Vec::new();
4554        push_deactivate_trig_rules(&mut rules);
4555        sort_rubi_helper_rules(&mut rules);
4556        rules
4557    });
4558    RULES.as_slice()
4559}
4560
4561#[allow(non_snake_case)]
4562fn rubi_fix_inert_trig_function_rules() -> &'static [RubiRule] {
4563    static RULES: LazyLock<Vec<RubiRule>> = LazyLock::new(|| {
4564        let mut rules = Vec::new();
4565        rules::push_fix_inert_trig_function_rules(&mut rules);
4566        sort_rubi_helper_rules(&mut rules);
4567        rules
4568    });
4569    RULES.as_slice()
4570}
4571
4572#[allow(non_snake_case)]
4573fn rubi_unify_inert_trig_function_rules() -> &'static [RubiRule] {
4574    static RULES: LazyLock<Vec<RubiRule>> = LazyLock::new(|| {
4575        let mut rules = Vec::new();
4576        rules::push_unify_inert_trig_function_rules(&mut rules);
4577        sort_rubi_helper_rules(&mut rules);
4578        rules
4579    });
4580    RULES.as_slice()
4581}
4582
4583#[allow(non_snake_case)]
4584#[inline(never)]
4585fn push_deactivate_trig_rules(rules: &mut Vec<RubiRule>) {
4586    let symbols = rubi_symbols();
4587    let a__ = symbols.a__;
4588    let b__ = symbols.b__;
4589    let c__ = symbols.c__;
4590    let d__ = symbols.d__;
4591    let e__ = symbols.e__;
4592    let f__ = symbols.f__;
4593    let m_ = symbols.m_;
4594    let n_ = symbols.n_;
4595    let trig_ = symbols.trig_;
4596    let x_ = symbols.x_;
4597    let head = symbols.rubi_deactivate_trig;
4598
4599    rules.push_rubi_rule(rubi_helper_row!(
4600        order: 1,
4601        source: "DeactivateTrig[(c_.+d_.*x_)^m_.*(a_.+b_.*trig_[e_.+f_.*x_])^n_.,x_]",
4602        pattern: (c__ + d__ * x_).pow(m_) * (a__ + b__ * trig_.call(e__ + f__ * x_)).pow(n_),
4603        head: head,
4604        with: [c__, d__, m_, a__, b__, trig_, e__, f__, n_, x_],
4605        optional: [c__, d__, m_, a__, b__, e__, f__, n_],
4606        when: {
4607            freeq!([a__, b__, c__, d__, e__, f__, m_, n_], x_)
4608                && rubi_trig_or_hyperbolic_q(&trig_)
4609        },
4610        rhs: {
4611            let AtomView::Var(trig_symbol) = trig_.as_view() else {
4612                return None;
4613            };
4614            let trig_symbol = trig_symbol.get_symbol();
4615            let argument = &e__ + &f__ * x_;
4616            (&c__ + &d__ * x_).pow(&m_)
4617                    * (&a__ + &b__ * rubi_deactivate_trig(&trig_symbol.call((argument,)), x_)).pow(&n_)
4618        },
4619    ));
4620}
4621
4622#[allow(non_snake_case)]
4623fn rubi_rule_with_optional_action(
4624    #[cfg(any(test, feature = "trace"))] id: &'static str,
4625    #[cfg(not(any(test, feature = "trace")))] id: (),
4626    integrand_pattern: Atom,
4627    required: &[Symbol],
4628    rubi_int: Symbol,
4629    optional: &[Symbol],
4630    condition: RubiCondition,
4631    action: RubiAction,
4632) -> RubiRule {
4633    #[cfg(not(any(test, feature = "trace")))]
4634    let _ = id;
4635
4636    let explicit_x_factor_bound =
4637        rubi_explicit_pattern_x_factor_bound(&integrand_pattern, required);
4638    let require_explicit_variable_power_factor =
4639        rubi_has_explicit_variable_power_factor(integrand_pattern.as_view(), rubi_symbols().x_);
4640    let required_explicit_power_exponents =
4641        rubi_required_explicit_power_exponents(&integrand_pattern, required, optional);
4642    let required_function_heads = rubi_literal_function_heads(&integrand_pattern, required);
4643    let can_match_top_level_sum =
4644        rubi_pattern_can_match_top_level_sum(&integrand_pattern, optional);
4645    let max_top_level_term_count =
4646        rubi_pattern_max_top_level_term_count(&integrand_pattern, optional);
4647    let max_top_level_factor_count = rubi_pattern_max_top_level_factor_count(&integrand_pattern);
4648    let mut pattern = rubi_int
4649        .call((integrand_pattern, Atom::var(rubi_symbols().x_)))
4650        .to_pattern();
4651    for wildcard in optional {
4652        pattern = pattern.set_optional(*wildcard);
4653    }
4654    let replacement = pattern
4655        .replace_with(Atom::num(0).to_pattern())
4656        .partial(false)
4657        .max_level(0)
4658        .when(Condition::match_stack(rubi_replacement_condition));
4659
4660    RubiRule {
4661        #[cfg(any(test, feature = "trace"))]
4662        id,
4663        #[cfg(any(test, feature = "trace"))]
4664        block: None,
4665        downvalue_order: None,
4666        dispatch_order: None,
4667        #[cfg(any(test, feature = "steps"))]
4668        source_pattern: None,
4669        #[cfg(feature = "steps")]
4670        description: None,
4671        #[cfg(feature = "steps")]
4672        references: &[],
4673        replacement,
4674        required: required.to_vec(),
4675        required_function_heads,
4676        can_match_top_level_sum,
4677        max_top_level_term_count,
4678        max_top_level_factor_count,
4679        early_x_dependent: Vec::new(),
4680        early_x_free: Vec::new(),
4681        early_x_linear: Vec::new(),
4682        early_not_integration_variable: Vec::new(),
4683        require_repeated_proper_x_dependent_subexpression: false,
4684        early_numeric_bounds: Vec::new(),
4685        early_positive_integer_or_integer_pairs: Vec::new(),
4686        early_scaled_equal: Vec::new(),
4687        early_proportional_affine: Vec::new(),
4688        require_proportional_affine_factor_pair: false,
4689        require_proportional_common_expression_factor_pair: false,
4690        early_polynomial_derivative_pairs: Vec::new(),
4691        early_zero: Vec::new(),
4692        require_algebraic_zero_x_free_additive_part: false,
4693        max_zero_x_free_additive_term_count: None,
4694        require_proportional_binomial_base_pair: false,
4695        require_opposite_binomial_base_pair: false,
4696        require_negated_binomial_exponent_pair: false,
4697        required_common_binomial_exponent_factor_count: 0,
4698        required_common_positive_integer_binomial_factor_count: 0,
4699        required_common_polynomial_base_degree_count: 0,
4700        required_noninteger_power_factor_count: 0,
4701        require_even_quadratic_binomial_base: false,
4702        require_perfect_square_quadratic_base: false,
4703        require_half_integer_affine_power: false,
4704        require_positive_integer_affine_power: false,
4705        require_rational_noninteger_affine_power_below_negative_one: false,
4706        require_negative_scaled_affine_and_distinct_noninteger_affine: false,
4707        require_noninteger_affine_exponent_with_positive_difference: false,
4708        require_x_dependent_exponent_for_x_dependent_candidate: false,
4709        require_polynomial_complement_of_affine_power: false,
4710        required_noninteger_affine_power_count: 0,
4711        require_explicit_variable_power_factor,
4712        required_explicit_power_exponents,
4713        explicit_x_factor_bound,
4714        condition,
4715        action,
4716    }
4717}
4718
4719fn matcher_rule_target(target: &Atom, x: Symbol, rule: &'static RubiRule) -> Option<Atom> {
4720    #[cfg(feature = "bake-integration-variable")]
4721    {
4722        let pattern = rubi_pattern_with_integration_variable(&rule.replacement.pat, x);
4723        matcher_rule_target_with_replacement(target, x, rule, &rule.replacement, &pattern)
4724    }
4725    #[cfg(not(feature = "bake-integration-variable"))]
4726    matcher_rule_target_with_replacement(target, x, rule, &rule.replacement, &rule.replacement.pat)
4727}
4728
4729#[cfg(feature = "bake-integration-variable")]
4730fn rubi_pattern_with_integration_variable(pattern: &Pattern, x: Symbol) -> Pattern {
4731    let integration_wildcard = rubi_symbols().x_;
4732    match pattern {
4733        Pattern::Literal(atom) => Pattern::Literal(atom.to_owned()),
4734        Pattern::Wildcard(wildcard, _) if *wildcard == integration_wildcard => {
4735            Pattern::Literal(Atom::var(x))
4736        }
4737        Pattern::Wildcard(wildcard, optional) => Pattern::Wildcard(*wildcard, *optional),
4738        Pattern::Fn(head, arguments) => Pattern::Fn(
4739            *head,
4740            arguments
4741                .iter()
4742                .map(|argument| rubi_pattern_with_integration_variable(argument, x))
4743                .collect(),
4744        ),
4745        Pattern::Pow(arguments) => Pattern::Pow(Box::new([
4746            rubi_pattern_with_integration_variable(&arguments[0], x),
4747            rubi_pattern_with_integration_variable(&arguments[1], x),
4748        ])),
4749        Pattern::Mul(arguments) => Pattern::Mul(
4750            arguments
4751                .iter()
4752                .map(|argument| rubi_pattern_with_integration_variable(argument, x))
4753                .collect(),
4754        ),
4755        Pattern::Add(arguments) => Pattern::Add(
4756            arguments
4757                .iter()
4758                .map(|argument| rubi_pattern_with_integration_variable(argument, x))
4759                .collect(),
4760        ),
4761        Pattern::Alternative(alternatives) => Pattern::Alternative(
4762            alternatives
4763                .iter()
4764                .map(|alternative| rubi_pattern_with_integration_variable(alternative, x))
4765                .collect(),
4766        ),
4767        Pattern::Transformer(transformer) => Pattern::Transformer(transformer.to_owned()),
4768    }
4769}
4770
4771fn matcher_rule_target_with_replacement(
4772    target: &Atom,
4773    x: Symbol,
4774    rule: &'static RubiRule,
4775    replacement: &Replacement,
4776    pattern: &Pattern,
4777) -> Option<Atom> {
4778    #[cfg(feature = "trace")]
4779    let trace_phases = RUBI_SETTINGS
4780        .trace_rule_phase_timings
4781        .load(AtomicOrdering::Relaxed);
4782    #[cfg(feature = "trace")]
4783    let phase_threshold = RUBI_SETTINGS
4784        .trace_rule_phase_timing_ms
4785        .load(AtomicOrdering::Relaxed);
4786    #[cfg(feature = "trace")]
4787    let trace_phase = |phase: &str, start: Option<std::time::Instant>, outcome: &str| {
4788        let Some(start) = start else {
4789            return;
4790        };
4791        let elapsed = start.elapsed();
4792        if elapsed < std::time::Duration::from_millis(phase_threshold) {
4793            return;
4794        }
4795        if let Some(order) = rule.downvalue_order {
4796            eprintln!("phase {phase} order {order} {outcome} {elapsed:?}");
4797        } else {
4798            eprintln!(
4799                "phase {phase} unordered {} {outcome} {elapsed:?}",
4800                rule.id.lines().next().unwrap_or_default()
4801            );
4802        }
4803    };
4804
4805    #[cfg(feature = "trace")]
4806    let matcher_start = trace_phases.then(std::time::Instant::now);
4807    let mut matches = target.pattern_match(
4808        pattern,
4809        replacement.conditions.as_ref(),
4810        Some(&replacement.match_settings),
4811    );
4812    #[cfg(feature = "trace")]
4813    trace_phase("matcher", matcher_start, "created");
4814
4815    loop {
4816        #[cfg(feature = "trace")]
4817        let next_start = trace_phases.then(std::time::Instant::now);
4818        let Some(matched) = matches.next_detailed() else {
4819            #[cfg(feature = "trace")]
4820            trace_phase("pattern", next_start, "rejected");
4821            break;
4822        };
4823        #[cfg(feature = "trace")]
4824        trace_phase("pattern", next_start, "matched");
4825
4826        // `rubi_replacement_condition` is installed on the replacement and
4827        // Symbolica only yields complete matches for which it returned True.
4828        // Rechecking here would evaluate every Rubi guard twice; in particular,
4829        // loaded `With` guards such as ExpandIntegrand can be substantial.
4830        #[cfg(feature = "trace")]
4831        if RUBI_SETTINGS.trace_accepted.load(AtomicOrdering::Relaxed)
4832            && rubi_trace_rule_matches(rule)
4833        {
4834            match (rule.block, rule.downvalue_order) {
4835                (Some(block), Some(order)) => {
4836                    eprintln!("! order {order} {} block {block}", rule.id)
4837                }
4838                (Some(block), None) => eprintln!("! {} block {block}", rule.id),
4839                (None, Some(order)) => eprintln!("! order {order} {}", rule.id),
4840                (None, None) => eprintln!("! {}", rule.id),
4841            }
4842            if RUBI_SETTINGS
4843                .trace_accepted_inputs
4844                .load(AtomicOrdering::Relaxed)
4845            {
4846                eprintln!("! target {target}");
4847            }
4848        }
4849        #[cfg(feature = "trace")]
4850        let rhs_start = trace_phases.then(std::time::Instant::now);
4851        #[cfg(feature = "steps")]
4852        let primitive = if RUBI_STEPS_ACTIVE.with(Cell::get) {
4853            let explanation_checkpoint =
4854                begin_explanation_step(rule, x, || match target.as_view() {
4855                    AtomView::Fun(function) => function
4856                        .into_iter()
4857                        .next()
4858                        .expect("a Rubi rule target has an integrand argument")
4859                        .to_owned(),
4860                    _ => unreachable!("a Rubi rule target is a function call"),
4861                });
4862            let immediate_output = explanation_checkpoint
4863                .is_some()
4864                .then(|| capture_rule_rhs(rule, matched.match_stack, x))
4865                .flatten();
4866            let explanation_depth = explanation_checkpoint.map(|_| RubiStepDepth::push());
4867            let primitive = rule.apply(matched.match_stack, x);
4868            drop(explanation_depth);
4869            finish_explanation_step(
4870                explanation_checkpoint,
4871                immediate_output.as_ref(),
4872                primitive.as_ref(),
4873            );
4874            primitive
4875        } else {
4876            rule.apply(matched.match_stack, x)
4877        };
4878        #[cfg(not(feature = "steps"))]
4879        let primitive = rule.apply(matched.match_stack, x);
4880        #[cfg(feature = "trace")]
4881        trace_phase(
4882            "rhs",
4883            rhs_start,
4884            if primitive.is_some() {
4885                "accepted"
4886            } else {
4887                "rejected"
4888            },
4889        );
4890        if let Some(primitive) = primitive {
4891            return Some(primitive);
4892        }
4893    }
4894
4895    None
4896}
4897
4898#[cfg(test)]
4899fn matcher_rule<T: AtomCore>(expr: T, x: Symbol, rule: &'static RubiRule) -> Option<Atom> {
4900    let expr = expr.as_atom_view();
4901    let target = rubi_symbols()
4902        .rubi_int
4903        .call((expr.to_owned(), Atom::var(x)));
4904    let candidate_bounds = RubiCandidateBounds::new(expr, x);
4905    matcher_rule_with_target(expr, x, rule, &target, &candidate_bounds)
4906}
4907
4908fn matcher_rule_with_target(
4909    expr: AtomView<'_>,
4910    x: Symbol,
4911    rule: &'static RubiRule,
4912    target: &Atom,
4913    candidate_bounds: &RubiCandidateBounds,
4914) -> Option<Atom> {
4915    #[cfg(feature = "trace")]
4916    {
4917        if RUBI_SETTINGS
4918            .trace_rule_timings
4919            .load(AtomicOrdering::Relaxed)
4920        {
4921            let threshold = RUBI_SETTINGS
4922                .trace_rule_timing_ms
4923                .load(AtomicOrdering::Relaxed);
4924            let start = std::time::Instant::now();
4925            let result = matcher_rule_with_target_inner(expr, x, rule, target, candidate_bounds);
4926            let elapsed = start.elapsed();
4927            if elapsed >= std::time::Duration::from_millis(threshold) {
4928                match (rule.block, rule.downvalue_order) {
4929                    (Some(block), Some(order)) => {
4930                        eprintln!(
4931                            "rule {} block {} order {} {:?}",
4932                            rule.id, block, order, elapsed
4933                        )
4934                    }
4935                    (Some(block), None) => {
4936                        eprintln!("rule {} block {} {:?}", rule.id, block, elapsed)
4937                    }
4938                    (None, Some(order)) => {
4939                        eprintln!("rule {} order {} {:?}", rule.id, order, elapsed)
4940                    }
4941                    (None, None) => eprintln!("rule {} {:?}", rule.id, elapsed),
4942                }
4943            }
4944            return result;
4945        }
4946    }
4947
4948    matcher_rule_with_target_inner(expr, x, rule, target, candidate_bounds)
4949}
4950
4951fn matcher_rule_with_target_inner(
4952    expr: AtomView<'_>,
4953    x: Symbol,
4954    rule: &'static RubiRule,
4955    target: &Atom,
4956    candidate_bounds: &RubiCandidateBounds,
4957) -> Option<Atom> {
4958    #[cfg(any(test, feature = "trace"))]
4959    debug_assert!(!rule.id.is_empty());
4960
4961    if !rule
4962        .required_function_heads
4963        .iter()
4964        .all(|head| candidate_bounds.function_heads.contains(head))
4965    {
4966        return None;
4967    }
4968    if candidate_bounds.top_level_is_sum && !rule.can_match_top_level_sum {
4969        return None;
4970    }
4971    if candidate_bounds.top_level_is_sum
4972        && rule
4973            .max_top_level_term_count
4974            .is_some_and(|maximum| candidate_bounds.top_level_term_count > maximum)
4975    {
4976        return None;
4977    }
4978    if rule
4979        .max_top_level_factor_count
4980        .is_some_and(|maximum| candidate_bounds.top_level_factor_count > maximum)
4981    {
4982        return None;
4983    }
4984    if candidate_bounds.top_level_noninteger_power_factor_count
4985        < rule.required_noninteger_power_factor_count
4986    {
4987        return None;
4988    }
4989
4990    if let Some(bound) = &rule.explicit_x_factor_bound {
4991        let x_factor_symbols_are_free = bound
4992            .x_factor_symbols
4993            .iter()
4994            .all(|symbol| rule.wildcard_known_x_free(*symbol));
4995        if x_factor_symbols_are_free
4996            && candidate_bounds.top_level_polynomial_base_count < bound.polynomial_base_count
4997        {
4998            return None;
4999        }
5000        if bound
5001            .non_x_factor_symbols
5002            .iter()
5003            .all(|symbol| rule.wildcard_known_x_free(*symbol))
5004        {
5005            let candidate_factor_count = candidate_bounds.top_level_x_factor_count;
5006            if candidate_factor_count > bound.factor_count {
5007                return None;
5008            }
5009            if x_factor_symbols_are_free {
5010                let optional_free_factor_count = bound.factor_count - candidate_factor_count;
5011                let required_affine_base_count = bound
5012                    .affine_base_count
5013                    .saturating_sub(optional_free_factor_count);
5014                if candidate_bounds.top_level_affine_base_factor_count < required_affine_base_count
5015                {
5016                    return None;
5017                }
5018                let required_unpowered_affine_count = bound
5019                    .unpowered_affine_factor_count
5020                    .saturating_sub(optional_free_factor_count);
5021                if candidate_bounds.top_level_unpowered_affine_factor_count
5022                    < required_unpowered_affine_count
5023                {
5024                    return None;
5025                }
5026            }
5027        }
5028    }
5029    if rule.require_repeated_proper_x_dependent_subexpression
5030        && !rubi_has_repeated_proper_x_dependent_subexpression(expr, x)
5031    {
5032        return None;
5033    }
5034    if rule.require_algebraic_zero_x_free_additive_part
5035        && !rubi_has_algebraic_zero_x_free_additive_part(expr, x)
5036    {
5037        return None;
5038    }
5039    if candidate_bounds.top_level_is_sum
5040        && rule
5041            .max_zero_x_free_additive_term_count
5042            .is_some_and(|maximum| candidate_bounds.top_level_term_count > maximum)
5043    {
5044        return None;
5045    }
5046    if rule.require_proportional_binomial_base_pair
5047        && !rubi_has_proportional_binomial_base_pair(expr, x)
5048    {
5049        return None;
5050    }
5051    if rule.require_opposite_binomial_base_pair && !rubi_has_opposite_binomial_base_pair(expr, x) {
5052        return None;
5053    }
5054    if rule.require_negated_binomial_exponent_pair
5055        && !candidate_bounds.has_negated_binomial_exponent_pair
5056    {
5057        return None;
5058    }
5059    if candidate_bounds.max_common_binomial_exponent_factor_count
5060        < rule.required_common_binomial_exponent_factor_count
5061    {
5062        return None;
5063    }
5064    if candidate_bounds.max_common_positive_integer_binomial_factor_count
5065        < rule.required_common_positive_integer_binomial_factor_count
5066    {
5067        return None;
5068    }
5069    if candidate_bounds
5070        .max_common_polynomial_base_degree_count
5071        .is_some_and(|count| count < rule.required_common_polynomial_base_degree_count)
5072    {
5073        return None;
5074    }
5075    if rule.require_even_quadratic_binomial_base
5076        && !candidate_bounds.has_even_quadratic_binomial_base
5077    {
5078        return None;
5079    }
5080    if rule.require_perfect_square_quadratic_base
5081        && !candidate_bounds.has_perfect_square_quadratic_base
5082    {
5083        return None;
5084    }
5085    if rule.require_half_integer_affine_power && !candidate_bounds.has_half_integer_affine_power {
5086        return None;
5087    }
5088    if rule.require_positive_integer_affine_power
5089        && !candidate_bounds.has_positive_integer_affine_power
5090    {
5091        return None;
5092    }
5093    if rule.require_rational_noninteger_affine_power_below_negative_one
5094        && !candidate_bounds.has_rational_noninteger_affine_power_below_negative_one
5095    {
5096        return None;
5097    }
5098    if rule.require_negative_scaled_affine_and_distinct_noninteger_affine
5099        && !candidate_bounds.has_negative_scaled_affine_and_distinct_noninteger_affine
5100    {
5101        return None;
5102    }
5103    if rule.require_noninteger_affine_exponent_with_positive_difference
5104        && !candidate_bounds.has_noninteger_affine_exponent_with_positive_difference
5105    {
5106        return None;
5107    }
5108    if rule.require_x_dependent_exponent_for_x_dependent_candidate
5109        && expr.contains_symbol(x)
5110        && !candidate_bounds.has_x_dependent_exponent
5111    {
5112        return None;
5113    }
5114    if rule.require_polynomial_complement_of_affine_power
5115        && !rubi_has_polynomial_complement_of_affine_power(expr, x)
5116    {
5117        return None;
5118    }
5119    if candidate_bounds.noninteger_affine_power_count < rule.required_noninteger_affine_power_count
5120    {
5121        return None;
5122    }
5123    if rule.require_explicit_variable_power_factor
5124        && !candidate_bounds.has_explicit_variable_power_factor
5125    {
5126        return None;
5127    }
5128    if rule.require_proportional_affine_factor_pair
5129        && !rubi_has_proportional_affine_factor_pair(expr, x)
5130    {
5131        return None;
5132    }
5133    if rule.require_proportional_common_expression_factor_pair
5134        && !rubi_has_proportional_common_expression_factor_pair(expr, x)
5135    {
5136        return None;
5137    }
5138    if !rule.early_polynomial_derivative_pairs.is_empty()
5139        && !rubi_has_polynomial_derivative_factor_pair(expr, x)
5140    {
5141        return None;
5142    }
5143    #[cfg(feature = "trace")]
5144    let trace_match_timings = RUBI_SETTINGS
5145        .trace_match_timings
5146        .load(AtomicOrdering::Relaxed);
5147    #[cfg(feature = "trace")]
5148    let trace_match_timing_threshold = RUBI_SETTINGS
5149        .trace_match_timing_ms
5150        .load(AtomicOrdering::Relaxed);
5151    #[cfg(feature = "trace")]
5152    let trace_start = trace_match_timings.then(std::time::Instant::now);
5153    let _context = RubiReplacementContext::push(rule, x);
5154    let result = matcher_rule_target(target, x, rule);
5155    #[cfg(feature = "trace")]
5156    if let Some(start) = trace_start {
5157        let elapsed = start.elapsed();
5158        if elapsed >= std::time::Duration::from_millis(trace_match_timing_threshold) {
5159            match (rule.block, rule.downvalue_order) {
5160                (Some(block), Some(order)) => {
5161                    eprintln!(
5162                        "match {} block {} order {} {:?}",
5163                        rule.id, block, order, elapsed
5164                    )
5165                }
5166                (Some(block), None) => eprintln!("match {} block {} {:?}", rule.id, block, elapsed),
5167                (None, Some(order)) => eprintln!("match {} order {} {:?}", rule.id, order, elapsed),
5168                (None, None) => eprintln!("match {} {:?}", rule.id, elapsed),
5169            }
5170        }
5171    }
5172
5173    if let Some(result) = result {
5174        #[cfg(feature = "trace")]
5175        if RUBI_SETTINGS.trace_rules.load(AtomicOrdering::Relaxed) && rubi_trace_rule_matches(rule)
5176        {
5177            match rule.block {
5178                Some(block) => eprintln!("{} block {}: {} => {}", rule.id, block, expr, result),
5179                None => eprintln!("{}: {} => {}", rule.id, expr, result),
5180            }
5181        }
5182        Some(result)
5183    } else {
5184        None
5185    }
5186}
5187
5188fn matcher_helper_rule(
5189    expr: &Atom,
5190    x: Symbol,
5191    rule: &'static RubiRule,
5192    head: Symbol,
5193) -> Option<Atom> {
5194    #[cfg(any(test, feature = "trace"))]
5195    debug_assert!(!rule.id.is_empty());
5196
5197    #[cfg(feature = "trace")]
5198    let trace_match_timings = RUBI_SETTINGS
5199        .trace_match_timings
5200        .load(AtomicOrdering::Relaxed);
5201    #[cfg(feature = "trace")]
5202    let trace_match_timing_threshold = RUBI_SETTINGS
5203        .trace_match_timing_ms
5204        .load(AtomicOrdering::Relaxed);
5205    #[cfg(feature = "trace")]
5206    let trace_start = trace_match_timings.then(std::time::Instant::now);
5207    let target = head.call((expr, x));
5208    let candidate_bounds = RubiCandidateBounds::new(expr.as_view(), x);
5209    let result =
5210        matcher_rule_with_target_inner(expr.as_view(), x, rule, &target, &candidate_bounds);
5211    #[cfg(feature = "trace")]
5212    if let Some(start) = trace_start {
5213        let elapsed = start.elapsed();
5214        if elapsed >= std::time::Duration::from_millis(trace_match_timing_threshold) {
5215            match rule.block {
5216                Some(block) => eprintln!("match {} block {} {:?}", rule.id, block, elapsed),
5217                None => eprintln!("match {} {:?}", rule.id, elapsed),
5218            }
5219        }
5220    }
5221
5222    if let Some(result) = result {
5223        #[cfg(feature = "trace")]
5224        if RUBI_SETTINGS.trace_helpers.load(AtomicOrdering::Relaxed)
5225            && rubi_trace_rule_matches(rule)
5226        {
5227            match rule.block {
5228                Some(block) => eprintln!("{} block {}: {} => {}", rule.id, block, expr, result),
5229                None => eprintln!("{}: {} => {}", rule.id, expr, result),
5230            }
5231        }
5232        Some(result)
5233    } else {
5234        None
5235    }
5236}
5237
5238fn rubi_replacement_context() -> Option<(&'static RubiRule, Symbol)> {
5239    RUBI_REPLACEMENT_CONTEXT.with(|context| {
5240        context.borrow().map(|(rule, x)| {
5241            // The pointer is installed from the static `rubi_rules()` slice while a replacement is matched.
5242            (unsafe { &*rule }, x)
5243        })
5244    })
5245}
5246
5247fn rubi_replacement_condition(matches: &symbolica::id::MatchStack<'_>) -> ConditionResult {
5248    let Some((rule, x)) = rubi_replacement_context() else {
5249        return ConditionResult::False;
5250    };
5251
5252    rule.check(matches, x)
5253}
5254
5255// Rule metadata is populated once during registration. Keep allocation and
5256// growth out of the thousands of generated rule constructors; borrowing the
5257// destination also avoids moving the large RubiRule through an outlined setter.
5258#[cold]
5259#[inline(never)]
5260fn extend_rubi_rule_metadata<T: Copy>(destination: &mut Vec<T>, values: &[T]) {
5261    if !values.is_empty() {
5262        destination.extend_from_slice(values);
5263    }
5264}
5265
5266impl RubiRule {
5267    fn dispatch_before(mut self, order: u16) -> Self {
5268        self.dispatch_order = Some(rubi_dispatch_order(order) - 1);
5269        self
5270    }
5271
5272    fn wildcard_known_x_free(&self, wildcard: Symbol) -> bool {
5273        let mut known = self.early_x_free.to_owned();
5274        known.extend(
5275            self.early_numeric_bounds
5276                .iter()
5277                .map(|(bounded, _)| *bounded),
5278        );
5279        loop {
5280            let previous_len = known.len();
5281            for (left, scale, right) in &self.early_scaled_equal {
5282                if *scale != 0 && known.contains(right) && !known.contains(left) {
5283                    known.push(*left);
5284                }
5285                if *scale != 0 && known.contains(left) && !known.contains(right) {
5286                    known.push(*right);
5287                }
5288            }
5289            if known.len() == previous_len {
5290                return known.contains(&wildcard);
5291            }
5292        }
5293    }
5294
5295    fn with_early_x_dependent(mut self, wildcard: Symbol) -> Self {
5296        self.early_x_dependent.push(wildcard);
5297        self
5298    }
5299
5300    fn with_early_not_integration_variable(mut self, wildcard: Symbol) -> Self {
5301        self.early_not_integration_variable.push(wildcard);
5302        self
5303    }
5304
5305    fn with_repeated_proper_x_dependent_subexpression(mut self) -> Self {
5306        self.require_repeated_proper_x_dependent_subexpression = true;
5307        self
5308    }
5309
5310    fn with_early_numeric_bound(mut self, wildcard: Symbol, bound: RubiEarlyNumericBound) -> Self {
5311        self.early_numeric_bounds.push((wildcard, bound));
5312        self
5313    }
5314
5315    fn with_early_positive_integer_or_integer_pair(
5316        mut self,
5317        first: Symbol,
5318        second: Symbol,
5319    ) -> Self {
5320        self.early_positive_integer_or_integer_pairs
5321            .push((first, second));
5322        self
5323    }
5324
5325    fn with_early_proportional_affine(mut self, coefficients: [Symbol; 4]) -> Self {
5326        self.early_proportional_affine.push(coefficients);
5327        self.require_proportional_affine_factor_pair = true;
5328        self
5329    }
5330
5331    fn with_early_proportional_common_expression(mut self, coefficients: [Symbol; 4]) -> Self {
5332        self.early_proportional_affine.push(coefficients);
5333        self.require_proportional_common_expression_factor_pair = true;
5334        self
5335    }
5336
5337    fn with_proportional_affine_factor_pair(mut self) -> Self {
5338        self.require_proportional_affine_factor_pair = true;
5339        self
5340    }
5341
5342    fn with_algebraic_zero_x_free_additive_part(mut self, max_terms: usize) -> Self {
5343        self.require_algebraic_zero_x_free_additive_part = true;
5344        self.max_zero_x_free_additive_term_count = Some(max_terms);
5345        self
5346    }
5347
5348    fn with_proportional_binomial_base_pair(mut self) -> Self {
5349        self.require_proportional_binomial_base_pair = true;
5350        self
5351    }
5352
5353    fn with_opposite_binomial_base_pair(mut self) -> Self {
5354        self.require_opposite_binomial_base_pair = true;
5355        self
5356    }
5357
5358    fn with_negated_binomial_exponent_pair(mut self) -> Self {
5359        self.require_negated_binomial_exponent_pair = true;
5360        self
5361    }
5362
5363    fn with_common_positive_integer_binomial_factor_count(mut self, count: usize) -> Self {
5364        self.required_common_positive_integer_binomial_factor_count = count;
5365        self
5366    }
5367
5368    fn with_common_binomial_exponent_factor_count(mut self, count: usize) -> Self {
5369        self.required_common_binomial_exponent_factor_count = count;
5370        self
5371    }
5372
5373    fn with_common_polynomial_base_degree_count(mut self, count: usize) -> Self {
5374        self.required_common_polynomial_base_degree_count = count;
5375        self
5376    }
5377
5378    fn with_noninteger_power_factor_count(mut self, count: usize) -> Self {
5379        self.required_noninteger_power_factor_count = count;
5380        self
5381    }
5382
5383    fn with_even_quadratic_binomial_base(mut self) -> Self {
5384        self.require_even_quadratic_binomial_base = true;
5385        self
5386    }
5387
5388    fn with_explicit_variable_power_factor(mut self) -> Self {
5389        self.require_explicit_variable_power_factor = true;
5390        self
5391    }
5392
5393    fn with_noninteger_affine_exponent_with_positive_difference(mut self) -> Self {
5394        self.require_noninteger_affine_exponent_with_positive_difference = true;
5395        self
5396    }
5397
5398    fn with_positive_integer_affine_power(mut self) -> Self {
5399        self.require_positive_integer_affine_power = true;
5400        self
5401    }
5402
5403    fn with_rational_noninteger_affine_power_below_negative_one(mut self) -> Self {
5404        self.require_rational_noninteger_affine_power_below_negative_one = true;
5405        self
5406    }
5407
5408    fn with_x_dependent_exponent_for_x_dependent_candidate(mut self) -> Self {
5409        self.require_x_dependent_exponent_for_x_dependent_candidate = true;
5410        self
5411    }
5412
5413    fn with_polynomial_complement_of_affine_power(mut self) -> Self {
5414        self.require_polynomial_complement_of_affine_power = true;
5415        self
5416    }
5417
5418    fn check(&self, matches: &symbolica::id::MatchStack<'_>, x: Symbol) -> ConditionResult {
5419        let symbols = rubi_symbols();
5420
5421        // Symbolica invokes match-stack conditions immediately after appending a
5422        // new binding, so all earlier entries have already passed these bounds.
5423        if let Some((wildcard, matched)) = matches.get_matches().last() {
5424            if *wildcard == symbols.x_ && matched.as_single() != Some(InlineVar::new(x).as_view()) {
5425                return ConditionResult::False;
5426            } else if self.early_x_dependent.contains(wildcard)
5427                && !matched.to_atom().contains_symbol(x)
5428            {
5429                return ConditionResult::False;
5430            } else if self.early_x_free.contains(wildcard) && matched.to_atom().contains_symbol(x) {
5431                return ConditionResult::False;
5432            } else if self.early_x_linear.contains(wildcard)
5433                && !rubi_linear_q(matched.to_atom().as_view(), x)
5434            {
5435                return ConditionResult::False;
5436            } else if self.early_not_integration_variable.contains(wildcard)
5437                && matched.as_single() == Some(InlineVar::new(x).as_view())
5438            {
5439                return ConditionResult::False;
5440            } else if self.required_explicit_power_exponents.contains(wildcard) {
5441                let exponent = matched.to_atom();
5442                if exponent.is_zero() || exponent.is_one() {
5443                    return ConditionResult::False;
5444                }
5445            } else if self
5446                .early_numeric_bounds
5447                .iter()
5448                .filter(|(bounded, _)| bounded == wildcard)
5449                .any(|(_, bound)| !bound.matches(&matched.to_atom()))
5450            {
5451                return ConditionResult::False;
5452            } else if self.early_zero.contains(wildcard)
5453                && !rubi_algebraic_zero_q(&matched.to_atom())
5454            {
5455                return ConditionResult::False;
5456            }
5457
5458            for (left, scale, right) in &self.early_scaled_equal {
5459                if *wildcard != *left && *wildcard != *right {
5460                    continue;
5461                }
5462                let Some([left, right]) = wildcard_atoms_for_rule(matches, [*left, *right], self)
5463                else {
5464                    continue;
5465                };
5466                if !rubi_algebraic_zero_q(&(left - Atom::num(*scale) * right)) {
5467                    return ConditionResult::False;
5468                }
5469            }
5470
5471            for (first, second) in &self.early_positive_integer_or_integer_pairs {
5472                if *wildcard != *first && *wildcard != *second {
5473                    continue;
5474                }
5475                let Some([first, second]) =
5476                    wildcard_atoms_for_rule(matches, [*first, *second], self)
5477                else {
5478                    continue;
5479                };
5480                if !(igtq!(first, 0) || integersq!([first, second])) {
5481                    return ConditionResult::False;
5482                }
5483            }
5484
5485            for coefficients @ [a, b, c, d] in &self.early_proportional_affine {
5486                if !coefficients.contains(wildcard) {
5487                    continue;
5488                }
5489                let Some([a, b, c, d]) = wildcard_atoms_for_rule(matches, [*a, *b, *c, *d], self)
5490                else {
5491                    continue;
5492                };
5493                if !rubi_algebraic_zero_q(&(b * c - a * d)) {
5494                    return ConditionResult::False;
5495                }
5496            }
5497
5498            for (polynomial, derivative) in &self.early_polynomial_derivative_pairs {
5499                if *wildcard != *polynomial && *wildcard != *derivative {
5500                    continue;
5501                }
5502                let Some([polynomial, derivative]) =
5503                    wildcard_atoms_for_rule(matches, [*polynomial, *derivative], self)
5504                else {
5505                    continue;
5506                };
5507                if !rubi_polynomial_derivative_pair_q(&polynomial, &derivative, x) {
5508                    return ConditionResult::False;
5509                }
5510            }
5511        }
5512
5513        let match_count = matches.get_matches().len();
5514        #[cfg(feature = "bake-integration-variable")]
5515        let expected_count = self.required.len() - usize::from(self.required.contains(&symbols.x_));
5516        #[cfg(not(feature = "bake-integration-variable"))]
5517        let expected_count =
5518            self.required.len() + usize::from(!self.required.contains(&symbols.x_));
5519        if match_count != expected_count {
5520            #[cfg(feature = "trace")]
5521            if RUBI_SETTINGS.trace_candidates.load(AtomicOrdering::Relaxed)
5522                && rubi_trace_rule_matches(self)
5523            {
5524                eprintln!(
5525                    "? {} binding count: expected {}, got {}",
5526                    self.id, expected_count, match_count
5527                );
5528                let missing_names = self
5529                    .required
5530                    .iter()
5531                    .copied()
5532                    .filter(|wildcard| wildcard_atom_for_rule(matches, *wildcard, self).is_none())
5533                    .map(|wildcard| wildcard.to_string())
5534                    .collect::<Vec<_>>();
5535                let x_missing = wildcard_atom_for_rule(matches, symbols.x_, self).is_none();
5536                eprintln!("  missing with: {missing_names:?}; x_ missing: {x_missing}");
5537            }
5538            return ConditionResult::Inconclusive;
5539        }
5540        let Some(integration_variable) = wildcard_atom_for_rule(matches, symbols.x_, self) else {
5541            return ConditionResult::Inconclusive;
5542        };
5543        debug_assert_eq!(integration_variable, x);
5544
5545        #[cfg(feature = "trace")]
5546        if RUBI_SETTINGS.trace_candidates.load(AtomicOrdering::Relaxed)
5547            && rubi_trace_rule_matches(self)
5548        {
5549            match self.block {
5550                Some(block) => eprintln!("? {} block {}", self.id, block),
5551                None => eprintln!("? {}", self.id),
5552            }
5553            if RUBI_SETTINGS.trace_bindings.load(AtomicOrdering::Relaxed) {
5554                for wildcard in &self.required {
5555                    if let Some(bound) = wildcard_atom_for_rule(matches, *wildcard, self) {
5556                        eprintln!("  {} = {}", wildcard, bound);
5557                    }
5558                }
5559            }
5560        }
5561
5562        #[cfg(feature = "trace")]
5563        let trace_condition_timings = RUBI_SETTINGS
5564            .trace_condition_timings
5565            .load(AtomicOrdering::Relaxed);
5566        #[cfg(feature = "trace")]
5567        let trace_condition_timing_threshold = RUBI_SETTINGS
5568            .trace_condition_timing_ms
5569            .load(AtomicOrdering::Relaxed);
5570        #[cfg(feature = "trace")]
5571        let trace_start = trace_condition_timings.then(std::time::Instant::now);
5572        #[cfg(feature = "trace")]
5573        let previous_rule = CURRENT_RUBI_RULE.with(|current| {
5574            let previous = current.get();
5575            current.set(self as *const RubiRule);
5576            previous
5577        });
5578        let result = (self.condition)(matches, x, self);
5579        #[cfg(feature = "trace")]
5580        CURRENT_RUBI_RULE.with(|current| current.set(previous_rule));
5581        #[cfg(feature = "trace")]
5582        if let Some(start) = trace_start {
5583            let elapsed = start.elapsed();
5584            if elapsed >= std::time::Duration::from_millis(trace_condition_timing_threshold) {
5585                match self.block {
5586                    Some(block) => eprintln!("condition {} block {} {:?}", self.id, block, elapsed),
5587                    None => eprintln!("condition {} {:?}", self.id, elapsed),
5588                }
5589            }
5590        }
5591        result
5592    }
5593
5594    fn apply(&self, matches: &symbolica::id::MatchStack<'_>, x: Symbol) -> Option<Atom> {
5595        #[cfg(feature = "trace")]
5596        let previous_rule = CURRENT_RUBI_RULE.with(|current| {
5597            let previous = current.get();
5598            current.set(self as *const RubiRule);
5599            previous
5600        });
5601        let result = (self.action)(matches, x, self);
5602        #[cfg(feature = "trace")]
5603        CURRENT_RUBI_RULE.with(|current| current.set(previous_rule));
5604        result
5605    }
5606}
5607
5608impl RubiEarlyNumericBound {
5609    fn matches(self, value: &Atom) -> bool {
5610        match self {
5611            Self::Integer => integer_q(value),
5612            Self::IntegerGreaterThan(threshold) => is_integer_greater_than(value, threshold),
5613            Self::IntegerLessThan(threshold) => is_integer_less_than(value, threshold),
5614            Self::NumberGreaterThan(threshold) => is_number_greater_than(value, threshold),
5615            Self::NumberLessThan(threshold) => is_number_less_than(value, threshold),
5616        }
5617    }
5618}
5619
5620#[cfg(test)]
5621fn scaled_monomial_inside_general_binomial_substitution_primitive(
5622    constant: Atom,
5623    coefficient: Atom,
5624    scale: Atom,
5625    inner_exponent: Atom,
5626    binomial_exponent: Atom,
5627    monomial_exponent: Atom,
5628    x: Symbol,
5629) -> Option<Atom> {
5630    if !is_free_of(
5631        (
5632            &constant,
5633            &coefficient,
5634            &scale,
5635            &inner_exponent,
5636            &binomial_exponent,
5637            &monomial_exponent,
5638        ),
5639        x,
5640    ) {
5641        return None;
5642    }
5643
5644    let transformed_power = (inner_exponent * &monomial_exponent).expand();
5645    if integer_i64(&transformed_power).is_none() {
5646        return None;
5647    }
5648
5649    let variable = Atom::var(x);
5650    let scaled_monomial = scale * variable.pow(&monomial_exponent);
5651    let replacement = scaled_monomial.pow(Atom::num(1) / monomial_exponent);
5652    if replacement == variable {
5653        return None;
5654    }
5655
5656    let substitution_guard = fresh_substitution_symbol().unwrap();
5657    let substitution_symbol = substitution_guard.symbol();
5658    let substitution_variable = Atom::var(substitution_symbol);
5659    let transformed_integrand = (constant
5660        + coefficient * substitution_variable.pow(transformed_power))
5661    .pow(binomial_exponent);
5662    let transformed_primitive =
5663        integrate_internal(transformed_integrand.as_view(), substitution_symbol)
5664            .or_else(|| integrate_polynomial(&transformed_integrand.expand(), substitution_symbol))
5665            .or_else(|| {
5666                integrate_laurent_polynomial(&transformed_integrand.expand(), substitution_symbol)
5667            })?;
5668
5669    Some(
5670        variable / &replacement
5671            * substitute_symbol(&transformed_primitive, substitution_symbol, replacement),
5672    )
5673}
5674
5675#[allow(clippy::too_many_arguments)]
5676fn normalize_power_of_linear(expr: AtomView<'_>, x: Symbol) -> Option<(Atom, bool)> {
5677    if let Some(normalized) = normalize_visible_power_of_linear(expr, x) {
5678        return Some(normalized);
5679    }
5680
5681    let factored = rubi_try_factor(expr)?;
5682    if factored.as_view() == expr {
5683        return None;
5684    }
5685    let (normalized, _) = normalize_visible_power_of_linear(factored.as_view(), x)?;
5686    Some((normalized, true))
5687}
5688
5689fn normalize_visible_power_of_linear(expr: AtomView<'_>, x: Symbol) -> Option<(Atom, bool)> {
5690    if let Some((constant, slope)) = linear_coefficients(expr, x) {
5691        if slope.is_zero() {
5692            return None;
5693        }
5694        let normalized = constant + slope * Atom::var(x);
5695        return Some((normalized.to_owned(), normalized.as_view() != expr));
5696    }
5697
5698    if let AtomView::Pow(power) = expr {
5699        let (base, exponent) = power.get_base_exp();
5700        let exponent = exponent.to_owned();
5701        if !is_free_of(&exponent, x) {
5702            return None;
5703        }
5704        let (constant, slope) = linear_coefficients(base, x)?;
5705        if slope.is_zero() {
5706            return None;
5707        }
5708        let normalized_base = constant + slope * Atom::var(x);
5709        let normalized = normalized_base.pow(exponent);
5710        return Some((normalized.to_owned(), normalized.as_view() != expr));
5711    }
5712
5713    None
5714}
5715
5716fn rubi_power_of_linear_match_q(expr: &Atom, x: Symbol) -> bool {
5717    normalize_power_of_linear(expr.as_view(), x).is_some_and(|(_, changed)| !changed)
5718}
5719
5720#[cfg(test)]
5721fn rubi_normalize_power_of_linear(expr: &Atom, x: Symbol) -> Option<Atom> {
5722    normalize_power_of_linear(expr.as_view(), x).map(|(normalized, _)| normalized)
5723}
5724
5725/// Tests whether a value contains the current integration symbol.
5726trait FreeOf {
5727    fn has_symbol(self, x: Symbol) -> bool;
5728}
5729
5730impl FreeOf for AtomView<'_> {
5731    fn has_symbol(self, x: Symbol) -> bool {
5732        atom_view_has_symbol(self, x)
5733    }
5734}
5735
5736impl FreeOf for &Atom {
5737    fn has_symbol(self, x: Symbol) -> bool {
5738        atom_view_has_symbol(self.as_view(), x)
5739    }
5740}
5741
5742impl FreeOf for &Symbol {
5743    fn has_symbol(self, x: Symbol) -> bool {
5744        *self == x
5745    }
5746}
5747
5748/// Implements `FreeOf` for tuples used by multi-argument `FreeQ` guards.
5749macro_rules! impl_free_of_tuple {
5750    ($($name:ident),+) => {
5751        impl<$($name: FreeOf),+> FreeOf for ($($name,)+) {
5752            #[allow(non_snake_case)]
5753            fn has_symbol(self, x: Symbol) -> bool {
5754                let ($($name,)+) = self;
5755                false $(|| $name.has_symbol(x))+
5756            }
5757        }
5758    };
5759}
5760
5761impl_free_of_tuple!(A, B);
5762impl_free_of_tuple!(A, B, C);
5763impl_free_of_tuple!(A, B, C, D);
5764impl_free_of_tuple!(A, B, C, D, E);
5765impl_free_of_tuple!(A, B, C, D, E, F);
5766impl_free_of_tuple!(A, B, C, D, E, F, G);
5767impl_free_of_tuple!(A, B, C, D, E, F, G, H);
5768impl_free_of_tuple!(A, B, C, D, E, F, G, H, I);
5769impl_free_of_tuple!(A, B, C, D, E, F, G, H, I, J);
5770impl_free_of_tuple!(A, B, C, D, E, F, G, H, I, J, K);
5771impl_free_of_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
5772impl_free_of_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
5773impl_free_of_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
5774
5775fn is_free_of(expr: impl FreeOf, x: Symbol) -> bool {
5776    !expr.has_symbol(x)
5777}
5778
5779fn rubi_evaluated_free_q(expr: impl RubiAtomArgument, x: Symbol) -> bool {
5780    is_free_of(&expr.rubi_atom_or_view().as_view().expand(), x)
5781}
5782
5783fn atom_view_has_symbol(expr: AtomView<'_>, x: Symbol) -> bool {
5784    match expr {
5785        AtomView::Var(variable) => variable.get_symbol() == x,
5786        AtomView::Num(_) => false,
5787        AtomView::Pow(power) => {
5788            atom_view_has_symbol(power.get_base(), x) || atom_view_has_symbol(power.get_exp(), x)
5789        }
5790        AtomView::Mul(mul) => mul
5791            .into_iter()
5792            .any(|factor| atom_view_has_symbol(factor, x)),
5793        AtomView::Add(add) => add.into_iter().any(|term| atom_view_has_symbol(term, x)),
5794        AtomView::Fun(function) => {
5795            function.get_symbol() == x
5796                || function
5797                    .into_iter()
5798                    .any(|argument| atom_view_has_symbol(argument, x))
5799        }
5800    }
5801}
5802
5803fn rubi_nonfree_factors(expr: &Atom, x: Symbol) -> Atom {
5804    match expr.as_view() {
5805        AtomView::Mul(mul) => mul
5806            .into_iter()
5807            .filter(|factor| !is_free_of(*factor, x))
5808            .map(|factor| factor.to_owned())
5809            .fold(Atom::num(1), |product, factor| product * factor),
5810        _ if is_free_of(expr, x) => Atom::num(1),
5811        _ => expr.to_owned(),
5812    }
5813}
5814
5815fn rubi_free_factors(expr: &Atom, x: Symbol) -> Atom {
5816    match expr.as_view() {
5817        AtomView::Mul(mul) => mul
5818            .into_iter()
5819            .filter(|factor| is_free_of(*factor, x))
5820            .map(|factor| factor.to_owned())
5821            .fold(Atom::num(1), |product, factor| product * factor),
5822        _ if is_free_of(expr, x) => expr.to_owned(),
5823        _ => Atom::num(1),
5824    }
5825}
5826
5827fn rubi_remove_content(expr: &Atom, x: Symbol) -> Atom {
5828    let expr = rubi_evaluate_builtin_trig_pi_shifts(expr.as_view(), x);
5829    let expr = rubi_normalize_numeric_minus_one_powers(expr.as_view());
5830    let v = rubi_nonfree_factors(&expr, x);
5831    // Mathematica Together leaves a denominator-free sum structurally unchanged.
5832    // Symbolica may factor a global sign, which changes the subsequent
5833    // RemoveContentAux pattern selected by Rubi.
5834    let w = if rubi_sum_q(&v) && !rubi_explicit_negative_rational_power_q(v.as_view()) {
5835        v.to_owned()
5836    } else {
5837        v.together()
5838    };
5839    if eqq!(rubi_free_factors(&w, x), 1) {
5840        rubi_remove_content_aux(&v, x)
5841    } else {
5842        rubi_remove_content_aux(&rubi_nonfree_factors(&w, x), x)
5843    }
5844}
5845
5846fn rubi_explicit_negative_rational_power_q(expr: AtomView<'_>) -> bool {
5847    match expr {
5848        AtomView::Pow(power) => {
5849            let (base, exponent) = power.get_base_exp();
5850            (raw_integer_i64(base) != Some(-1)
5851                && rational_number_view(exponent).is_some_and(|(numerator, _)| numerator < 0))
5852                || rubi_explicit_negative_rational_power_q(base)
5853                || rubi_explicit_negative_rational_power_q(exponent)
5854        }
5855        AtomView::Add(add) => add.into_iter().any(rubi_explicit_negative_rational_power_q),
5856        AtomView::Mul(mul) => mul.into_iter().any(rubi_explicit_negative_rational_power_q),
5857        AtomView::Fun(function) => function
5858            .into_iter()
5859            .any(rubi_explicit_negative_rational_power_q),
5860        AtomView::Num(_) | AtomView::Var(_) => false,
5861    }
5862}
5863
5864fn rubi_normalize_numeric_minus_one_powers(expr: AtomView<'_>) -> Atom {
5865    fn normalized_power(numerator: i64, denominator: i64) -> Atom {
5866        let integer_part = numerator.div_euclid(denominator);
5867        let remainder = numerator.rem_euclid(denominator);
5868        let sign = if integer_part.rem_euclid(2) == 0 {
5869            1
5870        } else {
5871            -1
5872        };
5873        if remainder == 0 {
5874            Atom::num(sign)
5875        } else {
5876            Atom::num(sign) * Atom::num(-1).pow(Atom::num(remainder) / Atom::num(denominator))
5877        }
5878    }
5879
5880    match expr {
5881        AtomView::Pow(power) => {
5882            let base = rubi_normalize_numeric_minus_one_powers(power.get_base());
5883            let exponent = rubi_normalize_numeric_minus_one_powers(power.get_exp());
5884            if base == Atom::num(-1)
5885                && let Some((numerator, denominator)) = rational_number(&exponent)
5886            {
5887                return normalized_power(numerator, denominator);
5888            }
5889            if let AtomView::Pow(inner_power) = base.as_view()
5890                && inner_power.get_base().to_owned() == Atom::num(-1)
5891                && let Some((inner_numerator, inner_denominator)) =
5892                    rational_number_view(inner_power.get_exp())
5893                && let Some(outer_integer) = integer_i64(&exponent)
5894                && let Some(numerator) = inner_numerator.checked_mul(outer_integer)
5895            {
5896                return normalized_power(numerator, inner_denominator);
5897            }
5898            base.pow(exponent)
5899        }
5900        AtomView::Add(add) => add
5901            .into_iter()
5902            .map(rubi_normalize_numeric_minus_one_powers)
5903            .fold(Atom::num(0), |sum, term| sum + term),
5904        AtomView::Mul(mul) => mul
5905            .into_iter()
5906            .map(rubi_normalize_numeric_minus_one_powers)
5907            .fold(Atom::num(1), |product, factor| product * factor),
5908        AtomView::Fun(function) => function.get_symbol().call_args(
5909            function
5910                .into_iter()
5911                .map(rubi_normalize_numeric_minus_one_powers),
5912        ),
5913        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
5914    }
5915}
5916
5917fn rubi_evaluate_builtin_trig_pi_shifts(expr: AtomView<'_>, x: Symbol) -> Atom {
5918    match expr {
5919        AtomView::Fun(function)
5920            if function.get_nargs() == 1 && rubi_builtin_trig_symbol_q(function.get_symbol()) =>
5921        {
5922            let argument = rubi_evaluate_builtin_trig_pi_shifts(function.get(0), x);
5923            if rubi_linear_q(argument.as_view(), x) {
5924                let inert_symbol = rubi_inert_symbol_for_builtin_trig(function.get_symbol())
5925                    .expect("built-in trig guard should map to an inert symbol");
5926                return rubi_activate_trig(&rubi_reduce_inert_trig(
5927                    inert_symbol,
5928                    rubi_expand_to_sum(&argument, x),
5929                ));
5930            }
5931            function.get_symbol().call((argument,))
5932        }
5933        AtomView::Fun(function) => {
5934            let args: Vec<_> = function
5935                .into_iter()
5936                .map(|argument| rubi_evaluate_builtin_trig_pi_shifts(argument, x))
5937                .collect();
5938            function.get_symbol().call_args(args)
5939        }
5940        AtomView::Add(add) => add
5941            .into_iter()
5942            .map(|term| rubi_evaluate_builtin_trig_pi_shifts(term, x))
5943            .fold(Atom::num(0), |sum, term| sum + term),
5944        AtomView::Mul(mul) => mul
5945            .into_iter()
5946            .map(|factor| rubi_evaluate_builtin_trig_pi_shifts(factor, x))
5947            .fold(Atom::num(1), |product, factor| product * factor),
5948        AtomView::Pow(power) => rubi_evaluate_builtin_trig_pi_shifts(power.get_base(), x)
5949            .pow(rubi_evaluate_builtin_trig_pi_shifts(power.get_exp(), x)),
5950        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
5951    }
5952}
5953
5954fn rubi_remove_content_aux(expr: &Atom, x: Symbol) -> Atom {
5955    if let Some(reduced) = rubi_remove_opposite_integer_power_content(expr, x) {
5956        return rubi_remove_content_aux(&reduced, x);
5957    }
5958
5959    if let Some(reduced) = rubi_remove_common_free_power_content(expr, x) {
5960        return rubi_remove_content_aux(&reduced, x);
5961    }
5962
5963    if rubi_sum_q(expr) && rubi_first_term_neg_q(expr) {
5964        rubi_add_terms(expr)
5965            .into_iter()
5966            .map(|term| -term)
5967            .fold(Atom::num(0), |sum, term| sum + term)
5968    } else {
5969        expr.to_owned()
5970    }
5971}
5972
5973fn rubi_remove_opposite_integer_power_content(expr: &Atom, x: Symbol) -> Option<Atom> {
5974    let terms = rubi_add_terms(expr);
5975    if terms.len() != 2 {
5976        return None;
5977    }
5978
5979    let first = rubi_mathematica_first_sum_term_in(expr, x)?;
5980    let mut candidates = free_power_factors(&first, x);
5981    candidates.sort_by_key(|(_, exponent)| integer_i64(exponent) == Some(1));
5982    for (a, m) in candidates {
5983        // The source pattern is a_^m_, so an implicit exponent of 1 does not match.
5984        if integer_i64(&m) == Some(1) || !integerq!(a) || !rationalq!(m) {
5985            continue;
5986        }
5987
5988        let first_index = terms.iter().position(|term| *term == first)?;
5989        let rest = terms[1 - first_index].to_owned();
5990        let b = -&a;
5991        let Some(v) = rubi_divide_explicit_integer_factor(&rest, &b) else {
5992            continue;
5993        };
5994        let u = (&first / a.pow(&m)).cancel();
5995        let reduced = if gtq!(m, 1) {
5996            a.pow(&m - Atom::num(1)) * u - v
5997        } else {
5998            u - a.pow(Atom::num(1) - &m) * v
5999        };
6000        return Some(rubi_normalize_numeric_minus_one_powers(reduced.as_view()));
6001    }
6002
6003    None
6004}
6005
6006fn rubi_divide_explicit_integer_factor(expr: &Atom, factor: &Atom) -> Option<Atom> {
6007    if factor.is_one() {
6008        return Some(expr.to_owned());
6009    }
6010
6011    let mut quotient = Atom::num(0);
6012    for term in rubi_add_terms(expr) {
6013        let (numeric, nonnumeric) = rubi_split_numeric_factor(&term);
6014        if rational_atom(numeric) != *factor {
6015            return None;
6016        }
6017        quotient += nonnumeric;
6018    }
6019    Some(quotient)
6020}
6021
6022fn rubi_first_term_neg_q(expr: &Atom) -> bool {
6023    rubi_mathematica_first_sum_term(expr).is_some_and(|term| is_negative_term(&term))
6024}
6025
6026fn is_negative_term(expr: &Atom) -> bool {
6027    if rubi_negative_form_q(expr) {
6028        return true;
6029    }
6030
6031    match expr.as_view() {
6032        AtomView::Mul(mul) => mul
6033            .into_iter()
6034            .any(|factor| is_number_less_than(&factor.to_owned(), 0)),
6035        _ => false,
6036    }
6037}
6038
6039fn rubi_remove_common_free_power_content(expr: &Atom, x: Symbol) -> Option<Atom> {
6040    let AtomView::Add(add) = expr.as_view() else {
6041        return None;
6042    };
6043    let terms: Vec<Atom> = add.into_iter().map(|term| term.to_owned()).collect();
6044    if terms.len() < 2 || terms.len() > 3 {
6045        return None;
6046    }
6047
6048    let mut candidates = free_power_factors(&terms[0], x);
6049    candidates.sort_by_key(|(_, exponent)| integer_i64(exponent) == Some(1));
6050    'candidate: for (base, m) in candidates {
6051        let mut exponents = Vec::new();
6052        for term in &terms {
6053            let Some(exponent) = exponent_of_free_power_factor(term, &base) else {
6054                continue 'candidate;
6055            };
6056            if !rational_q(&exponent) {
6057                exponents.clear();
6058                break;
6059            }
6060            exponents.push(exponent);
6061        }
6062        if exponents.is_empty() {
6063            continue;
6064        }
6065
6066        if m.is_zero() {
6067            continue;
6068        }
6069        if exponents
6070            .iter()
6071            .any(|exponent| !is_number_greater_or_equal_atom(&(exponent - &m), &Atom::num(0)))
6072        {
6073            continue;
6074        }
6075
6076        let reduced = terms
6077            .iter()
6078            .map(|term| term / base.pow(&m))
6079            .fold(Atom::num(0), |sum, term| sum + term);
6080        let reduced = reduced.expand().cancel();
6081        let reduced = rubi_normalize_numeric_minus_one_powers(reduced.as_view());
6082        return Some(reduced);
6083    }
6084
6085    None
6086}
6087
6088fn free_power_factors(expr: &Atom, x: Symbol) -> Vec<(Atom, Atom)> {
6089    match expr.as_view() {
6090        AtomView::Mul(mul) => mul
6091            .into_iter()
6092            .filter_map(|factor| free_power_factor(&factor.to_owned(), x))
6093            .collect(),
6094        _ => free_power_factor(expr, x).into_iter().collect(),
6095    }
6096}
6097
6098fn free_power_factor(expr: &Atom, x: Symbol) -> Option<(Atom, Atom)> {
6099    if let AtomView::Pow(power) = expr.as_view() {
6100        let (base, exponent) = power.get_base_exp();
6101        let base = base.to_owned();
6102        let exponent = exponent.to_owned();
6103        if is_free_of(&base, x) && rational_q(&exponent) {
6104            return Some((base, exponent));
6105        }
6106    }
6107
6108    is_free_of(expr, x).then(|| (expr.to_owned(), Atom::num(1)))
6109}
6110
6111fn exponent_of_free_power_factor(expr: &Atom, base: &Atom) -> Option<Atom> {
6112    if let AtomView::Mul(mul) = expr.as_view() {
6113        for factor in mul {
6114            if let Some((factor_base, exponent)) = power_factor(&factor.to_owned()) {
6115                if factor_base == *base {
6116                    return Some(exponent);
6117                }
6118            }
6119            if factor.to_owned() == *base {
6120                return Some(Atom::num(1));
6121            }
6122        }
6123        return None;
6124    }
6125
6126    if let Some((factor_base, exponent)) = power_factor(expr) {
6127        if factor_base == *base {
6128            return Some(exponent);
6129        }
6130    }
6131    if expr == base {
6132        Some(Atom::num(1))
6133    } else {
6134        None
6135    }
6136}
6137
6138fn power_factor(expr: &Atom) -> Option<(Atom, Atom)> {
6139    let AtomView::Pow(power) = expr.as_view() else {
6140        return None;
6141    };
6142    let (base, exponent) = power.get_base_exp();
6143    Some((base.to_owned(), exponent.to_owned()))
6144}
6145
6146fn has_x_free_factor(expr: &Atom, x: Symbol) -> bool {
6147    match expr.as_view() {
6148        AtomView::Mul(mul) => mul.into_iter().any(|factor| is_free_of(factor, x)),
6149        _ => false,
6150    }
6151}
6152
6153fn poly_q(expr: &Atom, x: Symbol) -> bool {
6154    rubi_polynomial_terms(expr, x).is_some()
6155}
6156
6157fn rubi_poly_q(expr: &Atom, x: Symbol) -> bool {
6158    poly_q(expr, x)
6159}
6160
6161fn rubi_polynomial_q(expr: &Atom, x: Symbol) -> bool {
6162    collect_polynomial_terms(expr, x).is_some()
6163}
6164
6165fn poly_in_power_q(expr: &Atom, x: Symbol, power: &Atom) -> bool {
6166    let Some((power_numerator, power_denominator)) = rational_number(power) else {
6167        return false;
6168    };
6169    if power_numerator == 0 {
6170        return false;
6171    }
6172
6173    let expanded = expr.expand();
6174    match expanded.as_view() {
6175        AtomView::Add(add) => add.into_iter().all(|term| {
6176            monomial_rational_degree(term, x).is_some_and(|degree| {
6177                rational_degree_is_nonnegative_multiple(
6178                    degree,
6179                    (power_numerator, power_denominator),
6180                )
6181            })
6182        }),
6183        term => monomial_rational_degree(term, x).is_some_and(|degree| {
6184            rational_degree_is_nonnegative_multiple(degree, (power_numerator, power_denominator))
6185        }),
6186    }
6187}
6188
6189fn subst_for_power(expr: &Atom, x: Symbol, power: &Atom, sub: Symbol) -> Option<Atom> {
6190    let Some((power_numerator, power_denominator)) = rational_number(power) else {
6191        return None;
6192    };
6193    if power_numerator == 0 {
6194        return None;
6195    }
6196
6197    let sub_atom = Atom::var(sub);
6198    let x_atom = Atom::var(x);
6199    let expanded = expr.expand();
6200    let mut result = Atom::num(0);
6201
6202    match expanded.as_view() {
6203        AtomView::Add(add) => {
6204            for term in add {
6205                result += subst_for_power_term(
6206                    term,
6207                    x,
6208                    &x_atom,
6209                    &sub_atom,
6210                    (power_numerator, power_denominator),
6211                )?;
6212            }
6213        }
6214        term => {
6215            result += subst_for_power_term(
6216                term,
6217                x,
6218                &x_atom,
6219                &sub_atom,
6220                (power_numerator, power_denominator),
6221            )?;
6222        }
6223    }
6224
6225    Some(result.expand())
6226}
6227
6228fn rubi_subst_for_power(expr: &Atom, x: Symbol, power: &Atom, sub: Symbol) -> Option<Atom> {
6229    subst_for_power(expr, x, power, sub)
6230}
6231
6232fn rubi_subst_for(expr: &Atom, base: impl RubiAtomArgument, sub: Symbol) -> Atom {
6233    let base = base.into_rubi_atom();
6234    if !rubi_inert_trig_free_q(expr) {
6235        return rubi_subst_for(&rubi_activate_trig(expr), &base, sub);
6236    }
6237
6238    if let Some(result) = rubi_subst_for_trig_base(expr, &base, sub) {
6239        return result;
6240    }
6241
6242    if let Some(result) = rubi_subst_for_hyperbolic_base(expr, &base, sub) {
6243        return result;
6244    }
6245
6246    rubi_subst_for_aux(expr, &base, sub)
6247}
6248
6249fn rubi_subst_for_factor(factor: &Atom, base: &Atom, expr: &Atom, sub: Symbol) -> Atom {
6250    let simplified = rubi_simplify_integrand(&(factor * rubi_subst_for(expr, base, sub)), sub);
6251    rubi_extract_positive_numeric_fractional_power_factors(&simplified, sub)
6252}
6253
6254fn rubi_extract_positive_numeric_fractional_power_factors(expr: &Atom, x: Symbol) -> Atom {
6255    match expr.as_view() {
6256        AtomView::Pow(power) => {
6257            let base = rubi_extract_positive_numeric_fractional_power_factors(
6258                &power.get_base().to_owned(),
6259                x,
6260            );
6261            let exponent = rubi_extract_positive_numeric_fractional_power_factors(
6262                &power.get_exp().to_owned(),
6263                x,
6264            );
6265            if rationalq!(exponent) && !integerq!(exponent) {
6266                let base = rubi_recombine_simpler_polynomial_inverse_factors(&base, x);
6267                let (numeric, nonnumeric) = rubi_split_numeric_factor(&base);
6268                if numeric > 0 && numeric != Rational::from(1) {
6269                    return rational_atom(numeric).pow(&exponent) * nonnumeric.pow(exponent);
6270                }
6271                return base.pow(exponent);
6272            }
6273            base.pow(exponent)
6274        }
6275        AtomView::Add(add) => add
6276            .into_iter()
6277            .map(|term| rubi_extract_positive_numeric_fractional_power_factors(&term.to_owned(), x))
6278            .fold(Atom::num(0), |sum, term| sum + term),
6279        AtomView::Mul(mul) => mul
6280            .into_iter()
6281            .map(|factor| {
6282                rubi_extract_positive_numeric_fractional_power_factors(&factor.to_owned(), x)
6283            })
6284            .fold(Atom::num(1), |product, factor| product * factor),
6285        AtomView::Fun(function) => function.get_symbol().call_args(
6286            function
6287                .into_iter()
6288                .map(|argument| {
6289                    rubi_extract_positive_numeric_fractional_power_factors(&argument.to_owned(), x)
6290                })
6291                .collect::<Vec<_>>(),
6292        ),
6293        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
6294    }
6295}
6296
6297fn rubi_subst_for_trig_base(expr: &Atom, base: &Atom, sub: Symbol) -> Option<Atom> {
6298    let (symbol, argument) = rubi_trig_function(base)?;
6299    let sub = Atom::var(sub);
6300    let family = rubi_trig_symbol_family(symbol)?;
6301    let (sin, cos) = match family {
6302        RubiTrigFamily::Sin => (sub.to_owned(), (Atom::num(1) - sub.pow(2)).sqrt()),
6303        RubiTrigFamily::Cos => ((Atom::num(1) - sub.pow(2)).sqrt(), sub.to_owned()),
6304        RubiTrigFamily::Tan => {
6305            let denominator = (Atom::num(1) + sub.pow(2)).sqrt();
6306            (sub / &denominator, Atom::num(1) / denominator)
6307        }
6308        RubiTrigFamily::Cot => {
6309            let denominator = (Atom::num(1) + sub.pow(2)).sqrt();
6310            (Atom::num(1) / &denominator, sub / denominator)
6311        }
6312        RubiTrigFamily::Sec => (
6313            Atom::num(1) / (Atom::num(1) - sub.pow(2)).sqrt(),
6314            Atom::num(1) / sub,
6315        ),
6316        RubiTrigFamily::Csc => (
6317            Atom::num(1) / &sub,
6318            Atom::num(1) / (Atom::num(1) - sub.pow(2)).sqrt(),
6319        ),
6320    };
6321
6322    Some(rubi_subst_for_trig(expr, &sin, &cos, &argument))
6323}
6324
6325fn rubi_subst_for_hyperbolic_base(expr: &Atom, base: &Atom, sub: Symbol) -> Option<Atom> {
6326    let (symbol, argument) = rubi_hyperbolic_function(base)?;
6327    let sub = Atom::var(sub);
6328    let (sinh, cosh) = match symbol.get_stripped_ascii_name()? {
6329        "sinh" => (sub.to_owned(), (Atom::num(1) + sub.pow(2)).sqrt()),
6330        "cosh" => ((-Atom::num(1) + sub.pow(2)).sqrt(), sub.to_owned()),
6331        "tanh" => {
6332            let denominator = (Atom::num(1) - sub.pow(2)).sqrt();
6333            (sub / &denominator, Atom::num(1) / denominator)
6334        }
6335        "coth" => {
6336            let denominator = (-Atom::num(1) + sub.pow(2)).sqrt();
6337            (Atom::num(1) / &denominator, sub / denominator)
6338        }
6339        "sech" => (
6340            Atom::num(1) / (-Atom::num(1) + sub.pow(2)).sqrt(),
6341            Atom::num(1) / sub,
6342        ),
6343        "csch" => (
6344            Atom::num(1) / &sub,
6345            Atom::num(1) / (Atom::num(1) + sub.pow(2)).sqrt(),
6346        ),
6347        _ => return None,
6348    };
6349
6350    Some(rubi_subst_for_hyperbolic(expr, &sinh, &cosh, &argument))
6351}
6352
6353fn rubi_subst_for_aux(expr: &Atom, base: &Atom, sub: Symbol) -> Atom {
6354    if (expr - base).expand().is_zero() {
6355        return Atom::var(sub);
6356    }
6357
6358    if atom_q(expr.as_view()) {
6359        if let Some((base_inner, base_exponent)) = rubi_power_with_rational_exponent(base) {
6360            if (expr - &base_inner).expand().is_zero() {
6361                return Atom::var(sub).pow((Atom::num(1) / base_exponent).cancel());
6362            }
6363        }
6364        return expr.to_owned();
6365    }
6366
6367    match expr.as_view() {
6368        AtomView::Pow(power) => {
6369            let (power_base, power_exponent) = power.get_base_exp();
6370            let power_base = power_base.to_owned();
6371            let power_exponent = power_exponent.to_owned();
6372            if rationalq!(power_exponent) {
6373                if (power_base.to_owned() - base).expand().is_zero() {
6374                    return Atom::var(sub).pow(power_exponent);
6375                }
6376                if let Some((base_inner, base_exponent)) = rubi_power_with_rational_exponent(base) {
6377                    if (power_base.to_owned() - base_inner).expand().is_zero() {
6378                        return Atom::var(sub).pow((power_exponent / base_exponent).cancel());
6379                    }
6380                }
6381                return rubi_subst_for_aux(&power_base, base, sub).pow(power_exponent);
6382            }
6383
6384            rubi_subst_for_aux(&power_base, base, sub).pow(rubi_subst_for_aux(
6385                &power_exponent,
6386                base,
6387                sub,
6388            ))
6389        }
6390        AtomView::Add(add) => add
6391            .into_iter()
6392            .map(|term| rubi_subst_for_aux(&term.to_owned(), base, sub))
6393            .fold(Atom::num(0), |sum, term| sum + term),
6394        AtomView::Mul(mul) => mul
6395            .into_iter()
6396            .map(|factor| rubi_subst_for_aux(&factor.to_owned(), base, sub))
6397            .fold(Atom::num(1), |product, factor| product * factor),
6398        AtomView::Fun(fun) => fun.get_symbol().call_args(
6399            fun.into_iter()
6400                .map(|argument| rubi_subst_for_aux(&argument.to_owned(), base, sub)),
6401        ),
6402        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
6403    }
6404}
6405
6406fn rubi_power_with_rational_exponent(expr: &Atom) -> Option<(Atom, Atom)> {
6407    let AtomView::Pow(power) = expr.as_view() else {
6408        return None;
6409    };
6410    let (base, exponent) = power.get_base_exp();
6411    let exponent = exponent.to_owned();
6412    rationalq!(exponent).then(|| (base.to_owned(), exponent))
6413}
6414
6415#[cfg(test)]
6416fn rubi_subst_for_sin_trig(expr: &Atom, v: &Atom, free_factor: &Atom, sub: Symbol) -> Atom {
6417    let sin = free_factor * Atom::var(sub);
6418    let cos = (Atom::num(1) - sin.pow(2)).sqrt();
6419    rubi_subst_for_trig(expr, &sin, &cos, v)
6420}
6421
6422fn rubi_function_of_sin_trig_recur(expr: &Atom, v: &Atom, x: Symbol) -> bool {
6423    if atom_q(expr.as_view()) {
6424        return expr != &Atom::var(x);
6425    }
6426
6427    if let Some((symbol, argument)) = rubi_active_trig_function(expr) {
6428        if let Some(quotient) = rubi_integer_quotient(&argument, v) {
6429            return if quotient % 2 == 0 {
6430                rubi_cos_family_symbol(symbol)
6431            } else {
6432                rubi_sin_family_symbol(symbol)
6433            };
6434        }
6435
6436        return rubi_children(expr.as_view())
6437            .into_iter()
6438            .all(|child| rubi_function_of_sin_trig_recur(&child, v, x));
6439    }
6440
6441    if let AtomView::Pow(power) = expr.as_view() {
6442        let base = power.get_base().to_owned();
6443        let exponent = power.get_exp().to_owned();
6444        if let Some((_symbol, argument)) = rubi_active_trig_function(&base)
6445            && rubi_integer_quotient(&argument, v).is_some()
6446            && rubi_even_integer_atom_q(&exponent)
6447        {
6448            return true;
6449        }
6450        return rubi_function_of_sin_trig_recur(&base, v, x)
6451            && rubi_function_of_sin_trig_recur(&exponent, v, x);
6452    }
6453
6454    if rubi_product_q(expr) {
6455        if rubi_half_angle_sin_product_q(expr, v) {
6456            let remainder = rubi_drop_first_product_factors(expr, 2);
6457            return rubi_function_of_sin_trig_recur(&remainder, v, x);
6458        }
6459
6460        if let Some((argument, rest)) =
6461            rubi_find_trig_factor(expr, v, &[RubiTrigFamily::Sin, RubiTrigFamily::Csc], false)
6462            && rubi_integer_quotient(&argument, v).is_some_and(|quotient| quotient % 2 == 0)
6463        {
6464            let reduced = v.cos() * rest;
6465            let reduced = rubi_mathematica_trig_quotient(&reduced).unwrap_or(reduced);
6466            return rubi_function_of_sin_trig_recur(&reduced, v, x);
6467        }
6468
6469        if let Some((argument, rest)) =
6470            rubi_find_trig_factor(expr, v, &[RubiTrigFamily::Cos, RubiTrigFamily::Sec], false)
6471            && rubi_integer_quotient(&argument, v).is_some_and(|quotient| quotient % 2 != 0)
6472        {
6473            let reduced = v.cos() * rest;
6474            let reduced = rubi_mathematica_trig_quotient(&reduced).unwrap_or(reduced);
6475            return rubi_function_of_sin_trig_recur(&reduced, v, x);
6476        }
6477
6478        if let Some((_argument, rest)) =
6479            rubi_find_trig_factor(expr, v, &[RubiTrigFamily::Tan, RubiTrigFamily::Cot], true)
6480        {
6481            let reduced = v.cos() * rest;
6482            let reduced = rubi_mathematica_trig_quotient(&reduced).unwrap_or(reduced);
6483            return rubi_function_of_sin_trig_recur(&reduced, v, x);
6484        }
6485    }
6486
6487    rubi_children(expr.as_view())
6488        .into_iter()
6489        .all(|child| rubi_function_of_sin_trig_recur(&child, v, x))
6490}
6491
6492fn rubi_function_of_cos_trig_recur(expr: &Atom, v: &Atom, x: Symbol) -> bool {
6493    if atom_q(expr.as_view()) {
6494        return expr != &Atom::var(x);
6495    }
6496
6497    if let Some((symbol, argument)) = rubi_active_trig_function(expr) {
6498        if rubi_integer_quotient(&argument, v).is_some() {
6499            return rubi_cos_family_symbol(symbol);
6500        }
6501
6502        return rubi_children(expr.as_view())
6503            .into_iter()
6504            .all(|child| rubi_function_of_cos_trig_recur(&child, v, x));
6505    }
6506
6507    if let AtomView::Pow(power) = expr.as_view() {
6508        let base = power.get_base().to_owned();
6509        let exponent = power.get_exp().to_owned();
6510        if let Some((_symbol, argument)) = rubi_active_trig_function(&base)
6511            && rubi_integer_quotient(&argument, v).is_some()
6512            && rubi_even_integer_atom_q(&exponent)
6513        {
6514            return true;
6515        }
6516        return rubi_function_of_cos_trig_recur(&base, v, x)
6517            && rubi_function_of_cos_trig_recur(&exponent, v, x);
6518    }
6519
6520    if rubi_product_q(expr) {
6521        if let Some((_argument, rest)) =
6522            rubi_find_trig_factor(expr, v, &[RubiTrigFamily::Sin, RubiTrigFamily::Csc], false)
6523        {
6524            let reduced = v.sin() * rest;
6525            let reduced = rubi_mathematica_trig_quotient(&reduced).unwrap_or(reduced);
6526            return rubi_function_of_cos_trig_recur(&reduced, v, x);
6527        }
6528
6529        if let Some((_argument, rest)) =
6530            rubi_find_trig_factor(expr, v, &[RubiTrigFamily::Tan, RubiTrigFamily::Cot], true)
6531        {
6532            let reduced = v.sin() * rest;
6533            let reduced = rubi_mathematica_trig_quotient(&reduced).unwrap_or(reduced);
6534            return rubi_function_of_cos_trig_recur(&reduced, v, x);
6535        }
6536    }
6537
6538    rubi_children(expr.as_view())
6539        .into_iter()
6540        .all(|child| rubi_function_of_cos_trig_recur(&child, v, x))
6541}
6542
6543fn rubi_function_of_tan_trig_recur(expr: &Atom, v: &Atom, x: Symbol) -> bool {
6544    if atom_q(expr.as_view()) {
6545        return expr != &Atom::var(x);
6546    }
6547
6548    if let Some((symbol, argument)) = rubi_active_trig_function(expr) {
6549        if let Some(quotient) = rubi_integer_quotient(&argument, v) {
6550            return matches!(
6551                rubi_trig_symbol_family(symbol),
6552                Some(RubiTrigFamily::Tan | RubiTrigFamily::Cot)
6553            ) || quotient % 2 == 0;
6554        }
6555
6556        return rubi_children(expr.as_view())
6557            .into_iter()
6558            .all(|child| rubi_function_of_tan_trig_recur(&child, v, x));
6559    }
6560
6561    if let AtomView::Pow(power) = expr.as_view() {
6562        let base = power.get_base().to_owned();
6563        let exponent = power.get_exp().to_owned();
6564        if let Some((_symbol, argument)) = rubi_active_trig_function(&base)
6565            && rubi_integer_quotient(&argument, v).is_some()
6566            && rubi_even_integer_atom_q(&exponent)
6567        {
6568            return true;
6569        }
6570        if rubi_even_integer_atom_q(&exponent) && rubi_sum_q(&base) {
6571            return rubi_function_of_tan_trig_recur(&base.pow(2).expand(), v, x);
6572        }
6573        return rubi_function_of_tan_trig_recur(&base, v, x)
6574            && rubi_function_of_tan_trig_recur(&exponent, v, x);
6575    }
6576
6577    if rubi_product_q(expr) {
6578        let rejected: Vec<Atom> = rubi_product_factors(expr)
6579            .into_iter()
6580            .filter(|factor| !rubi_function_of_tan_trig_recur(factor, v, x))
6581            .collect();
6582        if rejected.is_empty() {
6583            return true;
6584        }
6585        return rejected.len() == 2
6586            && rubi_odd_trig_power_q(&rejected[0], v, x)
6587            && rubi_odd_trig_power_q(&rejected[1], v, x);
6588    }
6589
6590    rubi_children(expr.as_view())
6591        .into_iter()
6592        .all(|child| rubi_function_of_tan_trig_recur(&child, v, x))
6593}
6594
6595fn rubi_odd_trig_power_q(expr: &Atom, v: &Atom, x: Symbol) -> bool {
6596    if let Some((symbol, argument)) = rubi_active_trig_function(expr) {
6597        return !matches!(
6598            rubi_trig_symbol_family(symbol),
6599            Some(RubiTrigFamily::Tan | RubiTrigFamily::Cot)
6600        ) && rubi_odd_quotient_q(&argument, v);
6601    }
6602
6603    if let AtomView::Pow(power) = expr.as_view() {
6604        let exponent = power.get_exp().to_owned();
6605        return rubi_integer_atom(&exponent).is_some_and(|n| n % 2 != 0)
6606            && rubi_odd_trig_power_q(&power.get_base().to_owned(), v, x);
6607    }
6608
6609    if rubi_product_q(expr) {
6610        let nonfree = rubi_nonfree_factors(expr, x);
6611        if nonfree != *expr {
6612            return rubi_odd_trig_power_q(&nonfree, v, x);
6613        }
6614
6615        let rejected: Vec<Atom> = rubi_product_factors(expr)
6616            .into_iter()
6617            .filter(|factor| !rubi_function_of_tan_trig_recur(factor, v, x))
6618            .collect();
6619        return rejected.is_empty()
6620            || (rejected.len() == 1 && rubi_odd_trig_power_q(&rejected[0], v, x));
6621    }
6622
6623    if rubi_sum_q(expr) {
6624        return rubi_children(expr.as_view())
6625            .into_iter()
6626            .all(|child| rubi_odd_trig_power_q(&child, v, x));
6627    }
6628
6629    false
6630}
6631
6632fn rubi_pure_function_of_trig_family_recur(
6633    expr: &Atom,
6634    v: &Atom,
6635    x: Symbol,
6636    allowed_families: &[RubiTrigFamily],
6637) -> bool {
6638    if atom_q(expr.as_view()) {
6639        return expr != &Atom::var(x);
6640    }
6641
6642    if let Some((symbol, argument)) = rubi_active_trig_function(expr)
6643        && eqq!(argument, v)
6644    {
6645        return rubi_trig_symbol_family(symbol)
6646            .is_some_and(|family| allowed_families.contains(&family));
6647    }
6648
6649    if matches!(expr.as_view(), AtomView::Fun(function) if rubi_calculus_function_symbol(function.get_symbol()))
6650    {
6651        return false;
6652    }
6653
6654    rubi_children(expr.as_view())
6655        .into_iter()
6656        .all(|child| rubi_pure_function_of_trig_family_recur(&child, v, x, allowed_families))
6657}
6658
6659fn rubi_pure_function_of_hyperbolic_family_recur(
6660    expr: &Atom,
6661    v: &Atom,
6662    x: Symbol,
6663    allowed_names: &[&str],
6664) -> bool {
6665    if atom_q(expr.as_view()) {
6666        return expr != &Atom::var(x);
6667    }
6668
6669    if let Some((symbol, argument)) = rubi_hyperbolic_function(expr)
6670        && eqq!(argument, v)
6671    {
6672        return symbol
6673            .get_stripped_ascii_name()
6674            .is_some_and(|name| allowed_names.contains(&name));
6675    }
6676
6677    if matches!(expr.as_view(), AtomView::Fun(function) if rubi_calculus_function_symbol(function.get_symbol()))
6678    {
6679        return false;
6680    }
6681
6682    rubi_children(expr.as_view())
6683        .into_iter()
6684        .all(|child| rubi_pure_function_of_hyperbolic_family_recur(&child, v, x, allowed_names))
6685}
6686
6687fn rubi_function_of_sinh_hyperbolic_recur(expr: &Atom, v: &Atom, x: Symbol) -> bool {
6688    if atom_q(expr.as_view()) {
6689        return expr != &Atom::var(x);
6690    }
6691
6692    if matches!(expr.as_view(), AtomView::Fun(function) if rubi_calculus_function_symbol(function.get_symbol()))
6693    {
6694        return false;
6695    }
6696
6697    if let Some((symbol, argument)) = rubi_hyperbolic_function(expr) {
6698        let Some(quotient) = rubi_integer_quotient(&argument, v) else {
6699            return false;
6700        };
6701        return if quotient % 2 == 0 {
6702            rubi_cosh_family_symbol(symbol)
6703        } else {
6704            rubi_sinh_family_symbol(symbol)
6705        };
6706    }
6707
6708    if let AtomView::Pow(power) = expr.as_view() {
6709        let base = power.get_base().to_owned();
6710        let exponent = power.get_exp().to_owned();
6711        if let Some((_symbol, argument)) = rubi_hyperbolic_function(&base)
6712            && rubi_integer_quotient(&argument, v).is_some()
6713            && rubi_even_integer_atom_q(&exponent)
6714        {
6715            return true;
6716        }
6717        return rubi_function_of_sinh_hyperbolic_recur(&base, v, x)
6718            && rubi_function_of_sinh_hyperbolic_recur(&exponent, v, x);
6719    }
6720
6721    if rubi_product_q(expr) {
6722        if rubi_half_angle_sinh_product_q(expr, v) {
6723            let remainder = rubi_drop_first_product_factors(expr, 2);
6724            return rubi_function_of_sinh_hyperbolic_recur(&remainder, v, x);
6725        }
6726
6727        if let Some((argument, rest)) =
6728            rubi_find_hyperbolic_factor(expr, v, &[RubiTrigFamily::Sin, RubiTrigFamily::Csc], false)
6729            && rubi_integer_quotient(&argument, v).is_some_and(|quotient| quotient % 2 == 0)
6730        {
6731            return rubi_function_of_sinh_hyperbolic_recur(&(v.cosh() * rest), v, x);
6732        }
6733
6734        if let Some((argument, rest)) =
6735            rubi_find_hyperbolic_factor(expr, v, &[RubiTrigFamily::Cos, RubiTrigFamily::Sec], false)
6736            && rubi_integer_quotient(&argument, v).is_some_and(|quotient| quotient % 2 != 0)
6737        {
6738            return rubi_function_of_sinh_hyperbolic_recur(&(v.cosh() * rest), v, x);
6739        }
6740
6741        if let Some((_argument, rest)) =
6742            rubi_find_hyperbolic_factor(expr, v, &[RubiTrigFamily::Tan, RubiTrigFamily::Cot], true)
6743        {
6744            return rubi_function_of_sinh_hyperbolic_recur(&(v.cosh() * rest), v, x);
6745        }
6746    }
6747
6748    rubi_children(expr.as_view())
6749        .into_iter()
6750        .all(|child| rubi_function_of_sinh_hyperbolic_recur(&child, v, x))
6751}
6752
6753fn rubi_function_of_cosh_hyperbolic_recur(expr: &Atom, v: &Atom, x: Symbol) -> bool {
6754    if atom_q(expr.as_view()) {
6755        return expr != &Atom::var(x);
6756    }
6757
6758    if matches!(expr.as_view(), AtomView::Fun(function) if rubi_calculus_function_symbol(function.get_symbol()))
6759    {
6760        return false;
6761    }
6762
6763    if let Some((symbol, argument)) = rubi_hyperbolic_function(expr) {
6764        let Some(_quotient) = rubi_integer_quotient(&argument, v) else {
6765            return false;
6766        };
6767        return rubi_cosh_family_symbol(symbol);
6768    }
6769
6770    if let AtomView::Pow(power) = expr.as_view() {
6771        let base = power.get_base().to_owned();
6772        let exponent = power.get_exp().to_owned();
6773        if let Some((_symbol, argument)) = rubi_hyperbolic_function(&base)
6774            && rubi_integer_quotient(&argument, v).is_some()
6775            && rubi_even_integer_atom_q(&exponent)
6776        {
6777            return true;
6778        }
6779        return rubi_function_of_cosh_hyperbolic_recur(&base, v, x)
6780            && rubi_function_of_cosh_hyperbolic_recur(&exponent, v, x);
6781    }
6782
6783    if rubi_product_q(expr) {
6784        if let Some((_argument, rest)) =
6785            rubi_find_hyperbolic_factor(expr, v, &[RubiTrigFamily::Sin, RubiTrigFamily::Csc], false)
6786        {
6787            return rubi_function_of_cosh_hyperbolic_recur(&(v.sinh() * rest), v, x);
6788        }
6789
6790        if let Some((_argument, rest)) =
6791            rubi_find_hyperbolic_factor(expr, v, &[RubiTrigFamily::Tan, RubiTrigFamily::Cot], true)
6792        {
6793            return rubi_function_of_cosh_hyperbolic_recur(&(v.sinh() * rest), v, x);
6794        }
6795    }
6796
6797    rubi_children(expr.as_view())
6798        .into_iter()
6799        .all(|child| rubi_function_of_cosh_hyperbolic_recur(&child, v, x))
6800}
6801
6802fn rubi_function_of_tanh_hyperbolic_recur(expr: &Atom, v: &Atom, x: Symbol) -> bool {
6803    if atom_q(expr.as_view()) {
6804        return expr != &Atom::var(x);
6805    }
6806
6807    if let Some((symbol, argument)) = rubi_hyperbolic_function(expr) {
6808        if let Some(quotient) = rubi_integer_quotient(&argument, v) {
6809            return rubi_tanh_family_symbol(symbol) || quotient % 2 == 0;
6810        }
6811
6812        return rubi_children(expr.as_view())
6813            .into_iter()
6814            .all(|child| rubi_function_of_tanh_hyperbolic_recur(&child, v, x));
6815    }
6816
6817    if let AtomView::Pow(power) = expr.as_view() {
6818        let base = power.get_base().to_owned();
6819        let exponent = power.get_exp().to_owned();
6820        if let Some((_symbol, argument)) = rubi_hyperbolic_function(&base)
6821            && rubi_integer_quotient(&argument, v).is_some()
6822            && rubi_even_integer_atom_q(&exponent)
6823        {
6824            return true;
6825        }
6826        if rubi_even_integer_atom_q(&exponent) && rubi_sum_q(&base) {
6827            return rubi_function_of_tanh_hyperbolic_recur(&base.pow(2).expand(), v, x);
6828        }
6829        return rubi_function_of_tanh_hyperbolic_recur(&base, v, x)
6830            && rubi_function_of_tanh_hyperbolic_recur(&exponent, v, x);
6831    }
6832
6833    if rubi_product_q(expr) {
6834        let rejected: Vec<Atom> = rubi_product_factors(expr)
6835            .into_iter()
6836            .filter(|factor| !rubi_function_of_tanh_hyperbolic_recur(factor, v, x))
6837            .collect();
6838        if rejected.is_empty() {
6839            return true;
6840        }
6841        return rejected.len() == 2
6842            && rubi_odd_hyperbolic_power_q(&rejected[0], v, x)
6843            && rubi_odd_hyperbolic_power_q(&rejected[1], v, x);
6844    }
6845
6846    rubi_children(expr.as_view())
6847        .into_iter()
6848        .all(|child| rubi_function_of_tanh_hyperbolic_recur(&child, v, x))
6849}
6850
6851fn rubi_odd_hyperbolic_power_q(expr: &Atom, v: &Atom, x: Symbol) -> bool {
6852    if let Some((symbol, argument)) = rubi_hyperbolic_function(expr) {
6853        return !rubi_tanh_family_symbol(symbol) && rubi_odd_quotient_q(&argument, v);
6854    }
6855
6856    if let AtomView::Pow(power) = expr.as_view() {
6857        let exponent = power.get_exp().to_owned();
6858        return rubi_integer_atom(&exponent).is_some_and(|n| n % 2 != 0)
6859            && rubi_odd_hyperbolic_power_q(&power.get_base().to_owned(), v, x);
6860    }
6861
6862    if rubi_product_q(expr) {
6863        let nonfree = rubi_nonfree_factors(expr, x);
6864        if nonfree != *expr {
6865            return rubi_odd_hyperbolic_power_q(&nonfree, v, x);
6866        }
6867
6868        let rejected: Vec<Atom> = rubi_product_factors(expr)
6869            .into_iter()
6870            .filter(|factor| !rubi_function_of_tanh_hyperbolic_recur(factor, v, x))
6871            .collect();
6872        return rejected.is_empty()
6873            || (rejected.len() == 1 && rubi_odd_hyperbolic_power_q(&rejected[0], v, x));
6874    }
6875
6876    if rubi_sum_q(expr) {
6877        return rubi_children(expr.as_view())
6878            .into_iter()
6879            .all(|child| rubi_odd_hyperbolic_power_q(&child, v, x));
6880    }
6881
6882    false
6883}
6884
6885fn rubi_odd_quotient_q(argument: &Atom, v: &Atom) -> bool {
6886    rubi_integer_quotient(argument, v).is_some_and(|quotient| quotient % 2 != 0)
6887}
6888
6889fn rubi_hyperbolic_function(expr: &Atom) -> Option<(Symbol, Atom)> {
6890    let AtomView::Fun(function) = expr.as_view() else {
6891        return None;
6892    };
6893    if function.get_nargs() != 1 || !rubi_hyperbolic_function_symbol(function.get_symbol()) {
6894        return None;
6895    }
6896
6897    Some((function.get_symbol(), function.get(0).to_owned()))
6898}
6899
6900#[derive(Clone, Copy, PartialEq, Eq)]
6901/// Trigonometric function families recognized by Rubi predicates.
6902enum RubiTrigFamily {
6903    Sin,
6904    Cos,
6905    Tan,
6906    Cot,
6907    Sec,
6908    Csc,
6909}
6910
6911fn rubi_trig_function(expr: &Atom) -> Option<(Symbol, Atom)> {
6912    let AtomView::Fun(function) = expr.as_view() else {
6913        return None;
6914    };
6915    if function.get_nargs() != 1 || rubi_trig_symbol_family(function.get_symbol()).is_none() {
6916        return None;
6917    }
6918
6919    Some((function.get_symbol(), function.get(0).to_owned()))
6920}
6921
6922fn rubi_active_trig_function(expr: &Atom) -> Option<(Symbol, Atom)> {
6923    let (symbol, argument) = rubi_trig_function(expr)?;
6924    rubi_builtin_trig_symbol_q(symbol).then_some((symbol, argument))
6925}
6926
6927fn rubi_trig_symbol_family(symbol: Symbol) -> Option<RubiTrigFamily> {
6928    let symbols = rubi_symbols();
6929    if symbol == symbols.inert_sin {
6930        Some(RubiTrigFamily::Sin)
6931    } else if symbol == symbols.inert_cos {
6932        Some(RubiTrigFamily::Cos)
6933    } else if symbol == symbols.inert_tan {
6934        Some(RubiTrigFamily::Tan)
6935    } else if symbol == symbols.inert_cot {
6936        Some(RubiTrigFamily::Cot)
6937    } else if symbol == symbols.inert_sec {
6938        Some(RubiTrigFamily::Sec)
6939    } else if symbol == symbols.inert_csc {
6940        Some(RubiTrigFamily::Csc)
6941    } else {
6942        match symbol.get_stripped_ascii_name()? {
6943            "sin" => Some(RubiTrigFamily::Sin),
6944            "cos" => Some(RubiTrigFamily::Cos),
6945            "tan" => Some(RubiTrigFamily::Tan),
6946            "cot" => Some(RubiTrigFamily::Cot),
6947            "sec" => Some(RubiTrigFamily::Sec),
6948            "csc" => Some(RubiTrigFamily::Csc),
6949            _ => None,
6950        }
6951    }
6952}
6953
6954fn rubi_sin_family_symbol(symbol: Symbol) -> bool {
6955    matches!(
6956        rubi_trig_symbol_family(symbol),
6957        Some(RubiTrigFamily::Sin | RubiTrigFamily::Csc)
6958    )
6959}
6960
6961fn rubi_cos_family_symbol(symbol: Symbol) -> bool {
6962    matches!(
6963        rubi_trig_symbol_family(symbol),
6964        Some(RubiTrigFamily::Cos | RubiTrigFamily::Sec)
6965    )
6966}
6967
6968fn rubi_find_trig_factor(
6969    expr: &Atom,
6970    v: &Atom,
6971    families: &[RubiTrigFamily],
6972    allow_same_argument: bool,
6973) -> Option<(Atom, Atom)> {
6974    rubi_split_product(
6975        |factor| rubi_trig_factor_matches(factor, v, families, allow_same_argument).is_some(),
6976        expr,
6977    )
6978    .and_then(|(factor, rest)| {
6979        let (argument, _degree) =
6980            rubi_trig_factor_matches(&factor, v, families, allow_same_argument)?;
6981        Some((argument, rest))
6982    })
6983}
6984
6985fn rubi_trig_factor_matches(
6986    factor: &Atom,
6987    v: &Atom,
6988    families: &[RubiTrigFamily],
6989    allow_same_argument: bool,
6990) -> Option<(Atom, i64)> {
6991    let (base, degree) = match factor.as_view() {
6992        AtomView::Pow(power) => {
6993            let degree = rubi_integer_atom(&power.get_exp().to_owned())?;
6994            (power.get_base().to_owned(), degree)
6995        }
6996        _ => (factor.to_owned(), 1),
6997    };
6998    if degree % 2 == 0 {
6999        return None;
7000    }
7001
7002    let (symbol, argument) = rubi_active_trig_function(&base)?;
7003    let family = rubi_trig_symbol_family(symbol)?;
7004    if !families.contains(&family) || rubi_integer_quotient(&argument, v).is_none() {
7005        return None;
7006    }
7007    if !allow_same_argument && eqq!(argument, v) {
7008        return None;
7009    }
7010
7011    Some((argument, degree))
7012}
7013
7014fn rubi_find_hyperbolic_factor(
7015    expr: &Atom,
7016    v: &Atom,
7017    families: &[RubiTrigFamily],
7018    allow_same_argument: bool,
7019) -> Option<(Atom, Atom)> {
7020    rubi_split_product(
7021        |factor| rubi_hyperbolic_factor_matches(factor, v, families, allow_same_argument).is_some(),
7022        expr,
7023    )
7024    .and_then(|(factor, rest)| {
7025        let (argument, _degree) =
7026            rubi_hyperbolic_factor_matches(&factor, v, families, allow_same_argument)?;
7027        Some((argument, rest))
7028    })
7029}
7030
7031fn rubi_hyperbolic_factor_matches(
7032    factor: &Atom,
7033    v: &Atom,
7034    families: &[RubiTrigFamily],
7035    allow_same_argument: bool,
7036) -> Option<(Atom, i64)> {
7037    let (base, degree) = match factor.as_view() {
7038        AtomView::Pow(power) => {
7039            let degree = rubi_integer_atom(&power.get_exp().to_owned())?;
7040            (power.get_base().to_owned(), degree)
7041        }
7042        _ => (factor.to_owned(), 1),
7043    };
7044    if degree % 2 == 0 {
7045        return None;
7046    }
7047
7048    let (symbol, argument) = rubi_hyperbolic_function(&base)?;
7049    let family = rubi_hyperbolic_symbol_family(symbol)?;
7050    if !families.contains(&family) || rubi_integer_quotient(&argument, v).is_none() {
7051        return None;
7052    }
7053    if !allow_same_argument && eqq!(argument, v) {
7054        return None;
7055    }
7056
7057    Some((argument, degree))
7058}
7059
7060fn rubi_integer_atom(expr: &Atom) -> Option<i64> {
7061    let (numerator, denominator) = rational_number(expr)?;
7062    (denominator == 1).then_some(numerator)
7063}
7064
7065fn rubi_half_angle_sin_product_q(expr: &Atom, v: &Atom) -> bool {
7066    match expr.as_view() {
7067        AtomView::Mul(mul) => {
7068            let factors: Vec<Atom> = mul.into_iter().map(|factor| factor.to_owned()).collect();
7069            rubi_half_angle_sin_product_factors_q(&factors, v)
7070        }
7071        _ => false,
7072    }
7073}
7074
7075fn rubi_half_angle_sinh_product_q(expr: &Atom, v: &Atom) -> bool {
7076    let AtomView::Mul(mul) = expr.as_view() else {
7077        return false;
7078    };
7079    let factors: Vec<Atom> = mul.into_iter().map(|factor| factor.to_owned()).collect();
7080    if factors.len() < 2 {
7081        return false;
7082    }
7083
7084    matches!(
7085        (
7086            rubi_hyperbolic_function(&factors[0]),
7087            rubi_hyperbolic_function(&factors[1]),
7088        ),
7089        (Some((symbol1, argument1)), Some((symbol2, argument2)))
7090            if rubi_hyperbolic_symbol_family(symbol1) == Some(RubiTrigFamily::Cos)
7091                && rubi_hyperbolic_symbol_family(symbol2) == Some(RubiTrigFamily::Sin)
7092                && eqq!(argument1, v / 2)
7093                && eqq!(argument2, v / 2)
7094    )
7095}
7096
7097fn rubi_half_angle_sin_product_factors_q(factors: &[Atom], v: &Atom) -> bool {
7098    if factors.len() < 2 {
7099        return false;
7100    }
7101
7102    matches!(
7103        (
7104            rubi_active_trig_function(&factors[0]),
7105            rubi_active_trig_function(&factors[1]),
7106        ),
7107        (Some((symbol1, argument1)), Some((symbol2, argument2)))
7108            if rubi_trig_symbol_family(symbol1) == Some(RubiTrigFamily::Cos)
7109                && rubi_trig_symbol_family(symbol2) == Some(RubiTrigFamily::Sin)
7110                && eqq!(argument1, v / 2)
7111                && eqq!(argument2, v / 2)
7112    )
7113}
7114
7115fn rubi_drop_first_product_factors(expr: &Atom, count: usize) -> Atom {
7116    match expr.as_view() {
7117        AtomView::Mul(mul) => {
7118            let factors: Vec<Atom> = mul.into_iter().map(|factor| factor.to_owned()).collect();
7119            product_atoms(&factors[count.min(factors.len())..])
7120        }
7121        _ if count == 0 => expr.to_owned(),
7122        _ => Atom::num(1),
7123    }
7124}
7125
7126fn rubi_sinh_family_symbol(symbol: Symbol) -> bool {
7127    matches!(symbol.get_stripped_ascii_name(), Some("sinh" | "csch"))
7128}
7129
7130fn rubi_cosh_family_symbol(symbol: Symbol) -> bool {
7131    matches!(symbol.get_stripped_ascii_name(), Some("cosh" | "sech"))
7132}
7133
7134fn rubi_tanh_family_symbol(symbol: Symbol) -> bool {
7135    matches!(symbol.get_stripped_ascii_name(), Some("tanh" | "coth"))
7136}
7137
7138fn rubi_even_integer_atom_q(expr: &Atom) -> bool {
7139    rational_number(expr)
7140        .is_some_and(|(numerator, denominator)| denominator == 1 && numerator % 2 == 0)
7141}
7142
7143fn rubi_subst_for_hyperbolic(expr: &Atom, sinh: &Atom, cosh: &Atom, v: &Atom) -> Atom {
7144    match expr.as_view() {
7145        AtomView::Fun(function) if function.get_nargs() == 1 => {
7146            let symbol = function.get_symbol();
7147            let argument = function.get(0).to_owned();
7148            if rubi_hyperbolic_function_symbol(symbol)
7149                && let Some(quotient) = rubi_integer_quotient(&argument, v)
7150            {
7151                return rubi_subst_for_hyperbolic_function(symbol, quotient, sinh, cosh);
7152            }
7153
7154            let args: Vec<_> = function
7155                .into_iter()
7156                .map(|argument| rubi_subst_for_hyperbolic(&argument.to_owned(), sinh, cosh, v))
7157                .collect();
7158            symbol.call_args(args)
7159        }
7160        AtomView::Fun(function) => {
7161            let args: Vec<_> = function
7162                .into_iter()
7163                .map(|argument| rubi_subst_for_hyperbolic(&argument.to_owned(), sinh, cosh, v))
7164                .collect();
7165            function.get_symbol().call_args(args)
7166        }
7167        AtomView::Pow(power) => {
7168            let base = rubi_subst_for_hyperbolic(&power.get_base().to_owned(), sinh, cosh, v);
7169            let exponent = rubi_subst_for_hyperbolic(&power.get_exp().to_owned(), sinh, cosh, v);
7170            base.pow(exponent)
7171        }
7172        AtomView::Mul(mul) => mul
7173            .into_iter()
7174            .map(|factor| rubi_subst_for_hyperbolic(&factor.to_owned(), sinh, cosh, v))
7175            .fold(Atom::num(1), |product, factor| product * factor),
7176        AtomView::Add(add) => add
7177            .into_iter()
7178            .map(|term| rubi_subst_for_hyperbolic(&term.to_owned(), sinh, cosh, v))
7179            .fold(Atom::num(0), |sum, term| sum + term),
7180        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
7181    }
7182}
7183
7184fn rubi_subst_for_hyperbolic_function(
7185    symbol: Symbol,
7186    quotient: i64,
7187    sinh: &Atom,
7188    cosh: &Atom,
7189) -> Atom {
7190    let (multiple_sinh, multiple_cosh) = rubi_sinh_cosh_integer_multiple(quotient, sinh, cosh);
7191
7192    if matches!(symbol.get_stripped_ascii_name(), Some("sinh")) {
7193        multiple_sinh
7194    } else if matches!(symbol.get_stripped_ascii_name(), Some("cosh")) {
7195        multiple_cosh
7196    } else if matches!(symbol.get_stripped_ascii_name(), Some("tanh")) {
7197        multiple_sinh / multiple_cosh
7198    } else if matches!(symbol.get_stripped_ascii_name(), Some("coth")) {
7199        multiple_cosh / multiple_sinh
7200    } else if matches!(symbol.get_stripped_ascii_name(), Some("sech")) {
7201        Atom::num(1) / multiple_cosh
7202    } else if matches!(symbol.get_stripped_ascii_name(), Some("csch")) {
7203        Atom::num(1) / multiple_sinh
7204    } else {
7205        unreachable!("rubi_subst_for_hyperbolic_function is only called for hyperbolic heads")
7206    }
7207}
7208
7209fn rubi_sinh_cosh_integer_multiple(quotient: i64, sinh: &Atom, cosh: &Atom) -> (Atom, Atom) {
7210    if quotient == 0 {
7211        return (Atom::num(0), Atom::num(1));
7212    }
7213
7214    let sign = if quotient < 0 { -1 } else { 1 };
7215    let mut current_sinh = Atom::num(0);
7216    let mut current_cosh = Atom::num(1);
7217    for _ in 0..quotient.abs() {
7218        let next_sinh = &current_sinh * cosh + &current_cosh * sinh;
7219        let next_cosh = &current_cosh * cosh + &current_sinh * sinh;
7220        // Mathematica's SubstForHyperbolic applies TrigExpand to an integer
7221        // multiple before substituting Sinh[v] and Cosh[v].
7222        current_sinh = next_sinh.expand();
7223        current_cosh = next_cosh.expand();
7224    }
7225
7226    if sign < 0 {
7227        current_sinh = -current_sinh;
7228    }
7229
7230    (current_sinh, current_cosh)
7231}
7232
7233fn rubi_integer_quotient(argument: &Atom, v: &Atom) -> Option<i64> {
7234    let quotient = (argument / v).expand().cancel();
7235    let (numerator, denominator) = rational_number(&quotient)?;
7236    (denominator == 1).then_some(numerator)
7237}
7238
7239fn rubi_subst_for_trig(expr: &Atom, sin: &Atom, cos: &Atom, v: &Atom) -> Atom {
7240    match expr.as_view() {
7241        AtomView::Fun(function) if function.get_nargs() == 1 => {
7242            let symbol = function.get_symbol();
7243            let argument = function.get(0).to_owned();
7244            if rubi_inert_or_builtin_trig_symbol_q(symbol)
7245                && let Some(quotient) = rubi_integer_quotient(&argument, v)
7246            {
7247                return rubi_subst_for_trig_function(symbol, quotient, sin, cos);
7248            }
7249
7250            let args: Vec<_> = function
7251                .into_iter()
7252                .map(|argument| rubi_subst_for_trig(&argument.to_owned(), sin, cos, v))
7253                .collect();
7254            symbol.call_args(args)
7255        }
7256        AtomView::Fun(function) => {
7257            let args: Vec<_> = function
7258                .into_iter()
7259                .map(|argument| rubi_subst_for_trig(&argument.to_owned(), sin, cos, v))
7260                .collect();
7261            function.get_symbol().call_args(args)
7262        }
7263        AtomView::Pow(power) => {
7264            let base = rubi_subst_for_trig(&power.get_base().to_owned(), sin, cos, v);
7265            let exponent = rubi_subst_for_trig(&power.get_exp().to_owned(), sin, cos, v);
7266            base.pow(exponent)
7267        }
7268        AtomView::Mul(mul) => {
7269            let factors: Vec<Atom> = mul.into_iter().map(|factor| factor.to_owned()).collect();
7270            if rubi_half_angle_sin_product_factors_q(&factors, v) {
7271                return sin * rubi_subst_for_trig(&product_atoms(&factors[2..]), sin, cos, v) / 2;
7272            }
7273
7274            factors
7275                .into_iter()
7276                .map(|factor| rubi_subst_for_trig(&factor, sin, cos, v))
7277                .fold(Atom::num(1), |product, factor| product * factor)
7278        }
7279        AtomView::Add(add) => add
7280            .into_iter()
7281            .map(|term| rubi_subst_for_trig(&term.to_owned(), sin, cos, v))
7282            .fold(Atom::num(0), |sum, term| sum + term),
7283        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
7284    }
7285}
7286
7287fn rubi_subst_for_trig_function(symbol: Symbol, quotient: i64, sin: &Atom, cos: &Atom) -> Atom {
7288    let (multiple_sin, multiple_cos) = rubi_sin_cos_integer_multiple(quotient, sin, cos);
7289    let family = rubi_trig_symbol_family(symbol)
7290        .expect("rubi_subst_for_trig_function is only called for trig heads");
7291
7292    match family {
7293        RubiTrigFamily::Sin => multiple_sin,
7294        RubiTrigFamily::Cos => multiple_cos,
7295        RubiTrigFamily::Tan => multiple_sin / multiple_cos,
7296        RubiTrigFamily::Cot => multiple_cos / multiple_sin,
7297        RubiTrigFamily::Sec => Atom::num(1) / multiple_cos,
7298        RubiTrigFamily::Csc => Atom::num(1) / multiple_sin,
7299    }
7300}
7301
7302fn rubi_sin_cos_integer_multiple(quotient: i64, sin: &Atom, cos: &Atom) -> (Atom, Atom) {
7303    if quotient == 0 {
7304        return (Atom::num(0), Atom::num(1));
7305    }
7306
7307    let sign = if quotient < 0 { -1 } else { 1 };
7308    let mut current_sin = Atom::num(0);
7309    let mut current_cos = Atom::num(1);
7310    for _ in 0..quotient.abs() {
7311        let next_sin = &current_sin * cos + &current_cos * sin;
7312        let next_cos = &current_cos * cos - &current_sin * sin;
7313        current_sin = next_sin.expand();
7314        current_cos = next_cos.expand();
7315    }
7316
7317    if sign < 0 {
7318        (-current_sin, current_cos)
7319    } else {
7320        (current_sin, current_cos)
7321    }
7322}
7323
7324fn rubi_function_of_q(base: &Atom, expr: &Atom, x: Symbol) -> bool {
7325    if is_free_of(expr, x) {
7326        return false;
7327    }
7328    if atom_q(base.as_view()) {
7329        return true;
7330    }
7331    if !rubi_inert_trig_free_q(expr) {
7332        return rubi_function_of_q(base, &rubi_activate_trig(expr), x);
7333    }
7334
7335    let nonfree_base = rubi_nonfree_factors(base, x);
7336    if nonfree_base != *base {
7337        return rubi_function_of_q(&nonfree_base, expr, x);
7338    }
7339
7340    if let Some((symbol, argument)) = rubi_active_trig_function(base) {
7341        return match rubi_trig_symbol_family(symbol) {
7342            Some(RubiTrigFamily::Sin | RubiTrigFamily::Csc) => {
7343                rubi_function_of_sin_trig_recur(expr, &argument, x)
7344            }
7345            Some(RubiTrigFamily::Cos | RubiTrigFamily::Sec) => {
7346                rubi_function_of_cos_trig_recur(expr, &argument, x)
7347            }
7348            Some(RubiTrigFamily::Tan | RubiTrigFamily::Cot) => {
7349                rubi_function_of_tan_trig_recur(expr, &argument, x)
7350            }
7351            _ => rubi_function_of_expn_q(expr, base, x).is_some(),
7352        };
7353    }
7354
7355    if let Some((symbol, argument)) = rubi_hyperbolic_function(base) {
7356        return match symbol.get_stripped_ascii_name() {
7357            Some("sinh" | "csch") => rubi_function_of_sinh_hyperbolic_recur(expr, &argument, x),
7358            Some("cosh" | "sech") => rubi_function_of_cosh_hyperbolic_recur(expr, &argument, x),
7359            Some("tanh" | "coth") => rubi_function_of_tanh_hyperbolic_recur(expr, &argument, x),
7360            _ => rubi_function_of_expn_q(expr, base, x).is_some(),
7361        };
7362    }
7363
7364    rubi_function_of_expn_q(expr, base, x).is_some()
7365}
7366
7367fn rubi_pure_function_of_q(base: &Atom, expr: &Atom, x: Symbol) -> bool {
7368    if is_free_of(expr, x) {
7369        return false;
7370    }
7371
7372    if atom_q(base.as_view()) {
7373        return true;
7374    }
7375
7376    if !rubi_inert_trig_free_q(expr) {
7377        return rubi_pure_function_of_q(base, &rubi_activate_trig(expr), x);
7378    }
7379
7380    let nonfree_base = rubi_nonfree_factors(base, x);
7381    if nonfree_base != *base {
7382        return rubi_pure_function_of_q(&nonfree_base, expr, x);
7383    }
7384
7385    if let Some((symbol, argument)) = rubi_active_trig_function(base) {
7386        return match rubi_trig_symbol_family(symbol) {
7387            Some(RubiTrigFamily::Sin) => rubi_pure_function_of_trig_family_recur(
7388                expr,
7389                &argument,
7390                x,
7391                &[RubiTrigFamily::Sin, RubiTrigFamily::Csc],
7392            ),
7393            Some(RubiTrigFamily::Cos) => rubi_pure_function_of_trig_family_recur(
7394                expr,
7395                &argument,
7396                x,
7397                &[RubiTrigFamily::Cos, RubiTrigFamily::Sec],
7398            ),
7399            Some(RubiTrigFamily::Tan) => rubi_pure_function_of_trig_family_recur(
7400                expr,
7401                &argument,
7402                x,
7403                &[RubiTrigFamily::Tan, RubiTrigFamily::Cot],
7404            ),
7405            Some(RubiTrigFamily::Cot) => {
7406                rubi_pure_function_of_trig_family_recur(expr, &argument, x, &[RubiTrigFamily::Cot])
7407            }
7408            Some(RubiTrigFamily::Sec) => rubi_pure_function_of_trig_family_recur(
7409                expr,
7410                &argument,
7411                x,
7412                &[RubiTrigFamily::Cos, RubiTrigFamily::Sec],
7413            ),
7414            Some(RubiTrigFamily::Csc) => rubi_pure_function_of_trig_family_recur(
7415                expr,
7416                &argument,
7417                x,
7418                &[RubiTrigFamily::Sin, RubiTrigFamily::Csc],
7419            ),
7420            _ => rubi_function_of_expn_q(expr, base, x).is_some(),
7421        };
7422    }
7423
7424    if let Some((symbol, argument)) = rubi_hyperbolic_function(base) {
7425        return match symbol.get_stripped_ascii_name() {
7426            Some("sinh") => {
7427                rubi_pure_function_of_hyperbolic_family_recur(expr, &argument, x, &["sinh", "csch"])
7428            }
7429            Some("cosh") => {
7430                rubi_pure_function_of_hyperbolic_family_recur(expr, &argument, x, &["cosh", "sech"])
7431            }
7432            Some("tanh") => {
7433                rubi_pure_function_of_hyperbolic_family_recur(expr, &argument, x, &["tanh", "coth"])
7434            }
7435            Some("coth") => {
7436                rubi_pure_function_of_hyperbolic_family_recur(expr, &argument, x, &["coth"])
7437            }
7438            Some("sech") => {
7439                rubi_pure_function_of_hyperbolic_family_recur(expr, &argument, x, &["cosh", "sech"])
7440            }
7441            Some("csch") => {
7442                rubi_pure_function_of_hyperbolic_family_recur(expr, &argument, x, &["sinh", "csch"])
7443            }
7444            _ => rubi_function_of_expn_q(expr, base, x).is_some(),
7445        };
7446    }
7447
7448    rubi_function_of_expn_q(expr, base, x).is_some()
7449}
7450
7451fn rubi_function_of_expn_q(expr: &Atom, base: &Atom, x: Symbol) -> Option<Atom> {
7452    if expr == base {
7453        return Some(Atom::num(1));
7454    }
7455    if atom_q(expr.as_view()) {
7456        return (expr != &Atom::var(x)).then_some(Atom::num(0));
7457    }
7458    if rubi_function_of_expn_calculus_q(expr, x) {
7459        return None;
7460    }
7461
7462    match expr.as_view() {
7463        AtomView::Pow(power) => {
7464            let expr_base = power.get_base().to_owned();
7465            let expr_exponent = power.get_exp().to_owned();
7466            if is_free_of(&expr_exponent, x) {
7467                if eqq!(expr_base, base) {
7468                    return if integerq!(expr_exponent.to_owned()) {
7469                        Some(expr_exponent)
7470                    } else {
7471                        Some(Atom::num(1))
7472                    };
7473                }
7474                if let Some((base_base, base_exponent)) = rubi_power_with_rational_exponent(base) {
7475                    if eqq!(expr_base, base_base) {
7476                        let quotient =
7477                            (expr_exponent.to_owned() / base_exponent.to_owned()).cancel();
7478                        if let Some((base_num, base_den)) = rational_number(&base_exponent) {
7479                            let base_positive = base_num > 0 && base_den > 0;
7480                            let expr_negative = rational_number(&expr_exponent)
7481                                .is_some_and(|(num, den)| num < 0 && den > 0);
7482                            if rational_number(&expr_exponent).is_some()
7483                                && integerq!(quotient.to_owned())
7484                                && (base_positive || expr_negative)
7485                            {
7486                                return Some(quotient);
7487                            }
7488                            return None;
7489                        }
7490                        return integerq!(quotient.to_owned()).then_some(quotient);
7491                    }
7492                }
7493                return rubi_function_of_expn_q(&expr_base, base, x);
7494            }
7495            let degrees = [expr_base, expr_exponent]
7496                .into_iter()
7497                .map(|part| rubi_function_of_expn_q(&part, base, x))
7498                .collect::<Option<Vec<_>>>()?;
7499            rubi_gcd_atoms(&degrees)
7500        }
7501        AtomView::Mul(_) if !eqq!(rubi_free_factors(expr, x), 1) => {
7502            rubi_function_of_expn_q(&rubi_nonfree_factors(expr, x), base, x)
7503        }
7504        AtomView::Mul(_) if matches!(base.as_view(), AtomView::Mul(_)) => {
7505            let expr_factors = rubi_product_factors(expr);
7506            let base_factors = rubi_product_factors(base);
7507            let (Some(expr_first), Some(base_first)) = (expr_factors.first(), base_factors.first())
7508            else {
7509                return None;
7510            };
7511            let deg1 = rubi_function_of_expn_q(expr_first, base_first, x)?;
7512            let expr_rest = product_atoms(&expr_factors[1..]);
7513            let base_rest = product_atoms(&base_factors[1..]);
7514            let deg2 = rubi_function_of_expn_q(&expr_rest, &base_rest, x)?;
7515            if deg1 == deg2 && freeq!(rubi_simplify(&(expr / base.pow(deg1.to_owned()))), x) {
7516                Some(deg1)
7517            } else {
7518                None
7519            }
7520        }
7521        AtomView::Add(add) => {
7522            let degrees = add
7523                .into_iter()
7524                .map(|term| rubi_function_of_expn_q(&term.to_owned(), base, x))
7525                .collect::<Option<Vec<_>>>()?;
7526            rubi_gcd_atoms(&degrees)
7527        }
7528        AtomView::Mul(mul) => {
7529            let degrees = mul
7530                .into_iter()
7531                .map(|factor| rubi_function_of_expn_q(&factor.to_owned(), base, x))
7532                .collect::<Option<Vec<_>>>()?;
7533            rubi_gcd_atoms(&degrees)
7534        }
7535        AtomView::Fun(function) => {
7536            let degrees = function
7537                .into_iter()
7538                .map(|argument| rubi_function_of_expn_q(&argument.to_owned(), base, x))
7539                .collect::<Option<Vec<_>>>()?;
7540            rubi_gcd_atoms(&degrees)
7541        }
7542        AtomView::Num(_) | AtomView::Var(_) => None,
7543    }
7544}
7545
7546fn rubi_function_of_expn_calculus_q(expr: &Atom, _x: Symbol) -> bool {
7547    match expr.as_view() {
7548        AtomView::Fun(function) => rubi_calculus_function_symbol(function.get_symbol()),
7549        _ => false,
7550    }
7551}
7552
7553fn rubi_gcd_atoms(values: &[Atom]) -> Option<Atom> {
7554    let mut iter = values.iter();
7555    let first = iter.next()?;
7556    let mut gcd = rubi_integer_atom(first)?.abs();
7557    for value in iter {
7558        gcd = gcd_i64(gcd, rubi_integer_atom(value)?.abs());
7559    }
7560    Some(Atom::num(gcd))
7561}
7562
7563fn gcd_i64(mut left: i64, mut right: i64) -> i64 {
7564    while right != 0 {
7565        let remainder = left % right;
7566        left = right;
7567        right = remainder;
7568    }
7569    left.abs()
7570}
7571
7572fn rubi_polynomial_in_q(expr: &Atom, base: &Atom, x: Symbol) -> bool {
7573    let Some(substitution_guard) = fresh_substitution_symbol() else {
7574        return false;
7575    };
7576    let sub = substitution_guard.symbol();
7577    let replaced = rubi_subst_for(expr, base, sub);
7578    replaced != *expr && is_free_of(&replaced, x) && rubi_poly_q(&replaced, sub)
7579}
7580
7581fn rubi_polynomial_in_subst(expr: &Atom, base: &Atom, x: Symbol) -> Option<Atom> {
7582    let Some(substitution_guard) = fresh_substitution_symbol() else {
7583        return None;
7584    };
7585    let sub = substitution_guard.symbol();
7586    let replaced = rubi_subst_for(expr, base, sub);
7587    if replaced == *expr || !is_free_of(&replaced, x) || !rubi_poly_q(&replaced, sub) {
7588        return None;
7589    }
7590
7591    Some(rubi_subst(&replaced, sub, Atom::var(x)))
7592}
7593
7594/// Canonical representations of an exponential function's base.
7595enum RubiExponentialBase {
7596    Exp,
7597    Power(Atom),
7598}
7599
7600/// A function-of-exponential decomposition and its substitution parameters.
7601struct RubiFunctionOfExponential {
7602    exponential: Atom,
7603    function: Atom,
7604}
7605
7606fn rubi_function_of_exponential_q(expr: AtomView<'_>, x: Symbol) -> bool {
7607    rubi_function_of_exponential(expr, x).is_some()
7608}
7609
7610fn rubi_function_of_exponential_rule_exclusion_q(expr: AtomView<'_>, x: Symbol) -> bool {
7611    rubi_integer_scaled_power_product_match_q(expr, x)
7612        || rubi_exponential_inverse_function_product_match_q(expr, x)
7613}
7614
7615fn rubi_integer_scaled_power_product_match_q(expr: AtomView<'_>, x: Symbol) -> bool {
7616    match expr {
7617        AtomView::Mul(mul) => mul
7618            .into_iter()
7619            .any(|factor| rubi_integer_scaled_power_match_q(factor, x)),
7620        _ => rubi_integer_scaled_power_match_q(expr, x),
7621    }
7622}
7623
7624fn rubi_integer_scaled_power_match_q(expr: AtomView<'_>, x: Symbol) -> bool {
7625    let AtomView::Pow(power) = expr else {
7626        return false;
7627    };
7628    let exponent = power.get_exp();
7629    if !is_free_of(exponent, x) {
7630        return false;
7631    }
7632
7633    rubi_scaled_power_inner_exponent(power.get_base(), x).is_some_and(|inner_exponent| {
7634        is_free_of(&inner_exponent, x) && integerq!(exponent.to_owned() * inner_exponent)
7635    })
7636}
7637
7638fn rubi_scaled_power_inner_exponent(expr: AtomView<'_>, x: Symbol) -> Option<Atom> {
7639    match expr {
7640        AtomView::Pow(power)
7641            if is_free_of(power.get_base(), x) && !is_free_of(power.get_exp(), x) =>
7642        {
7643            Some(power.get_exp().to_owned())
7644        }
7645        AtomView::Mul(mul) => {
7646            let mut nonfree_exponent = None;
7647            for factor in mul {
7648                if is_free_of(factor, x) {
7649                    continue;
7650                }
7651                let exponent = match factor {
7652                    AtomView::Pow(power)
7653                        if is_free_of(power.get_base(), x) && !is_free_of(power.get_exp(), x) =>
7654                    {
7655                        power.get_exp().to_owned()
7656                    }
7657                    _ => return None,
7658                };
7659                if nonfree_exponent.replace(exponent).is_some() {
7660                    return None;
7661                }
7662            }
7663            nonfree_exponent
7664        }
7665        _ => None,
7666    }
7667}
7668
7669fn rubi_exponential_inverse_function_product_match_q(expr: AtomView<'_>, x: Symbol) -> bool {
7670    let mut has_linear_euler_factor = false;
7671    let mut has_inverse_function_factor = false;
7672    let mut visit = |factor| {
7673        has_linear_euler_factor |= rubi_exp_argument(factor)
7674            .is_some_and(|exponent| rubi_scaled_linear_q(exponent.as_view(), x));
7675        has_inverse_function_factor |= rubi_inverse_function_call_q(factor, x);
7676    };
7677
7678    match expr {
7679        AtomView::Mul(mul) => mul.into_iter().for_each(&mut visit),
7680        _ => visit(expr),
7681    }
7682
7683    has_linear_euler_factor && has_inverse_function_factor
7684}
7685
7686fn rubi_scaled_linear_q(expr: AtomView<'_>, x: Symbol) -> bool {
7687    match expr {
7688        AtomView::Mul(mul) => {
7689            let mut nonfree = Vec::new();
7690            for factor in mul {
7691                if !is_free_of(factor, x) {
7692                    nonfree.push(factor);
7693                }
7694            }
7695            nonfree.len() == 1 && rubi_linear_q(nonfree[0], x)
7696        }
7697        _ => rubi_linear_q(expr, x),
7698    }
7699}
7700
7701fn rubi_inverse_function_call_q(expr: AtomView<'_>, x: Symbol) -> bool {
7702    let AtomView::Fun(function) = expr else {
7703        return false;
7704    };
7705    if is_free_of(expr, x) {
7706        return false;
7707    }
7708    matches!(
7709        function.get_symbol(),
7710        s if s == symbol!("asin")
7711            || s == symbol!("acos")
7712            || s == symbol!("atan")
7713            || s == symbol!("acot")
7714            || s == symbol!("asinh")
7715            || s == symbol!("acosh")
7716            || s == symbol!("atanh")
7717            || s == symbol!("acoth")
7718            || s == symbol!("log")
7719    )
7720}
7721
7722fn rubi_inverse_function_q(expr: &Atom) -> bool {
7723    let AtomView::Fun(function) = expr.as_view() else {
7724        return false;
7725    };
7726    let head = function.get_symbol();
7727    head == symbol!("log")
7728        || (function.get_nargs() <= 1
7729            && matches!(
7730                head,
7731                s if s == symbol!("asin")
7732                    || s == symbol!("acos")
7733                    || s == symbol!("atan")
7734                    || s == symbol!("acot")
7735                    || s == symbol!("asec")
7736                    || s == symbol!("acsc")
7737            ))
7738        || matches!(
7739            head,
7740            s if s == symbol!("asinh")
7741                || s == symbol!("acosh")
7742                || s == symbol!("atanh")
7743                || s == symbol!("acoth")
7744                || s == symbol!("asech")
7745                || s == symbol!("acsch")
7746                || s == symbol!("Mods")
7747                || s == symbol!("polylog")
7748        )
7749}
7750
7751fn rubi_match_affine_inverse_function_q(expr: &Atom, x: Symbol) -> bool {
7752    let symbols = rubi_symbols();
7753    rubi_conditional_match_q(
7754        expr,
7755        Atom::var(symbols.a__) + Atom::var(symbols.b__) * Atom::var(symbols.v__),
7756        &[symbols.b__],
7757        |matches| {
7758            let Some(a) = wildcard_atom(matches, symbols.a__) else {
7759                return false;
7760            };
7761            let Some(b) = wildcard_atom(matches, symbols.b__) else {
7762                return false;
7763            };
7764            let Some(v) = wildcard_atom(matches, symbols.v__) else {
7765                return false;
7766            };
7767            freeq!([a, b], x) && rubi_inverse_function_q(&v)
7768        },
7769    )
7770}
7771
7772fn rubi_function_of_exponential(
7773    expr: AtomView<'_>,
7774    x: Symbol,
7775) -> Option<RubiFunctionOfExponential> {
7776    let mut basis = None;
7777    let mut explicit_exponential = false;
7778    if !rubi_function_of_exponential_test(expr, x, &mut basis, &mut explicit_exponential)
7779        || !explicit_exponential
7780    {
7781        return None;
7782    }
7783
7784    let (base, exponent) = basis?;
7785    let exponential = match &base {
7786        RubiExponentialBase::Exp => exponent.exp(),
7787        RubiExponentialBase::Power(base) => base.pow(&exponent),
7788    };
7789    let function = rubi_function_of_exponential_function_aux(expr, x, &base, &exponent)?;
7790
7791    Some(RubiFunctionOfExponential {
7792        exponential,
7793        function: rubi_simplify_integrand(&function, x),
7794    })
7795}
7796
7797fn rubi_function_of_exponential_test(
7798    expr: AtomView<'_>,
7799    x: Symbol,
7800    basis: &mut Option<(RubiExponentialBase, Atom)>,
7801    explicit_exponential: &mut bool,
7802) -> bool {
7803    if is_free_of(expr, x) {
7804        return true;
7805    }
7806
7807    match expr {
7808        AtomView::Fun(function)
7809            if function.get_symbol() == symbol!("exp") && function.get_nargs() == 1 =>
7810        {
7811            let argument = function.get(0);
7812            if rubi_linear_q(argument, x) {
7813                let argument = argument.to_owned();
7814                *explicit_exponential = true;
7815                return rubi_function_of_exponential_test_aux(
7816                    RubiExponentialBase::Exp,
7817                    &argument,
7818                    x,
7819                    basis,
7820                );
7821            }
7822            if let AtomView::Add(add) = argument {
7823                return add.into_iter().all(|term| {
7824                    rubi_function_of_exponential_test(
7825                        term.to_owned().exp().as_view(),
7826                        x,
7827                        basis,
7828                        explicit_exponential,
7829                    )
7830                });
7831            }
7832            rubi_function_of_exponential_test(argument, x, basis, explicit_exponential)
7833        }
7834        AtomView::Fun(function)
7835            if function.get_nargs() == 1
7836                && rubi_hyperbolic_function_symbol(function.get_symbol()) =>
7837        {
7838            let argument = function.get(0);
7839            if rubi_linear_q(argument, x) {
7840                let argument = argument.to_owned();
7841                return rubi_function_of_exponential_test_aux(
7842                    RubiExponentialBase::Exp,
7843                    &argument,
7844                    x,
7845                    basis,
7846                );
7847            }
7848
7849            rubi_function_of_exponential_test(argument, x, basis, explicit_exponential)
7850        }
7851        AtomView::Fun(function) if rubi_calculus_operator_symbol(function.get_symbol()) => false,
7852        AtomView::Fun(function) => function.into_iter().all(|argument| {
7853            rubi_function_of_exponential_test(argument, x, basis, explicit_exponential)
7854        }),
7855        AtomView::Pow(power) => {
7856            let (base, exponent) = power.get_base_exp();
7857            if is_free_of(base, x) && rubi_linear_q(exponent, x) {
7858                let exponent = exponent.to_owned();
7859                *explicit_exponential = true;
7860                return rubi_function_of_exponential_test_aux(
7861                    RubiExponentialBase::Power(base.to_owned()),
7862                    &exponent,
7863                    x,
7864                    basis,
7865                );
7866            }
7867            if is_free_of(base, x) {
7868                if let AtomView::Add(add) = exponent {
7869                    return add.into_iter().all(|term| {
7870                        rubi_function_of_exponential_test(
7871                            base.to_owned().pow(term.to_owned()).as_view(),
7872                            x,
7873                            basis,
7874                            explicit_exponential,
7875                        )
7876                    });
7877                }
7878            }
7879
7880            rubi_function_of_exponential_test(base, x, basis, explicit_exponential)
7881                && rubi_function_of_exponential_test(exponent, x, basis, explicit_exponential)
7882        }
7883        AtomView::Add(add) => add
7884            .into_iter()
7885            .all(|term| rubi_function_of_exponential_test(term, x, basis, explicit_exponential)),
7886        AtomView::Mul(mul) => mul.into_iter().all(|factor| {
7887            rubi_function_of_exponential_test(factor, x, basis, explicit_exponential)
7888        }),
7889        AtomView::Var(variable) => variable.get_symbol() != x,
7890        AtomView::Num(_) => true,
7891    }
7892}
7893
7894fn rubi_function_of_exponential_test_aux(
7895    base: RubiExponentialBase,
7896    exponent: &Atom,
7897    x: Symbol,
7898    basis: &mut Option<(RubiExponentialBase, Atom)>,
7899) -> bool {
7900    let Some(slope) = rubi_coefficient(exponent, x, 1) else {
7901        return false;
7902    };
7903    if slope.is_zero() {
7904        return false;
7905    }
7906
7907    let Some((basis_base, basis_exponent)) = basis else {
7908        *basis = Some((base, exponent.to_owned()));
7909        return true;
7910    };
7911
7912    let Some(basis_slope) = rubi_coefficient(basis_exponent, x, 1) else {
7913        return false;
7914    };
7915
7916    let Some(log_ratio) = rubi_exponential_base_log_ratio(&base, basis_base) else {
7917        return false;
7918    };
7919    let mut ratio = (log_ratio * &slope / &basis_slope).cancel();
7920    if rubi_exponential_base_prefer(&base, basis_base) {
7921        *basis_base = match base {
7922            RubiExponentialBase::Exp => RubiExponentialBase::Exp,
7923            RubiExponentialBase::Power(base) => RubiExponentialBase::Power(base.to_owned()),
7924        };
7925        *basis_exponent = exponent.to_owned();
7926        ratio = (Atom::num(1) / ratio).cancel();
7927    }
7928
7929    let Some((_ratio_numerator, ratio_denominator)) = rational_number(&ratio) else {
7930        return false;
7931    };
7932
7933    let constant = rubi_coefficient(exponent, x, 0).unwrap_or_else(|| Atom::num(0));
7934    let basis_constant = rubi_coefficient(basis_exponent, x, 0).unwrap_or_else(|| Atom::num(0));
7935    let preserves_constant_ratio =
7936        !eqq!(basis_constant, 0) && eqq!(ratio, (&constant / &basis_constant).cancel());
7937
7938    let mut updated_exponent = if preserves_constant_ratio {
7939        (&*basis_exponent / Atom::num(ratio_denominator)).cancel()
7940    } else {
7941        let x_atom = Atom::var(x);
7942        (&basis_slope * x_atom / Atom::num(ratio_denominator)).cancel()
7943    };
7944
7945    let Some(updated_slope) = rubi_coefficient(&updated_exponent, x, 1) else {
7946        return false;
7947    };
7948    if ltq!(ratio, 0) && negq!(updated_slope) {
7949        updated_exponent = -updated_exponent;
7950    }
7951    *basis_exponent = updated_exponent;
7952    true
7953}
7954
7955fn rubi_exponential_base_log_ratio(
7956    base: &RubiExponentialBase,
7957    basis_base: &RubiExponentialBase,
7958) -> Option<Atom> {
7959    if rubi_exponential_base_eq(base, basis_base) {
7960        return Some(Atom::num(1));
7961    }
7962
7963    let base = positive_integer_exponential_base(base)?;
7964    let basis_base = positive_integer_exponential_base(basis_base)?;
7965    let (numerator, denominator) = integer_log_ratio(base, basis_base)?;
7966    Some(Atom::num(numerator) / Atom::num(denominator))
7967}
7968
7969fn rubi_natural_exponential_base(base: &RubiExponentialBase) -> bool {
7970    match base {
7971        RubiExponentialBase::Exp => true,
7972        RubiExponentialBase::Power(base) => eqq!(base, Atom::var(Symbol::E)),
7973    }
7974}
7975
7976fn rubi_exponential_base_prefer(
7977    base: &RubiExponentialBase,
7978    basis_base: &RubiExponentialBase,
7979) -> bool {
7980    match (
7981        positive_integer_exponential_base(base),
7982        positive_integer_exponential_base(basis_base),
7983    ) {
7984        (Some(base), Some(basis_base)) => base < basis_base,
7985        _ => false,
7986    }
7987}
7988
7989fn positive_integer_exponential_base(base: &RubiExponentialBase) -> Option<i64> {
7990    match base {
7991        RubiExponentialBase::Power(base) => integer_i64(base).filter(|value| *value > 1),
7992        RubiExponentialBase::Exp => None,
7993    }
7994}
7995
7996fn integer_log_ratio(base: i64, basis_base: i64) -> Option<(i64, i64)> {
7997    let base_factors = integer_factorization(base)?;
7998    let basis_factors = integer_factorization(basis_base)?;
7999    let mut numerator = None;
8000    let mut denominator = None;
8001
8002    for prime in base_factors.keys().chain(basis_factors.keys()) {
8003        let left = *base_factors.get(prime).unwrap_or(&0);
8004        let right = *basis_factors.get(prime).unwrap_or(&0);
8005        if left == 0 || right == 0 {
8006            return None;
8007        }
8008
8009        match (numerator, denominator) {
8010            (Some(n), Some(d)) if left * d != right * n => return None,
8011            (None, None) => {
8012                numerator = Some(left);
8013                denominator = Some(right);
8014            }
8015            _ => {}
8016        }
8017    }
8018
8019    let numerator = numerator?;
8020    let denominator = denominator?;
8021    let gcd = integer_gcd(numerator, denominator);
8022    Some((numerator / gcd, denominator / gcd))
8023}
8024
8025fn integer_factorization(value: i64) -> Option<BTreeMap<i64, i64>> {
8026    if value <= 1 {
8027        return None;
8028    }
8029
8030    Integer::from(value)
8031        .factor()
8032        .into_iter()
8033        .map(|(factor, exponent)| Some((factor.to_i64()?, exponent.to_i64()?)))
8034        .collect()
8035}
8036
8037fn rubi_exponential_base_eq(left: &RubiExponentialBase, right: &RubiExponentialBase) -> bool {
8038    if rubi_natural_exponential_base(left) && rubi_natural_exponential_base(right) {
8039        return true;
8040    }
8041
8042    match (left, right) {
8043        (RubiExponentialBase::Exp, RubiExponentialBase::Exp) => true,
8044        (RubiExponentialBase::Power(left), RubiExponentialBase::Power(right)) => {
8045            eqq!(left, right)
8046        }
8047        _ => false,
8048    }
8049}
8050
8051fn rubi_function_of_exponential_function_aux(
8052    expr: AtomView<'_>,
8053    x: Symbol,
8054    basis_base: &RubiExponentialBase,
8055    basis_exponent: &Atom,
8056) -> Option<Atom> {
8057    if is_free_of(expr, x) {
8058        return Some(expr.to_owned());
8059    }
8060
8061    match expr {
8062        AtomView::Fun(function)
8063            if function.get_symbol() == symbol!("exp") && function.get_nargs() == 1 =>
8064        {
8065            let argument = function.get(0);
8066            if rubi_linear_q(argument, x) {
8067                let argument = argument.to_owned();
8068                return rubi_linear_exponential_as_substitution_power(
8069                    &RubiExponentialBase::Exp,
8070                    &argument,
8071                    basis_base,
8072                    basis_exponent,
8073                    x,
8074                );
8075            }
8076            if let AtomView::Add(add) = argument {
8077                let factors: Option<Vec<Atom>> = add
8078                    .into_iter()
8079                    .map(|term| {
8080                        rubi_function_of_exponential_function_aux(
8081                            term.to_owned().exp().as_view(),
8082                            x,
8083                            basis_base,
8084                            basis_exponent,
8085                        )
8086                    })
8087                    .collect();
8088                return Some(product_atoms(&factors?));
8089            }
8090            let rewritten_argument =
8091                rubi_function_of_exponential_function_aux(argument, x, basis_base, basis_exponent)?;
8092            Some(rewritten_argument.exp())
8093        }
8094        AtomView::Fun(function)
8095            if function.get_nargs() == 1
8096                && rubi_hyperbolic_function_symbol(function.get_symbol()) =>
8097        {
8098            let function_symbol = function.get_symbol();
8099            let argument = function.get(0);
8100            if rubi_linear_q(argument, x) {
8101                let slope = rubi_coefficient(&argument.to_owned(), x, 1)?;
8102                let basis_slope = rubi_coefficient(basis_exponent, x, 1)?;
8103                let log_ratio =
8104                    rubi_exponential_base_log_ratio(&RubiExponentialBase::Exp, basis_base)?;
8105                let substitution = Atom::var(x).pow((log_ratio * slope / basis_slope).cancel());
8106                let reciprocal = Atom::num(1) / &substitution;
8107                return match function_symbol.get_stripped_ascii_name() {
8108                    Some("sinh") => Some(&substitution / Atom::num(2) - reciprocal / Atom::num(2)),
8109                    Some("cosh") => Some(&substitution / Atom::num(2) + reciprocal / Atom::num(2)),
8110                    Some("tanh") => {
8111                        Some((&substitution - &reciprocal) / (&substitution + &reciprocal))
8112                    }
8113                    Some("coth") => {
8114                        Some((&substitution + &reciprocal) / (&substitution - &reciprocal))
8115                    }
8116                    Some("sech") => Some(Atom::num(2) / (&substitution + &reciprocal)),
8117                    Some("csch") => Some(Atom::num(2) / (&substitution - &reciprocal)),
8118                    _ => None,
8119                };
8120            }
8121
8122            let rewritten_argument =
8123                rubi_function_of_exponential_function_aux(argument, x, basis_base, basis_exponent)?;
8124            Some(function_symbol.call((rewritten_argument,)))
8125        }
8126        AtomView::Fun(function) => {
8127            let args: Option<Vec<Atom>> = function
8128                .into_iter()
8129                .map(|argument| {
8130                    rubi_function_of_exponential_function_aux(
8131                        argument,
8132                        x,
8133                        basis_base,
8134                        basis_exponent,
8135                    )
8136                })
8137                .collect();
8138            Some(function.get_symbol().call_args(args?))
8139        }
8140        AtomView::Pow(power) => {
8141            let (base, exponent) = power.get_base_exp();
8142            if is_free_of(base, x) && rubi_linear_q(exponent, x) {
8143                let base_atom = base.to_owned();
8144                let exponent_atom = exponent.to_owned();
8145                return rubi_linear_exponential_as_substitution_power(
8146                    &RubiExponentialBase::Power(base_atom),
8147                    &exponent_atom,
8148                    basis_base,
8149                    basis_exponent,
8150                    x,
8151                );
8152            }
8153            if is_free_of(base, x) {
8154                if let AtomView::Add(add) = exponent {
8155                    let factors: Option<Vec<Atom>> = add
8156                        .into_iter()
8157                        .map(|term| {
8158                            rubi_function_of_exponential_function_aux(
8159                                base.to_owned().pow(term.to_owned()).as_view(),
8160                                x,
8161                                basis_base,
8162                                basis_exponent,
8163                            )
8164                        })
8165                        .collect();
8166                    return Some(product_atoms(&factors?));
8167                }
8168            }
8169
8170            let rewritten_base =
8171                rubi_function_of_exponential_function_aux(base, x, basis_base, basis_exponent)?;
8172            let rewritten_exponent =
8173                rubi_function_of_exponential_function_aux(exponent, x, basis_base, basis_exponent)?;
8174            Some(rubi_hold_power(&rewritten_base, &rewritten_exponent))
8175        }
8176        AtomView::Add(add) => {
8177            let terms: Option<Vec<Atom>> = add
8178                .into_iter()
8179                .map(|term| {
8180                    rubi_function_of_exponential_function_aux(term, x, basis_base, basis_exponent)
8181                })
8182                .collect();
8183            Some(
8184                terms?
8185                    .into_iter()
8186                    .fold(Atom::num(0), |sum, term| sum + term),
8187            )
8188        }
8189        AtomView::Mul(mul) => {
8190            let factors: Option<Vec<Atom>> = mul
8191                .into_iter()
8192                .map(|factor| {
8193                    rubi_function_of_exponential_function_aux(factor, x, basis_base, basis_exponent)
8194                })
8195                .collect();
8196            Some(
8197                factors?
8198                    .into_iter()
8199                    .fold(Atom::num(1), |product, factor| product * factor),
8200            )
8201        }
8202        AtomView::Var(variable) if variable.get_symbol() == x => None,
8203        AtomView::Var(_) | AtomView::Num(_) => Some(expr.to_owned()),
8204    }
8205}
8206
8207fn rubi_linear_exponential_as_substitution_power(
8208    base: &RubiExponentialBase,
8209    exponent: &Atom,
8210    basis_base: &RubiExponentialBase,
8211    basis_exponent: &Atom,
8212    x: Symbol,
8213) -> Option<Atom> {
8214    let slope = rubi_coefficient(exponent, x, 1)?;
8215    let basis_slope = rubi_coefficient(basis_exponent, x, 1)?;
8216    let log_ratio = rubi_exponential_base_log_ratio(base, basis_base)?;
8217    let ratio = (log_ratio * &slope / basis_slope).cancel();
8218    if !rationalq!(ratio) {
8219        return None;
8220    }
8221
8222    let constant = rubi_coefficient(exponent, x, 0).unwrap_or_else(|| Atom::num(0));
8223    let basis_constant = rubi_coefficient(basis_exponent, x, 0).unwrap_or_else(|| Atom::num(0));
8224
8225    let x_atom = Atom::var(x);
8226    let substitution_power = x_atom.pow(ratio);
8227    if !eqq!(basis_constant, 0) || eqq!(constant, 0) {
8228        Some(substitution_power)
8229    } else {
8230        let constant_factor = match base {
8231            RubiExponentialBase::Exp => constant.exp(),
8232            RubiExponentialBase::Power(base) => base.pow(constant),
8233        };
8234        Some(constant_factor * substitution_power)
8235    }
8236}
8237
8238fn rubi_match_optional_multiplier_linear_power_q(expr: &Atom, x: Symbol) -> bool {
8239    if is_free_of(expr, x) {
8240        return true;
8241    }
8242
8243    rubi_split_product(|factor| rubi_linear_power_match_q(factor, x), expr)
8244        .is_some_and(|(_, rest)| is_free_of(&rest, x))
8245}
8246
8247fn rubi_linear_power_match_q(expr: &Atom, x: Symbol) -> bool {
8248    match expr.as_view() {
8249        AtomView::Pow(power) => {
8250            let (base, exponent) = power.get_base_exp();
8251            is_free_of(exponent, x) && rubi_linear_match_q_view(base, x)
8252        }
8253        _ => rubi_linear_match_q(expr, x),
8254    }
8255}
8256
8257fn rubi_power_variable_expn_subst(
8258    expr: &Atom,
8259    shift: &Atom,
8260    x: Symbol,
8261    sub: Symbol,
8262) -> Option<(Atom, Atom)> {
8263    let (integrand, power, _scale) = rubi_power_variable_expn_subst_scaled(expr, shift, x, sub)?;
8264    Some((integrand, power))
8265}
8266
8267fn rubi_power_variable_expn_subst_scaled(
8268    expr: &Atom,
8269    shift: &Atom,
8270    x: Symbol,
8271    sub: Symbol,
8272) -> Option<(Atom, Atom, Atom)> {
8273    if let Some(result) = rubi_power_variable_integer_expn_subst(expr, shift, x, sub) {
8274        return Some(result);
8275    }
8276
8277    rubi_power_variable_symbolic_expn_subst(expr, shift, x, sub)
8278}
8279
8280/// Decomposition of an expression as a power of a variable expression.
8281struct RubiPowerVariableExpn {
8282    integrand: Atom,
8283    power: Atom,
8284    scale: Atom,
8285    substitution_symbol: Symbol,
8286    _substitution_guard: FreshSubstitutionSymbol,
8287}
8288
8289fn rubi_power_variable_expn(expr: &Atom, shift: Atom, x: Symbol) -> Option<RubiPowerVariableExpn> {
8290    let substitution_guard = fresh_substitution_symbol()?;
8291    let sub = substitution_guard.symbol();
8292    let (integrand, power, scale) = rubi_power_variable_expn_subst_scaled(expr, &shift, x, sub)?;
8293    Some(RubiPowerVariableExpn {
8294        integrand,
8295        power,
8296        scale,
8297        substitution_symbol: sub,
8298        _substitution_guard: substitution_guard,
8299    })
8300}
8301
8302fn rubi_power_variable_integer_expn_subst(
8303    expr: &Atom,
8304    shift: &Atom,
8305    x: Symbol,
8306    sub: Symbol,
8307) -> Option<(Atom, Atom, Atom)> {
8308    let shift_value = integer_i64(shift)?;
8309    let (power_value, scale) =
8310        rubi_power_variable_integer_degree(expr.as_view(), shift_value, &Atom::num(1), x)?;
8311    if power_value == 0 {
8312        return None;
8313    }
8314    let transformed = subst_rubi_variable_integer_power(expr.as_view(), x, power_value, sub)?;
8315    let shift_power = shift_value.checked_div(power_value)?;
8316    if shift_value % power_value != 0 {
8317        return None;
8318    }
8319
8320    let sub_atom = Atom::var(sub);
8321    Some((
8322        sub_atom.pow(shift_power) * transformed,
8323        Atom::num(power_value),
8324        scale,
8325    ))
8326}
8327
8328fn rubi_power_variable_integer_degree(
8329    expr: AtomView<'_>,
8330    current_power: i64,
8331    current_scale: &Atom,
8332    x: Symbol,
8333) -> Option<(i64, Atom)> {
8334    if is_free_of(expr, x) {
8335        return Some((current_power, current_scale.to_owned()));
8336    }
8337
8338    if let AtomView::Pow(power) = expr {
8339        let (base, exponent) = power.get_base_exp();
8340        if let Some(base_scale) = rubi_scaled_variable_factor(base, x) {
8341            let exponent_value = integer_i64_view(exponent)?;
8342            if current_power == 0 {
8343                return Some((exponent_value, base_scale));
8344            }
8345            if *current_scale != base_scale {
8346                return None;
8347            }
8348            if current_power == exponent_value {
8349                return Some((current_power, current_scale.to_owned()));
8350            }
8351            let common_power = integer_gcd(current_power, exponent_value).abs();
8352            return (common_power > 1).then(|| (common_power, current_scale.to_owned()));
8353        }
8354    }
8355
8356    match expr {
8357        AtomView::Add(add) => {
8358            let mut state = (current_power, current_scale.to_owned());
8359            for term in add {
8360                state = rubi_power_variable_integer_degree(term, state.0, &state.1, x)?;
8361            }
8362            Some(state)
8363        }
8364        AtomView::Mul(mul) => {
8365            let mut state = (current_power, current_scale.to_owned());
8366            for factor in mul {
8367                state = rubi_power_variable_integer_degree(factor, state.0, &state.1, x)?;
8368            }
8369            Some(state)
8370        }
8371        AtomView::Pow(power) => {
8372            let (base, exponent) = power.get_base_exp();
8373            let state = rubi_power_variable_integer_degree(base, current_power, current_scale, x)?;
8374            rubi_power_variable_integer_degree(exponent, state.0, &state.1, x)
8375        }
8376        AtomView::Fun(function) => {
8377            let mut state = (current_power, current_scale.to_owned());
8378            for argument in function {
8379                state = rubi_power_variable_integer_degree(argument, state.0, &state.1, x)?;
8380            }
8381            Some(state)
8382        }
8383        AtomView::Var(_) | AtomView::Num(_) => None,
8384    }
8385}
8386
8387fn rubi_power_variable_symbolic_expn_subst(
8388    expr: &Atom,
8389    shift: &Atom,
8390    x: Symbol,
8391    sub: Symbol,
8392) -> Option<(Atom, Atom, Atom)> {
8393    let (power, scale) =
8394        rubi_power_variable_symbolic_degree(expr.as_view(), shift, &Atom::num(1), x)?;
8395    if eqq!(power, 0) {
8396        return None;
8397    }
8398
8399    let transformed = rubi_power_variable_symbolic_subst(expr.as_view(), &power, x, sub)?;
8400    let sub_atom = Atom::var(sub);
8401    Some((sub_atom.pow(shift / &power) * transformed, power, scale))
8402}
8403
8404fn rubi_power_variable_symbolic_degree(
8405    expr: AtomView<'_>,
8406    shift: &Atom,
8407    scale: &Atom,
8408    x: Symbol,
8409) -> Option<(Atom, Atom)> {
8410    if is_free_of(expr, x) {
8411        return Some((shift.to_owned(), scale.to_owned()));
8412    }
8413
8414    match expr {
8415        AtomView::Var(variable) if variable.get_symbol() == x => None,
8416        AtomView::Pow(power) => {
8417            let (base, exponent_view) = power.get_base_exp();
8418            let exponent = exponent_view.to_owned();
8419            if let Some(base_scale) = rubi_scaled_variable_factor(base, x) {
8420                if eqq!(shift, 0) || (eqq!(shift, exponent) && eqq!(scale, base_scale)) {
8421                    return Some((exponent, base_scale));
8422                }
8423                return None;
8424            }
8425            if !is_free_of(&exponent, x) {
8426                return None;
8427            }
8428            rubi_power_variable_symbolic_degree(base, shift, scale, x)
8429        }
8430        AtomView::Add(add) => {
8431            let mut current_power = shift.to_owned();
8432            let mut current_scale = scale.to_owned();
8433            for term in add {
8434                let (next_power, next_scale) =
8435                    rubi_power_variable_symbolic_degree(term, &current_power, &current_scale, x)?;
8436                current_power = next_power;
8437                current_scale = next_scale;
8438            }
8439            Some((current_power, current_scale))
8440        }
8441        AtomView::Mul(mul) => {
8442            let mut current_power = shift.to_owned();
8443            let mut current_scale = scale.to_owned();
8444            for factor in mul {
8445                let (next_power, next_scale) =
8446                    rubi_power_variable_symbolic_degree(factor, &current_power, &current_scale, x)?;
8447                current_power = next_power;
8448                current_scale = next_scale;
8449            }
8450            Some((current_power, current_scale))
8451        }
8452        AtomView::Fun(function) => {
8453            let mut current_power = shift.to_owned();
8454            let mut current_scale = scale.to_owned();
8455            for argument in function {
8456                let (next_power, next_scale) = rubi_power_variable_symbolic_degree(
8457                    argument,
8458                    &current_power,
8459                    &current_scale,
8460                    x,
8461                )?;
8462                current_power = next_power;
8463                current_scale = next_scale;
8464            }
8465            Some((current_power, current_scale))
8466        }
8467        AtomView::Var(_) | AtomView::Num(_) => None,
8468    }
8469}
8470
8471fn rubi_power_variable_symbolic_subst(
8472    expr: AtomView<'_>,
8473    power_value: &Atom,
8474    x: Symbol,
8475    sub: Symbol,
8476) -> Option<Atom> {
8477    if is_free_of(expr, x) {
8478        return Some(expr.to_owned());
8479    }
8480
8481    let sub_atom = Atom::var(sub);
8482    match expr {
8483        AtomView::Var(variable) if variable.get_symbol() == x => {
8484            Some(sub_atom.pow(Atom::num(1) / power_value))
8485        }
8486        AtomView::Pow(power) => {
8487            let (base, exponent_view) = power.get_base_exp();
8488            let exponent = exponent_view.to_owned();
8489            if rubi_scaled_variable_factor(base, x).is_some() {
8490                return Some(sub_atom.pow(exponent / power_value));
8491            }
8492            if !is_free_of(&exponent, x) {
8493                return None;
8494            }
8495            Some(rubi_power_variable_symbolic_subst(base, power_value, x, sub)?.pow(exponent))
8496        }
8497        AtomView::Add(add) => {
8498            let mut sum = Atom::num(0);
8499            for term in add {
8500                sum += rubi_power_variable_symbolic_subst(term, power_value, x, sub)?;
8501            }
8502            Some(sum)
8503        }
8504        AtomView::Mul(mul) => {
8505            let mut product = Atom::num(1);
8506            for factor in mul {
8507                product *= rubi_power_variable_symbolic_subst(factor, power_value, x, sub)?;
8508            }
8509            Some(product)
8510        }
8511        AtomView::Fun(function) => {
8512            let arguments = function
8513                .into_iter()
8514                .map(|argument| rubi_power_variable_symbolic_subst(argument, power_value, x, sub))
8515                .collect::<Option<Vec<_>>>()?;
8516            Some(function.get_symbol().call_args(arguments))
8517        }
8518        AtomView::Var(_) | AtomView::Num(_) => Some(expr.to_owned()),
8519    }
8520}
8521
8522fn rubi_match_q(expr: &Atom, pattern_expr: Atom, optional: &[Symbol]) -> bool {
8523    let head = symbol!("rubi_match_q");
8524    let hit = Atom::var(symbol!("rubi_match_q_hit"));
8525    let mut pattern = head.call((pattern_expr,)).to_pattern();
8526    for wildcard in optional {
8527        pattern = pattern.set_optional(*wildcard);
8528    }
8529
8530    head.call((expr.to_owned(),))
8531        .replace(pattern)
8532        .with(hit.to_owned())
8533        == hit
8534}
8535
8536fn rubi_conditional_match_q(
8537    expr: &Atom,
8538    pattern_expr: Atom,
8539    optional: &[Symbol],
8540    mut condition: impl FnMut(&symbolica::id::MatchStack<'_>) -> bool,
8541) -> bool {
8542    let head = symbol!("rubi_conditional_match_q");
8543    let mut pattern = head.call((pattern_expr,)).to_pattern();
8544    for wildcard in optional {
8545        pattern = pattern.set_optional(*wildcard);
8546    }
8547
8548    let target = head.call((expr.to_owned(),));
8549    let mut matches = target.pattern_match(&pattern, None, None);
8550    while let Some(matched) = matches.next_detailed() {
8551        if condition(matched.match_stack) {
8552            return true;
8553        }
8554    }
8555    false
8556}
8557
8558fn rubi_scaled_variable_factor(expr: AtomView<'_>, x: Symbol) -> Option<Atom> {
8559    let x_atom = Atom::var(x);
8560    let scale = (expr.to_owned() / x_atom).expand().cancel();
8561    is_free_of(&scale, x).then_some(scale)
8562}
8563
8564fn rubi_power_variable_expn_q(expr: &Atom, shift: &Atom, x: Symbol) -> bool {
8565    let Some(substitution_guard) = fresh_substitution_symbol() else {
8566        return false;
8567    };
8568    rubi_power_variable_expn_subst(expr, shift, x, substitution_guard.symbol()).is_some()
8569}
8570
8571fn subst_rubi_variable_integer_power(
8572    expr: AtomView<'_>,
8573    x: Symbol,
8574    power_value: i64,
8575    sub: Symbol,
8576) -> Option<Atom> {
8577    if is_free_of(expr, x) {
8578        return Some(expr.to_owned());
8579    }
8580
8581    let sub_atom = Atom::var(sub);
8582    match expr {
8583        AtomView::Var(variable) if variable.get_symbol() == x => {
8584            if 1 % power_value == 0 {
8585                Some(sub_atom.pow(1 / power_value))
8586            } else {
8587                None
8588            }
8589        }
8590        AtomView::Pow(power) => {
8591            let (base, exponent) = power.get_base_exp();
8592            if rubi_scaled_variable_factor(base, x).is_some() {
8593                let exponent_value = integer_i64_view(exponent)?;
8594                if exponent_value % power_value != 0 {
8595                    return None;
8596                }
8597                return Some(sub_atom.pow(exponent_value / power_value));
8598            }
8599            if !is_free_of(exponent, x) {
8600                return None;
8601            }
8602            Some(
8603                subst_rubi_variable_integer_power(base, x, power_value, sub)?
8604                    .pow(exponent.to_owned()),
8605            )
8606        }
8607        AtomView::Add(add) => {
8608            let mut sum = Atom::num(0);
8609            for term in add {
8610                sum += subst_rubi_variable_integer_power(term, x, power_value, sub)?;
8611            }
8612            Some(sum)
8613        }
8614        AtomView::Mul(mul) => {
8615            let mut product = Atom::num(1);
8616            for factor in mul {
8617                product *= subst_rubi_variable_integer_power(factor, x, power_value, sub)?;
8618            }
8619            Some(product)
8620        }
8621        AtomView::Fun(function) => {
8622            let arguments = function
8623                .into_iter()
8624                .map(|argument| subst_rubi_variable_integer_power(argument, x, power_value, sub))
8625                .collect::<Option<Vec<_>>>()?;
8626            Some(function.get_symbol().call_args(arguments))
8627        }
8628        AtomView::Var(_) | AtomView::Num(_) => Some(expr.to_owned()),
8629    }
8630}
8631
8632/// Substitution data for a fractional power of an affine expression.
8633struct RubiSubstForFractionalPowerOfLinear {
8634    integrand: Atom,
8635    denominator: i64,
8636    base: Atom,
8637    multiplier: Atom,
8638}
8639
8640fn rubi_subst_for_fractional_power_q(expr: &Atom, base: &Atom, x: Symbol) -> bool {
8641    if atom_q(expr.as_view()) || is_free_of(expr.as_view(), x) {
8642        return true;
8643    }
8644    if rubi_fractional_power_q(expr) {
8645        return rubi_subst_for_fractional_power_aux_q(expr, base);
8646    }
8647    rubi_children(expr.as_view())
8648        .into_iter()
8649        .all(|child| rubi_subst_for_fractional_power_q(&child, base, x))
8650}
8651
8652fn rubi_subst_for_fractional_power_aux_q(expr: &Atom, base: &Atom) -> bool {
8653    if atom_q(expr.as_view()) {
8654        return false;
8655    }
8656    if let AtomView::Pow(power) = expr.as_view()
8657        && rubi_fractional_power_q(expr)
8658        && eqq!(power.get_base(), base)
8659    {
8660        return true;
8661    }
8662    rubi_children(expr.as_view())
8663        .into_iter()
8664        .any(|child| rubi_subst_for_fractional_power_aux_q(&child, base))
8665}
8666
8667fn rubi_fractional_power_q(expr: &Atom) -> bool {
8668    matches!(
8669        expr.as_view(),
8670        AtomView::Pow(power)
8671            if rational_number_view(power.get_exp())
8672                .is_some_and(|(_, denominator)| denominator != 1)
8673    )
8674}
8675
8676fn rubi_fractional_power_bases_are_variable_q(expr: AtomView<'_>, x: Symbol) -> bool {
8677    match expr {
8678        AtomView::Pow(power) => {
8679            let (base, exponent) = power.get_base_exp();
8680            let fractional =
8681                rational_number_view(exponent).is_some_and(|(_, denominator)| denominator != 1);
8682            (!fractional || matches!(base, AtomView::Var(variable) if variable.get_symbol() == x))
8683                && rubi_fractional_power_bases_are_variable_q(base, x)
8684        }
8685        AtomView::Add(add) => add
8686            .into_iter()
8687            .all(|term| rubi_fractional_power_bases_are_variable_q(term, x)),
8688        AtomView::Mul(mul) => mul
8689            .into_iter()
8690            .all(|factor| rubi_fractional_power_bases_are_variable_q(factor, x)),
8691        AtomView::Num(_) | AtomView::Var(_) => true,
8692        AtomView::Fun(_) => false,
8693    }
8694}
8695
8696fn rubi_subst_for_fractional_power_of_linear(
8697    expr: &Atom,
8698    x: Symbol,
8699    sub: Symbol,
8700) -> Option<RubiSubstForFractionalPowerOfLinear> {
8701    let (denominator, base) = rubi_fractional_power_of_linear(expr, x)?;
8702    if denominator <= 1 {
8703        return None;
8704    }
8705    let a = polynomial_coefficient(&base, x, 0)?;
8706    let b = polynomial_coefficient(&base, x, 1)?;
8707    if b.is_zero() {
8708        return None;
8709    }
8710
8711    let sub_atom = Atom::var(sub);
8712    let replacement = -&a / &b + sub_atom.pow(denominator) / &b;
8713    let transformed =
8714        rubi_subst_for_fractional_power(expr, &base, denominator, x, sub, &replacement)?;
8715    let tmp = rubi_mathematica_simplify_in(&(sub_atom.pow(denominator - 1) * transformed), sub);
8716    let integrand = rubi_nonfree_factors(&tmp, sub);
8717    let multiplier = rubi_free_factors(&tmp, sub) / &b;
8718
8719    Some(RubiSubstForFractionalPowerOfLinear {
8720        integrand,
8721        denominator,
8722        base,
8723        multiplier,
8724    })
8725}
8726
8727fn rubi_matching_rational_power_factor(factors: &[Atom], base: &Atom) -> Option<(usize, Rational)> {
8728    factors.iter().enumerate().find_map(|(index, factor)| {
8729        let (factor_base, factor_exponent) = rubi_factor_base_exponent(factor);
8730        (factor_base == *base)
8731            .then(|| {
8732                rational_number(&factor_exponent).map(|exponent| (index, Rational::from(exponent)))
8733            })
8734            .flatten()
8735    })
8736}
8737
8738fn rubi_fractional_power_of_linear(expr: &Atom, x: Symbol) -> Option<(i64, Atom)> {
8739    fn lcm_i64(a: i64, b: i64) -> i64 {
8740        fn gcd_i64(mut a: i64, mut b: i64) -> i64 {
8741            a = a.abs();
8742            b = b.abs();
8743            while b != 0 {
8744                let r = a % b;
8745                a = b;
8746                b = r;
8747            }
8748            a
8749        }
8750
8751        if a == 0 || b == 0 {
8752            0
8753        } else {
8754            (a / gcd_i64(a, b)) * b
8755        }
8756    }
8757
8758    fn recur(expr: &Atom, x: Symbol, denominator: &mut i64, base: &mut Option<Atom>) -> Option<()> {
8759        if atom_q(expr.as_view()) || is_free_of(expr, x) {
8760            return Some(());
8761        }
8762
8763        match expr.as_view() {
8764            AtomView::Pow(power) => {
8765                let (pow_base, pow_exponent) = power.get_base_exp();
8766                let pow_base = pow_base.to_owned();
8767                let pow_exponent = pow_exponent.to_owned();
8768                if rubi_linear_q(pow_base.as_view(), x) {
8769                    if let Some((_, exponent_denominator)) = rational_number(&pow_exponent) {
8770                        if exponent_denominator > 1 {
8771                            let matches_selected_base = match base {
8772                                Some(existing_base) => {
8773                                    (existing_base.to_owned() - &pow_base).expand().is_zero()
8774                                }
8775                                None => true,
8776                            };
8777                            if matches_selected_base {
8778                                if base.is_none() {
8779                                    *base = Some(pow_base);
8780                                }
8781                                *denominator = lcm_i64(*denominator, exponent_denominator);
8782                                return Some(());
8783                            }
8784                        }
8785                    }
8786                }
8787
8788                recur(&pow_base, x, denominator, base)?;
8789                recur(&pow_exponent, x, denominator, base)
8790            }
8791            AtomView::Add(add) => {
8792                for term in add {
8793                    recur(&term.to_owned(), x, denominator, base)?;
8794                }
8795                Some(())
8796            }
8797            AtomView::Mul(mul) => {
8798                let factors = rubi_mathematica_fractional_linear_scan_order(
8799                    mul.into_iter().map(|factor| factor.to_owned()).collect(),
8800                    x,
8801                );
8802                for factor in factors {
8803                    recur(&factor, x, denominator, base)?;
8804                }
8805                Some(())
8806            }
8807            AtomView::Fun(fun) => {
8808                for argument in fun {
8809                    recur(&argument.to_owned(), x, denominator, base)?;
8810                }
8811                Some(())
8812            }
8813            AtomView::Num(_) | AtomView::Var(_) => Some(()),
8814        }
8815    }
8816
8817    let mut denominator = 1;
8818    let mut base = None;
8819    recur(expr, x, &mut denominator, &mut base)?;
8820    base.map(|base| (denominator, base))
8821}
8822
8823fn rubi_mathematica_fractional_linear_scan_order(mut factors: Vec<Atom>, x: Symbol) -> Vec<Atom> {
8824    // Mathematica's canonical Times order scans negative fractional powers from
8825    // denominator factors before positive numerator powers in Rubi's
8826    // FractionalPowerOfLinear helper. Symbolica can present the same quotient
8827    // with positive numerator factors first, which changes the substitution
8828    // base for symmetric algebraic quotients.
8829    factors.sort_by_key(|factor| {
8830        let (base, exponent) = rubi_factor_base_exponent(factor);
8831        if rubi_linear_q(base.as_view(), x)
8832            && rational_number(&exponent)
8833                .is_some_and(|(numerator, denominator)| numerator < 0 && denominator > 1)
8834        {
8835            0
8836        } else {
8837            1
8838        }
8839    });
8840    factors
8841}
8842
8843/// Substitution data for a fractional power of a quotient of affine expressions.
8844struct RubiSubstForFractionalPowerOfQuotientOfLinears {
8845    integrand: Atom,
8846    denominator: i64,
8847    base: Atom,
8848    multiplier: Atom,
8849}
8850
8851fn rubi_subst_for_fractional_power_of_quotient_of_linears(
8852    expr: &Atom,
8853    x: Symbol,
8854    sub: Symbol,
8855) -> Option<RubiSubstForFractionalPowerOfQuotientOfLinears> {
8856    let (denominator, base, a, b, c, d) = rubi_fractional_power_of_quotient_of_linears(expr, x)?;
8857    if denominator <= 1 {
8858        return None;
8859    }
8860
8861    let sub_atom = Atom::var(sub);
8862    let sub_power = sub_atom.pow(denominator);
8863    let replacement = (-&a + &c * &sub_power) / (&b - &d * &sub_power);
8864    let transformed =
8865        rubi_subst_for_fractional_power(expr, &base, denominator, x, sub, &replacement)?;
8866    let tmp = rubi_together_simplify(
8867        &(sub_atom.pow(denominator - 1) * transformed
8868            / (&b - &d * sub_atom.pow(denominator)).pow(2)),
8869    );
8870    let tmp = rubi_normalize_sum_factors(tmp.as_view());
8871    let integrand = rubi_nonfree_factors(&tmp, sub);
8872    let multiplier = rubi_free_factors(&tmp, sub) * (&b * &c - &a * &d);
8873
8874    Some(RubiSubstForFractionalPowerOfQuotientOfLinears {
8875        integrand,
8876        denominator,
8877        base,
8878        multiplier,
8879    })
8880}
8881
8882fn rubi_fractional_power_of_quotient_of_linears(
8883    expr: &Atom,
8884    x: Symbol,
8885) -> Option<(i64, Atom, Atom, Atom, Atom, Atom)> {
8886    fn gcd_i64(mut a: i64, mut b: i64) -> i64 {
8887        a = a.abs();
8888        b = b.abs();
8889        while b != 0 {
8890            let r = a % b;
8891            a = b;
8892            b = r;
8893        }
8894        a
8895    }
8896
8897    fn lcm_i64(a: i64, b: i64) -> i64 {
8898        if a == 0 || b == 0 {
8899            0
8900        } else {
8901            (a / gcd_i64(a, b)) * b
8902        }
8903    }
8904
8905    fn recur(expr: &Atom, x: Symbol, denominator: &mut i64, base: &mut Option<Atom>) -> Option<()> {
8906        if atom_q(expr.as_view()) || is_free_of(expr, x) {
8907            return Some(());
8908        }
8909
8910        match expr.as_view() {
8911            AtomView::Pow(power) => {
8912                let (pow_base, pow_exponent) = power.get_base_exp();
8913                let pow_base = pow_base.to_owned();
8914                let pow_exponent = pow_exponent.to_owned();
8915                if rubi_quotient_of_linears_coefficients(&pow_base, x).is_some() {
8916                    if let Some((_, exponent_denominator)) = rational_number(&pow_exponent) {
8917                        if exponent_denominator > 1 {
8918                            let matches_selected_base = match base {
8919                                Some(existing_base) => {
8920                                    (existing_base.to_owned() - &pow_base).expand().is_zero()
8921                                }
8922                                None => true,
8923                            };
8924                            if matches_selected_base {
8925                                if base.is_none() {
8926                                    *base = Some(pow_base);
8927                                }
8928                                *denominator = lcm_i64(*denominator, exponent_denominator);
8929                                return Some(());
8930                            }
8931                        }
8932                    }
8933                }
8934
8935                recur(&pow_base, x, denominator, base)?;
8936                recur(&pow_exponent, x, denominator, base)
8937            }
8938            AtomView::Add(add) => {
8939                for term in add {
8940                    recur(&term.to_owned(), x, denominator, base)?;
8941                }
8942                Some(())
8943            }
8944            AtomView::Mul(mul) => {
8945                for factor in mul {
8946                    recur(&factor.to_owned(), x, denominator, base)?;
8947                }
8948                Some(())
8949            }
8950            AtomView::Fun(fun) => {
8951                for argument in fun {
8952                    recur(&argument.to_owned(), x, denominator, base)?;
8953                }
8954                Some(())
8955            }
8956            AtomView::Num(_) | AtomView::Var(_) => Some(()),
8957        }
8958    }
8959
8960    let mut denominator = 1;
8961    let mut base = None;
8962    recur(expr, x, &mut denominator, &mut base)?;
8963    let base = base?;
8964    let (a, b, c, d) = rubi_quotient_of_linears_coefficients(&base, x)?;
8965    Some((denominator, base, a, b, c, d))
8966}
8967
8968fn rubi_subst_for_fractional_power(
8969    expr: &Atom,
8970    base: &Atom,
8971    denominator: i64,
8972    x: Symbol,
8973    sub: Symbol,
8974    replacement: &Atom,
8975) -> Option<Atom> {
8976    if (expr - base).expand().is_zero() {
8977        return Some(Atom::var(sub).pow(denominator));
8978    }
8979
8980    match expr.as_view() {
8981        AtomView::Pow(power) => {
8982            let (pow_base, pow_exponent) = power.get_base_exp();
8983            let pow_base_atom = pow_base.to_owned();
8984            let pow_exponent_atom = pow_exponent.to_owned();
8985            if (&pow_base_atom - base).expand().is_zero() {
8986                if rational_number(&pow_exponent_atom).is_none() {
8987                    return None;
8988                }
8989                return Some(Atom::var(sub).pow(pow_exponent_atom * Atom::num(denominator)));
8990            }
8991
8992            let transformed_base = rubi_subst_for_fractional_power(
8993                &pow_base_atom,
8994                base,
8995                denominator,
8996                x,
8997                sub,
8998                replacement,
8999            )?;
9000            let transformed_exponent = rubi_subst_for_fractional_power(
9001                &pow_exponent_atom,
9002                base,
9003                denominator,
9004                x,
9005                sub,
9006                replacement,
9007            )?;
9008            Some(transformed_base.pow(transformed_exponent))
9009        }
9010        AtomView::Add(add) => {
9011            let mut sum = Atom::num(0);
9012            for term in add {
9013                sum += rubi_subst_for_fractional_power(
9014                    &term.to_owned(),
9015                    base,
9016                    denominator,
9017                    x,
9018                    sub,
9019                    replacement,
9020                )?;
9021            }
9022            Some(sum)
9023        }
9024        AtomView::Mul(mul) => {
9025            let mut product = Atom::num(1);
9026            for factor in mul {
9027                product *= rubi_subst_for_fractional_power(
9028                    &factor.to_owned(),
9029                    base,
9030                    denominator,
9031                    x,
9032                    sub,
9033                    replacement,
9034                )?;
9035            }
9036            Some(product)
9037        }
9038        AtomView::Fun(fun) => {
9039            let arguments: Vec<_> = fun
9040                .into_iter()
9041                .map(|argument| {
9042                    rubi_subst_for_fractional_power(
9043                        &argument.to_owned(),
9044                        base,
9045                        denominator,
9046                        x,
9047                        sub,
9048                        replacement,
9049                    )
9050                })
9051                .collect::<Option<Vec<_>>>()?;
9052            Some(fun.get_symbol().call_args(arguments))
9053        }
9054        AtomView::Var(variable) if variable.get_symbol() == x => Some(replacement.to_owned()),
9055        AtomView::Num(_) | AtomView::Var(_) => Some(expr.to_owned()),
9056    }
9057}
9058
9059fn subst_for_power_term(
9060    term: AtomView<'_>,
9061    x: Symbol,
9062    x_atom: &Atom,
9063    sub_atom: &Atom,
9064    power: (i64, i64),
9065) -> Option<Atom> {
9066    let degree = monomial_rational_degree(term, x)?;
9067    let multiple = rational_degree_multiple(degree, power)?;
9068    if multiple < 0 {
9069        return None;
9070    }
9071
9072    let coefficient = (term.to_owned() / x_atom.pow(rational_atom(degree)))
9073        .expand()
9074        .cancel();
9075    Some(coefficient * sub_atom.pow(multiple))
9076}
9077
9078fn rational_degree_multiple(degree: (i64, i64), power: (i64, i64)) -> Option<i64> {
9079    let numerator = degree.0.checked_mul(power.1)?;
9080    let denominator = degree.1.checked_mul(power.0)?;
9081    if denominator == 0 || numerator % denominator != 0 {
9082        return None;
9083    }
9084
9085    Some(numerator / denominator)
9086}
9087
9088fn rational_degree_is_nonnegative_multiple(degree: (i64, i64), power: (i64, i64)) -> bool {
9089    let Some(numerator) = degree.0.checked_mul(power.1) else {
9090        return false;
9091    };
9092    let Some(denominator) = degree.1.checked_mul(power.0) else {
9093        return false;
9094    };
9095    if denominator == 0 || numerator % denominator != 0 {
9096        return false;
9097    }
9098
9099    numerator / denominator >= 0
9100}
9101
9102fn monomial_rational_degree(term: AtomView<'_>, x: Symbol) -> Option<(i64, i64)> {
9103    if is_free_of(term, x) {
9104        return Some((0, 1));
9105    }
9106
9107    match term {
9108        AtomView::Var(variable) if variable.get_symbol() == x => Some((1, 1)),
9109        AtomView::Pow(power) => {
9110            let (base, exponent) = power.get_base_exp();
9111            match base {
9112                AtomView::Var(variable) if variable.get_symbol() == x => {
9113                    rational_number_view(exponent)
9114                }
9115                _ => None,
9116            }
9117        }
9118        AtomView::Mul(mul) => {
9119            let mut degree = (0_i64, 1_i64);
9120            for factor in mul {
9121                if is_free_of(factor, x) {
9122                    continue;
9123                }
9124
9125                let factor_degree = match factor {
9126                    AtomView::Var(variable) if variable.get_symbol() == x => (1, 1),
9127                    AtomView::Pow(power) => {
9128                        let (base, exponent) = power.get_base_exp();
9129                        match base {
9130                            AtomView::Var(variable) if variable.get_symbol() == x => {
9131                                rational_number_view(exponent)?
9132                            }
9133                            _ => return None,
9134                        }
9135                    }
9136                    _ => return None,
9137                };
9138                degree = add_rational_degrees(degree, factor_degree)?;
9139            }
9140
9141            Some(degree)
9142        }
9143        _ => None,
9144    }
9145}
9146
9147fn add_rational_degrees(left: (i64, i64), right: (i64, i64)) -> Option<(i64, i64)> {
9148    let numerator = left
9149        .0
9150        .checked_mul(right.1)?
9151        .checked_add(right.0.checked_mul(left.1)?)?;
9152    let denominator = left.1.checked_mul(right.1)?;
9153    normalize_rational_i64(numerator, denominator)
9154}
9155
9156fn normalize_rational_i64(numerator: i64, denominator: i64) -> Option<(i64, i64)> {
9157    if denominator == 0 {
9158        return None;
9159    }
9160    let sign = if denominator < 0 { -1 } else { 1 };
9161    let numerator = numerator.checked_mul(sign)?;
9162    let denominator = denominator.checked_mul(sign)?;
9163    let gcd = integer_gcd(numerator, denominator);
9164    Some((numerator / gcd, denominator / gcd))
9165}
9166
9167fn polynomial_degree(expr: &Atom, x: Symbol) -> Option<i64> {
9168    collect_polynomial_terms(expr, x)?
9169        .keys()
9170        .next_back()
9171        .copied()
9172}
9173
9174fn rubi_expon<T: AtomCore>(expr: T, x: Symbol) -> Option<i64> {
9175    polynomial_degree(&expr.as_atom_view().to_owned().together(), x)
9176}
9177
9178fn rubi_expon_min(expr: &Atom, x: Symbol) -> Option<i64> {
9179    collect_polynomial_terms(&expr.together(), x)?
9180        .keys()
9181        .next()
9182        .copied()
9183}
9184
9185fn rubi_expon_power(expr: &Atom, x: Symbol, power: &Atom) -> Option<i64> {
9186    let (power_numerator, power_denominator) = rational_number(power)?;
9187    if power_denominator != 1 || power_numerator <= 0 {
9188        return None;
9189    }
9190
9191    let terms = collect_polynomial_terms(&expr.together(), x)?;
9192    if terms.keys().any(|degree| degree % power_numerator != 0) {
9193        return None;
9194    }
9195
9196    terms
9197        .keys()
9198        .next_back()
9199        .map(|degree| degree / power_numerator)
9200}
9201
9202fn polynomial_leading_term(expr: &Atom, x: Symbol) -> Option<(i64, Atom)> {
9203    collect_polynomial_terms(expr, x)?.into_iter().next_back()
9204}
9205
9206fn polynomial_coefficient(expr: &Atom, x: Symbol, degree: i64) -> Option<Atom> {
9207    let terms = collect_polynomial_terms(expr, x)?;
9208    Some(terms.get(&degree).cloned().unwrap_or_else(|| Atom::num(0)))
9209}
9210
9211fn rubi_coeff(expr: &Atom, x: Symbol, degree: i64) -> Option<Atom> {
9212    let together_coefficient = polynomial_coefficient(&expr.together(), x, degree)?;
9213    let Some(coefficient) = polynomial_coefficient(expr, x, degree) else {
9214        return Some(together_coefficient);
9215    };
9216    if rubi_algebraic_zero_q(&(&coefficient - &together_coefficient)) {
9217        Some(coefficient)
9218    } else {
9219        Some(together_coefficient)
9220    }
9221}
9222
9223fn rubi_coefficient(expr: &Atom, x: Symbol, degree: i64) -> Option<Atom> {
9224    rubi_coeff(expr, x, degree)
9225}
9226
9227fn rubi_linear_q<T: AtomCore>(expr: T, x: Symbol) -> bool {
9228    rubi_expon(expr, x).is_some_and(|degree| degree == 1)
9229}
9230
9231fn rubi_linear_q_list(exprs: &[&Atom], x: Symbol) -> bool {
9232    exprs.iter().all(|expr| rubi_linear_q(expr.as_view(), x))
9233}
9234
9235fn rubi_linear_power_q(expr: &Atom, x: Symbol) -> bool {
9236    let (base, exponent) = match expr.as_view() {
9237        AtomView::Pow(power) => {
9238            let (base, exponent) = power.get_base_exp();
9239            (base.to_owned(), exponent.to_owned())
9240        }
9241        _ => (expr.to_owned(), Atom::num(1)),
9242    };
9243
9244    is_free_of(&exponent, x) && rubi_linear_match_q(&base, x)
9245}
9246
9247fn rubi_quotient_of_linears_coefficients(
9248    expr: &Atom,
9249    x: Symbol,
9250) -> Option<(Atom, Atom, Atom, Atom)> {
9251    if !rubi_quotient_of_linears_p(expr, x) {
9252        return None;
9253    }
9254    let (a, b, c, d) = rubi_quotient_of_linears_parts(expr, x)?;
9255    if neq!(b, 0) && neq!(d, 0) {
9256        Some((a, b, c, d))
9257    } else {
9258        None
9259    }
9260}
9261
9262fn rubi_quotient_of_linears_p(u: &Atom, x: Symbol) -> bool {
9263    if is_free_of(u, x) || u == &Atom::var(x) || rubi_linear_q(u.as_view(), x) {
9264        return true;
9265    }
9266
9267    if let Some((base, exponent)) = rubi_power_base_exponent(u) {
9268        return eqq!(exponent, -1) && rubi_quotient_of_linears_p(&base, x);
9269    }
9270
9271    if let AtomView::Mul(_) = u.as_view() {
9272        if let Some((nonfree_factor, _rest)) =
9273            rubi_split_product(|factor| !is_free_of(factor, x), u)
9274                .filter(|(_, rest)| is_free_of(rest, x))
9275        {
9276            return rubi_quotient_of_linears_p(&nonfree_factor, x);
9277        }
9278    }
9279
9280    if let AtomView::Add(add) = u.as_view() {
9281        let terms: Vec<Atom> = add.into_iter().map(|term| term.to_owned()).collect();
9282        let nonfree_terms: Vec<Atom> = terms
9283            .into_iter()
9284            .filter(|term| !is_free_of(term, x))
9285            .collect();
9286        if nonfree_terms.len() == 1 {
9287            return rubi_quotient_of_linears_p(&nonfree_terms[0], x);
9288        }
9289    }
9290
9291    if let Some((numerator, denominator)) = rubi_quotient_pair(u) {
9292        return rubi_linear_q(numerator.as_view(), x) && rubi_linear_q(denominator.as_view(), x);
9293    }
9294
9295    false
9296}
9297
9298fn rubi_quotient_of_linears_parts(u: &Atom, x: Symbol) -> Option<(Atom, Atom, Atom, Atom)> {
9299    if u == &Atom::var(x) {
9300        return Some((Atom::num(0), Atom::num(1), Atom::num(1), Atom::num(0)));
9301    }
9302    if is_free_of(u, x) {
9303        return Some((u.to_owned(), Atom::num(0), Atom::num(1), Atom::num(0)));
9304    }
9305    if rubi_linear_q(u.as_view(), x) {
9306        return Some((
9307            rubi_coefficient(u, x, 0)?,
9308            rubi_coefficient(u, x, 1)?,
9309            Atom::num(1),
9310            Atom::num(0),
9311        ));
9312    }
9313
9314    if let AtomView::Mul(_) = u.as_view() {
9315        if let Some((free_factor, rest)) = rubi_split_product(|factor| !is_free_of(factor, x), u)
9316            .filter(|(_, rest)| is_free_of(rest, x))
9317        {
9318            let (a, b, c, d) = rubi_quotient_of_linears_parts(&free_factor, x)?;
9319            return Some((rest.to_owned() * a, rest * b, c, d));
9320        }
9321    }
9322
9323    if let AtomView::Add(add) = u.as_view() {
9324        let terms: Vec<Atom> = add.into_iter().map(|term| term.to_owned()).collect();
9325        let free_sum = terms
9326            .iter()
9327            .filter(|term| is_free_of(*term, x))
9328            .cloned()
9329            .fold(Atom::num(0), |acc, term| acc + term);
9330        let nonfree_terms: Vec<Atom> = terms
9331            .into_iter()
9332            .filter(|term| !is_free_of(term, x))
9333            .collect();
9334        if nonfree_terms.len() == 1 {
9335            let (a, b, c, d) = rubi_quotient_of_linears_parts(&nonfree_terms[0], x)?;
9336            return Some((a + free_sum.to_owned() * &c, b + free_sum * &d, c, d));
9337        }
9338    }
9339
9340    if let Some((base, exponent)) = rubi_power_base_exponent(u) {
9341        if eqq!(exponent, -1) {
9342            let (a, b, c, d) = rubi_quotient_of_linears_parts(&base, x)?;
9343            return Some((c, d, a, b));
9344        }
9345    }
9346
9347    if let Some((numerator, denominator)) = rubi_quotient_pair(u) {
9348        if rubi_linear_q(numerator.as_view(), x) && rubi_linear_q(denominator.as_view(), x) {
9349            return Some((
9350                rubi_coefficient(&numerator, x, 0)?,
9351                rubi_coefficient(&numerator, x, 1)?,
9352                rubi_coefficient(&denominator, x, 0)?,
9353                rubi_coefficient(&denominator, x, 1)?,
9354            ));
9355        }
9356    }
9357
9358    None
9359}
9360
9361fn rubi_power_base_exponent(u: &Atom) -> Option<(Atom, Atom)> {
9362    match u.as_view() {
9363        AtomView::Pow(power) => Some((power.get_base().to_owned(), power.get_exp().to_owned())),
9364        _ => None,
9365    }
9366}
9367
9368fn rubi_quotient_pair(u: &Atom) -> Option<(Atom, Atom)> {
9369    let AtomView::Mul(mul) = u.as_view() else {
9370        return None;
9371    };
9372
9373    let mut numerator = Vec::new();
9374    let mut denominator = Vec::new();
9375    for factor in mul {
9376        let factor = factor.to_owned();
9377        if let Some((base, exponent)) = rubi_power_base_exponent(&factor) {
9378            if eqq!(exponent, -1) {
9379                denominator.push(base);
9380                continue;
9381            }
9382        }
9383        numerator.push(factor);
9384    }
9385
9386    (!denominator.is_empty()).then(|| (product_atoms(&numerator), product_atoms(&denominator)))
9387}
9388
9389fn rubi_quadratic_q(expr: &Atom, x: Symbol) -> bool {
9390    rubi_expon(expr.as_view(), x).is_some_and(|degree| degree == 2)
9391}
9392
9393fn rubi_divides(divisor: &Atom, dividend: &Atom, x: Symbol) -> Option<Atom> {
9394    let quotient = rubi_simplify(&(dividend / divisor));
9395    if freeq!(quotient, x) {
9396        Some(quotient)
9397    } else {
9398        None
9399    }
9400}
9401
9402/// Decomposition used for functions of a square root of a quadratic.
9403struct RubiFunctionOfSquareRootOfQuadratic {
9404    integrand: Atom,
9405    substitution: Atom,
9406    case_kind: RubiSquareRootQuadraticCase,
9407    substitution_symbol: Symbol,
9408    _substitution_guard: FreshSubstitutionSymbol,
9409}
9410
9411#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9412/// The supported substitution shapes for square roots of quadratics.
9413enum RubiSquareRootQuadraticCase {
9414    PositiveA,
9415    PositiveC,
9416    NegativeAAndC,
9417}
9418
9419fn rubi_euler_integrand_q(expr: &Atom, x: Symbol) -> bool {
9420    if let Some((u, n, p)) = rubi_euler_linear_power(expr, x) {
9421        return integerq!(&n + Atom::num(1) / Atom::num(2))
9422            && rubi_quadratic_q(&u, x)
9423            && (!rationalq!(p) || iltq!(p, 0) && !rubi_binomial_q(u.as_view(), x));
9424    }
9425
9426    if let Some((v, m, u, n, p)) = rubi_euler_product_linear_power(expr, x) {
9427        return polynomial_difference_is_zero(&u, &v)
9428            && integersq!([Atom::num(2) * &m, &n + Atom::num(1) / Atom::num(2)])
9429            && rubi_quadratic_q(&u, x)
9430            && (!rationalq!(p) || iltq!(p, 0) && !rubi_binomial_q(u.as_view(), x));
9431    }
9432
9433    if let Some((u, n, v, p)) = rubi_euler_product_of_quadratic_powers(expr, x) {
9434        return iltq!(p, 0)
9435            && integerq!(&n + Atom::num(1) / Atom::num(2))
9436            && rubi_quadratic_q(&u, x)
9437            && rubi_quadratic_q(&v, x)
9438            && !rubi_binomial_q(v.as_view(), x);
9439    }
9440
9441    false
9442}
9443
9444fn rubi_euler_linear_power(expr: &Atom, x: Symbol) -> Option<(Atom, Atom, Atom)> {
9445    let owned_factor;
9446    let factor = match expr.as_view() {
9447        AtomView::Pow(_) => expr,
9448        _ => {
9449            owned_factor = rubi_single_nonconstant_factor(expr, x)?;
9450            &owned_factor
9451        }
9452    };
9453    let AtomView::Pow(power) = factor.as_view() else {
9454        return None;
9455    };
9456    let (base, p) = power.get_base_exp();
9457    let (_, u, n) = rubi_euler_linear_base(&base.to_owned(), x)?;
9458    Some((u, n, p.to_owned()))
9459}
9460
9461fn rubi_single_nonconstant_factor(expr: &Atom, x: Symbol) -> Option<Atom> {
9462    let mut found = None;
9463    for factor in rubi_product_factors(expr) {
9464        if freeq!(factor, x) {
9465            continue;
9466        }
9467        if found.is_some() {
9468            return None;
9469        }
9470        found = Some(factor);
9471    }
9472    found
9473}
9474
9475fn rubi_euler_product_linear_power(
9476    expr: &Atom,
9477    x: Symbol,
9478) -> Option<(Atom, Atom, Atom, Atom, Atom)> {
9479    let factors = rubi_product_factors(expr);
9480    for (linear_index, linear_factor) in factors.iter().enumerate() {
9481        let AtomView::Pow(linear_power) = linear_factor.as_view() else {
9482            continue;
9483        };
9484        let (_, u, n) = rubi_euler_linear_base(&linear_power.get_base().to_owned(), x)?;
9485        for (quadratic_index, quadratic_factor) in factors.iter().enumerate() {
9486            if quadratic_index == linear_index {
9487                continue;
9488            }
9489            let (v, m) = rubi_quadratic_power_factor(quadratic_factor, x)?;
9490            return Some((v, m, u, n, linear_power.get_exp().to_owned()));
9491        }
9492    }
9493    None
9494}
9495
9496fn rubi_euler_product_of_quadratic_powers(
9497    expr: &Atom,
9498    x: Symbol,
9499) -> Option<(Atom, Atom, Atom, Atom)> {
9500    let factors = rubi_product_factors(expr);
9501    for (first_index, first_factor) in factors.iter().enumerate() {
9502        let (u, n) = rubi_quadratic_power_factor(first_factor, x)?;
9503        for (second_index, second_factor) in factors.iter().enumerate() {
9504            if second_index == first_index {
9505                continue;
9506            }
9507            let (v, p) = rubi_quadratic_power_factor(second_factor, x)?;
9508            return Some((u, n, v, p));
9509        }
9510    }
9511    None
9512}
9513
9514fn rubi_euler_linear_base(base: &Atom, x: Symbol) -> Option<(Atom, Atom, Atom)> {
9515    let terms = rubi_add_terms(base);
9516    if terms.len() != 2 {
9517        return None;
9518    }
9519
9520    let first_x = rubi_scaled_x_term(&terms[0], x);
9521    let second_x = rubi_scaled_x_term(&terms[1], x);
9522    let first_power = rubi_scaled_quadratic_power_term(&terms[0], x);
9523    let second_power = rubi_scaled_quadratic_power_term(&terms[1], x);
9524
9525    match (first_x, second_x, first_power, second_power) {
9526        (Some(a), None, None, Some((b, u, n))) if freeq!([a, b], x) => Some((b, u, n)),
9527        (None, Some(a), Some((b, u, n)), None) if freeq!([a, b], x) => Some((b, u, n)),
9528        _ => None,
9529    }
9530}
9531
9532fn rubi_scaled_x_term(term: &Atom, x: Symbol) -> Option<Atom> {
9533    if *term == x {
9534        return Some(Atom::num(1));
9535    }
9536
9537    let factors = rubi_product_factors(term);
9538    let mut found_x = false;
9539    let mut coeff = Atom::num(1);
9540    for factor in factors {
9541        if factor == x {
9542            if found_x {
9543                return None;
9544            }
9545            found_x = true;
9546        } else {
9547            if !freeq!(factor, x) {
9548                return None;
9549            }
9550            coeff *= factor;
9551        }
9552    }
9553
9554    found_x.then_some(coeff)
9555}
9556
9557fn rubi_scaled_quadratic_power_term(term: &Atom, x: Symbol) -> Option<(Atom, Atom, Atom)> {
9558    let factors = rubi_product_factors(term);
9559    let mut found = None;
9560    let mut coeff = Atom::num(1);
9561    for factor in factors {
9562        if let Some((u, n)) = rubi_quadratic_power_factor(&factor, x) {
9563            if found.is_some() {
9564                return None;
9565            }
9566            found = Some((u, n));
9567        } else {
9568            if !freeq!(factor, x) {
9569                return None;
9570            }
9571            coeff *= factor;
9572        }
9573    }
9574
9575    let (u, n) = found?;
9576    Some((coeff, u, n))
9577}
9578
9579fn rubi_quadratic_power_factor(factor: &Atom, x: Symbol) -> Option<(Atom, Atom)> {
9580    if rubi_quadratic_q(factor, x) {
9581        return Some((factor.to_owned(), Atom::num(1)));
9582    }
9583
9584    let AtomView::Pow(power) = factor.as_view() else {
9585        return None;
9586    };
9587    let base = power.get_base().to_owned();
9588    if rubi_quadratic_q(&base, x) {
9589        Some((base, power.get_exp().to_owned()))
9590    } else {
9591        None
9592    }
9593}
9594
9595fn rubi_function_of_square_root_of_quadratic(
9596    expr: &Atom,
9597    x: Symbol,
9598) -> Option<RubiFunctionOfSquareRootOfQuadratic> {
9599    let quadratic = rubi_square_root_quadratic_base(expr, x)?;
9600    let a = rubi_coeff(&quadratic, x, 0)?;
9601    let b = rubi_coeff(&quadratic, x, 1)?;
9602    let c = rubi_coeff(&quadratic, x, 2)?;
9603    if c.is_zero() {
9604        return None;
9605    }
9606
9607    let substitution_guard = fresh_substitution_symbol()?;
9608    let sub = substitution_guard.symbol();
9609    let t = Atom::var(sub);
9610    let radical = quadratic.sqrt();
9611    let sqrt_a = a.sqrt();
9612    let sqrt_c = c.sqrt();
9613    let discriminant_sqrt = (&b * &b - Atom::num(4) * &a * &c).sqrt();
9614
9615    let (radical_replacement, x_replacement, jacobian, substitution, case_kind) = if gtq!(a, 0) {
9616        let denominator = &c - t.pow(2);
9617        (
9618            (&c * &sqrt_a - &b * &t + &sqrt_a * t.pow(2)) / &denominator,
9619            (-&b + Atom::num(2) * &sqrt_a * &t) / &denominator,
9620            (&c * &sqrt_a - &b * &t + &sqrt_a * t.pow(2)) / denominator.pow(2),
9621            (-&sqrt_a + radical.to_owned()) / Atom::var(x),
9622            RubiSquareRootQuadraticCase::PositiveA,
9623        )
9624    } else if gtq!(c, 0) {
9625        let denominator = &b + Atom::num(2) * &sqrt_c * &t;
9626        (
9627            (&a * &sqrt_c + &b * &t + &sqrt_c * t.pow(2)) / &denominator,
9628            (-&a + t.pow(2)) / &denominator,
9629            (&a * &sqrt_c + &b * &t + &sqrt_c * t.pow(2)) / denominator.pow(2),
9630            &sqrt_c * Atom::var(x) + radical.to_owned(),
9631            RubiSquareRootQuadraticCase::PositiveC,
9632        )
9633    } else {
9634        let denominator = &c - t.pow(2);
9635        (
9636            -&discriminant_sqrt * &t / &denominator,
9637            (&b * &c + &c * &discriminant_sqrt + (-&b + &discriminant_sqrt) * t.pow(2))
9638                / (-Atom::num(2) * &c * &denominator),
9639            -&discriminant_sqrt * &t / denominator.pow(2),
9640            Atom::num(2) * &c * radical.to_owned()
9641                / (&b - &discriminant_sqrt + Atom::num(2) * &c * Atom::var(x)),
9642            RubiSquareRootQuadraticCase::NegativeAAndC,
9643        )
9644    };
9645
9646    let transformed =
9647        rubi_square_root_of_quadratic_subst(expr, &radical_replacement, &x_replacement, x);
9648    if !freeq!(transformed, x) {
9649        return None;
9650    }
9651
9652    let integrand = (transformed * jacobian).cancel();
9653    let integrand = rubi_normalize_numeric_roots(integrand.as_view());
9654    let integrand = rubi_collect_polynomial_power_bases(&integrand, sub);
9655    let integrand = rubi_normalize_lead_term_signs(&integrand);
9656    let integrand = rubi_expand_polynomial_numerator_over_denominator_powers(&integrand, sub);
9657    let integrand = rubi_collect_polynomial_power_bases(&integrand, sub);
9658
9659    Some(RubiFunctionOfSquareRootOfQuadratic {
9660        integrand,
9661        substitution,
9662        case_kind,
9663        substitution_symbol: sub,
9664        _substitution_guard: substitution_guard,
9665    })
9666}
9667
9668fn rubi_square_root_of_quadratic_subst(expr: &Atom, vv: &Atom, xx: &Atom, x: Symbol) -> Atom {
9669    match expr.as_view() {
9670        AtomView::Var(variable) if variable.get_symbol() == x => xx.to_owned(),
9671        atom if atom_q(atom) || is_free_of(atom, x) => expr.to_owned(),
9672        AtomView::Pow(power) => {
9673            let (base, exponent) = power.get_base_exp();
9674            let base = base.to_owned();
9675            let exponent = exponent.to_owned();
9676            if freeq!(exponent, x) {
9677                if rational_number(&exponent).is_some_and(|(_, denominator)| denominator == 2)
9678                    && polynomial_degree(&base, x).is_some_and(|degree| degree == 2)
9679                {
9680                    if let Some((numerator, _)) = rational_number(&exponent) {
9681                        return vv.pow(numerator);
9682                    }
9683                }
9684
9685                let base = rubi_square_root_of_quadratic_subst(&base, vv, xx, x);
9686                return rubi_power_together_quotient(base, exponent);
9687            }
9688
9689            let base = rubi_square_root_of_quadratic_subst(&base, vv, xx, x);
9690            let exponent = rubi_square_root_of_quadratic_subst(&exponent, vv, xx, x);
9691            rubi_power_together_quotient(base, exponent)
9692        }
9693        AtomView::Add(add) => add
9694            .into_iter()
9695            .map(|term| rubi_square_root_of_quadratic_subst(&term.to_owned(), vv, xx, x))
9696            .fold(Atom::num(0), |sum, term| sum + term),
9697        AtomView::Mul(mul) => mul
9698            .into_iter()
9699            .map(|factor| rubi_square_root_of_quadratic_subst(&factor.to_owned(), vv, xx, x))
9700            .fold(Atom::num(1), |product, factor| product * factor),
9701        AtomView::Fun(function) => {
9702            let args: Vec<_> = function
9703                .into_iter()
9704                .map(|argument| {
9705                    rubi_square_root_of_quadratic_subst(&argument.to_owned(), vv, xx, x)
9706                })
9707                .collect();
9708            function.get_symbol().call_args(args)
9709        }
9710        AtomView::Var(_) | AtomView::Num(_) => expr.to_owned(),
9711    }
9712}
9713
9714fn rubi_power_together_quotient(base: Atom, exponent: Atom) -> Atom {
9715    let base = rubi_together(&base);
9716    let Some(exponent_integer) = integer_i64(&exponent) else {
9717        return base.pow(exponent);
9718    };
9719    let Some((numerator, denominator)) = rubi_quotient_pair(&base) else {
9720        return base.pow(exponent);
9721    };
9722
9723    if exponent_integer < 0 {
9724        denominator.pow(-exponent_integer) / numerator.pow(-exponent_integer)
9725    } else {
9726        numerator.pow(exponent_integer) / denominator.pow(exponent_integer)
9727    }
9728}
9729
9730fn rubi_collect_polynomial_power_bases(expr: &Atom, x: Symbol) -> Atom {
9731    match expr.as_view() {
9732        AtomView::Pow(power) => {
9733            let (base, exponent) = power.get_base_exp();
9734            let base = rubi_collect_polynomial_power_bases(&base.to_owned(), x);
9735            let exponent = rubi_collect_polynomial_power_bases(&exponent.to_owned(), x);
9736            if is_free_of(&exponent, x) {
9737                if let Some(terms) = collect_polynomial_terms(&base, x) {
9738                    return polynomial_from_terms(&terms, x).pow(exponent);
9739                }
9740            }
9741            base.pow(exponent)
9742        }
9743        AtomView::Add(add) => add
9744            .into_iter()
9745            .map(|term| rubi_collect_polynomial_power_bases(&term.to_owned(), x))
9746            .fold(Atom::num(0), |sum, term| sum + term),
9747        AtomView::Mul(mul) => mul
9748            .into_iter()
9749            .map(|factor| rubi_collect_polynomial_power_bases(&factor.to_owned(), x))
9750            .fold(Atom::num(1), |product, factor| product * factor),
9751        AtomView::Fun(function) => {
9752            let args: Vec<_> = function
9753                .into_iter()
9754                .map(|argument| rubi_collect_polynomial_power_bases(&argument.to_owned(), x))
9755                .collect();
9756            function.get_symbol().call_args(args)
9757        }
9758        AtomView::Var(_) | AtomView::Num(_) => expr.to_owned(),
9759    }
9760}
9761
9762fn rubi_expand_polynomial_numerator_over_denominator_powers(expr: &Atom, x: Symbol) -> Atom {
9763    match expr.as_view() {
9764        AtomView::Mul(_) => {
9765            let factors = rubi_product_factors(expr);
9766            let mut numerator_factors = Vec::new();
9767            let mut other_factors = Vec::new();
9768            let mut has_polynomial_denominator_power = false;
9769
9770            for factor in factors {
9771                if let Some((base, exponent)) = rubi_power_base_exponent(&factor)
9772                    && integer_i64(&exponent).is_some_and(|integer| integer < 0)
9773                    && collect_polynomial_terms(&base, x).is_some()
9774                {
9775                    has_polynomial_denominator_power = true;
9776                    other_factors.push(factor);
9777                    continue;
9778                }
9779
9780                if collect_polynomial_terms(&factor, x).is_some() {
9781                    numerator_factors.push(factor);
9782                } else {
9783                    other_factors.push(factor);
9784                }
9785            }
9786
9787            if has_polynomial_denominator_power && numerator_factors.len() > 1 {
9788                let numerator = product_atoms(&numerator_factors).expand();
9789                let numerator = collect_polynomial_terms(&numerator, x)
9790                    .map(|terms| polynomial_from_terms(&terms, x))
9791                    .unwrap_or(numerator);
9792                return product_atoms(&[vec![numerator], other_factors].concat());
9793            }
9794
9795            expr.to_owned()
9796        }
9797        AtomView::Add(add) => add
9798            .into_iter()
9799            .map(|term| {
9800                rubi_expand_polynomial_numerator_over_denominator_powers(&term.to_owned(), x)
9801            })
9802            .fold(Atom::num(0), |sum, term| sum + term),
9803        AtomView::Pow(power) => {
9804            let (base, exponent) = power.get_base_exp();
9805            rubi_expand_polynomial_numerator_over_denominator_powers(&base.to_owned(), x).pow(
9806                rubi_expand_polynomial_numerator_over_denominator_powers(&exponent.to_owned(), x),
9807            )
9808        }
9809        AtomView::Fun(function) => {
9810            let args: Vec<_> = function
9811                .into_iter()
9812                .map(|argument| {
9813                    rubi_expand_polynomial_numerator_over_denominator_powers(
9814                        &argument.to_owned(),
9815                        x,
9816                    )
9817                })
9818                .collect();
9819            function.get_symbol().call_args(args)
9820        }
9821        AtomView::Var(_) | AtomView::Num(_) => expr.to_owned(),
9822    }
9823}
9824
9825fn rubi_square_root_quadratic_base(expr: &Atom, x: Symbol) -> Option<Atom> {
9826    let mut quadratic = None;
9827    rubi_collect_square_root_quadratic(expr.as_view(), x, &mut quadratic)?;
9828    quadratic
9829}
9830
9831fn rubi_collect_square_root_quadratic(
9832    expr: AtomView<'_>,
9833    x: Symbol,
9834    quadratic: &mut Option<Atom>,
9835) -> Option<()> {
9836    if is_free_of(expr, x) {
9837        return Some(());
9838    }
9839
9840    match expr {
9841        AtomView::Pow(power) => {
9842            let (base, exponent) = power.get_base_exp();
9843            let base_atom = base.to_owned();
9844            if rational_number_view(exponent).is_some_and(|rational| rational == (1, 2))
9845                && rubi_quadratic_q(&base_atom, x)
9846            {
9847                if let Some(existing) = quadratic {
9848                    if !polynomial_difference_is_zero(existing, &base_atom) {
9849                        return None;
9850                    }
9851                } else {
9852                    *quadratic = Some(base_atom);
9853                }
9854                return Some(());
9855            }
9856
9857            if !is_free_of(exponent, x) {
9858                return None;
9859            }
9860            rubi_collect_square_root_quadratic(base, x, quadratic)
9861        }
9862        AtomView::Add(add) => {
9863            for term in add {
9864                rubi_collect_square_root_quadratic(term, x, quadratic)?;
9865            }
9866            Some(())
9867        }
9868        AtomView::Mul(mul) => {
9869            for factor in mul {
9870                rubi_collect_square_root_quadratic(factor, x, quadratic)?;
9871            }
9872            Some(())
9873        }
9874        AtomView::Fun(function) => {
9875            for argument in function {
9876                rubi_collect_square_root_quadratic(argument, x, quadratic)?;
9877            }
9878            Some(())
9879        }
9880        AtomView::Var(_) | AtomView::Num(_) => Some(()),
9881    }
9882}
9883
9884fn rubi_quadratic_q_list(exprs: &[&Atom], x: Symbol) -> bool {
9885    exprs.iter().all(|expr| rubi_quadratic_q(expr, x))
9886}
9887
9888fn rubi_linear_match_q(expr: &Atom, x: Symbol) -> bool {
9889    rubi_linear_match_q_view(expr.as_view(), x)
9890}
9891
9892fn rubi_linear_match_q_view(expr: AtomView<'_>, x: Symbol) -> bool {
9893    let Some(terms) = collect_polynomial_terms_without_expanding_view(expr, x) else {
9894        return false;
9895    };
9896
9897    terms.keys().all(|degree| *degree == 0 || *degree == 1)
9898        && terms
9899            .get(&1)
9900            .is_some_and(|coefficient| !coefficient.expand().is_zero())
9901}
9902
9903fn rubi_linear_match_q_list(exprs: &[&Atom], x: Symbol) -> bool {
9904    exprs.iter().all(|expr| rubi_linear_match_q(expr, x))
9905}
9906
9907fn rubi_match_optional_multiplier_linear_q(expr: &Atom, x: Symbol) -> bool {
9908    rubi_split_product(|factor| rubi_linear_match_q(factor, x), expr)
9909        .is_some_and(|(_, rest)| is_free_of(&rest, x))
9910}
9911
9912fn rubi_match_optional_scaled_monomial_power_q(expr: &Atom, x: Symbol) -> bool {
9913    let (base, exponent) = match expr.as_view() {
9914        AtomView::Pow(power) => {
9915            let (base, exponent) = power.get_base_exp();
9916            (base.to_owned(), exponent.to_owned())
9917        }
9918        _ => (expr.to_owned(), Atom::num(1)),
9919    };
9920
9921    is_free_of(&exponent, x)
9922        && rubi_split_product(|factor| *factor == x, &base)
9923            .is_some_and(|(_, rest)| is_free_of(&rest, x))
9924}
9925
9926fn rubi_match_optional_scaled_monomial_power_times_q(
9927    expr: &Atom,
9928    x: Symbol,
9929    rest_match: fn(&Atom, Symbol) -> bool,
9930) -> bool {
9931    rubi_split_product(
9932        |factor| rubi_match_optional_scaled_monomial_power_q(factor, x),
9933        expr,
9934    )
9935    .is_some_and(|(_, rest)| rest_match(&rest, x))
9936}
9937
9938fn rubi_match_optional_scaled_monomial_power_times_power_of_linear_match_q(
9939    expr: &Atom,
9940    x: Symbol,
9941) -> bool {
9942    rubi_match_optional_scaled_monomial_power_times_q(expr, x, rubi_power_of_linear_match_q)
9943}
9944
9945fn rubi_match_optional_scaled_monomial_power_times_quadratic_binomial_power_q(
9946    expr: &Atom,
9947    x: Symbol,
9948) -> bool {
9949    rubi_match_optional_scaled_monomial_power_times_q(
9950        expr,
9951        x,
9952        rubi_match_q_quadratic_binomial_power,
9953    )
9954}
9955
9956fn rubi_quadratic_match_q(expr: &Atom, x: Symbol) -> bool {
9957    let Some(terms) = collect_polynomial_terms_without_expanding(expr, x) else {
9958        return false;
9959    };
9960
9961    terms.keys().all(|degree| (0..=2).contains(degree))
9962        && terms
9963            .get(&2)
9964            .is_some_and(|coefficient| !coefficient.expand().is_zero())
9965}
9966
9967fn rubi_quadratic_match_q_list(exprs: &[&Atom], x: Symbol) -> bool {
9968    exprs.iter().all(|expr| rubi_quadratic_match_q(expr, x))
9969}
9970
9971fn rubi_coeff_power(expr: &Atom, x: Symbol, power: &Atom, degree: i64) -> Option<Atom> {
9972    let (power_numerator, power_denominator) = rational_number(power)?;
9973    if power_denominator != 1 || power_numerator <= 0 {
9974        return None;
9975    }
9976
9977    rubi_coeff(expr, x, power_numerator.checked_mul(degree)?)
9978}
9979
9980fn rubi_poly_q_power(expr: &Atom, x: Symbol, power: &Atom) -> bool {
9981    poly_in_power_q(expr, x, power)
9982}
9983
9984fn rubi_poly_q_power_of(expr: &Atom, base: &Atom, power: &Atom, x: Symbol) -> bool {
9985    if integer_i64(power).is_some_and(|power| power > 0)
9986        && rubi_linear_q(base.as_view(), x)
9987        && !poly_q(expr, x)
9988    {
9989        return false;
9990    }
9991
9992    let Some(substitution_guard) = fresh_substitution_symbol() else {
9993        return false;
9994    };
9995    let sub = substitution_guard.symbol();
9996    let subst_for = rubi_subst_for(expr, base, sub);
9997
9998    rubi_poly_q_power(&subst_for, sub, power)
9999}
10000
10001fn rubi_match_q_quadratic_binomial_power(expr: &Atom, x: Symbol) -> bool {
10002    let (base, exponent) = match expr.as_view() {
10003        AtomView::Pow(power) => {
10004            let (base, exponent) = power.get_base_exp();
10005            (base.to_owned(), exponent.to_owned())
10006        }
10007        _ => (expr.to_owned(), Atom::num(1)),
10008    };
10009    if !is_free_of(&exponent, x) {
10010        return false;
10011    }
10012
10013    let Some(terms) = collect_polynomial_terms(&base, x) else {
10014        return false;
10015    };
10016    terms.contains_key(&2) && terms.keys().all(|degree| *degree == 0 || *degree == 2)
10017}
10018
10019fn rubi_poly_q_power_degree(expr: &Atom, x: Symbol, power: &Atom, degree: i64) -> bool {
10020    rubi_expon_power(expr, x, power).is_some_and(|exponent| exponent == degree)
10021}
10022
10023fn rubi_poly_q_degree(expr: &Atom, x: Symbol, degree: i64) -> bool {
10024    rubi_expon(expr.as_view(), x).is_some_and(|exponent| exponent == degree)
10025        && rubi_coeff(expr, x, degree).is_some_and(|coefficient| neq!(coefficient, 0))
10026}
10027
10028/// Coefficients and exponents of a pseudo-binomial expression.
10029struct PseudoBinomialParts {
10030    a: Atom,
10031    c: Atom,
10032    d: Atom,
10033    n: i64,
10034}
10035
10036fn pseudo_binomial_parts(expr: &Atom, x: Symbol) -> Option<PseudoBinomialParts> {
10037    if let AtomView::Pow(power) = expr.as_view()
10038        && integer_i64_view(power.get_exp()).is_some_and(|exponent| exponent > 2)
10039        && rubi_linear_q(power.get_base(), x)
10040    {
10041        // PseudoBinomialParts[(c+d*x)^n,x] has a zero residual constant, so
10042        // Mathematica rejects it before constructing a pseudo-binomial tuple.
10043        return None;
10044    }
10045
10046    let n = polynomial_degree(expr, x)?;
10047    if n <= 2 {
10048        return None;
10049    }
10050
10051    let coefficient_n = polynomial_coefficient(expr, x, n)?;
10052    let d = rubi_rt(&coefficient_n, n);
10053    let coefficient_n_minus_1 = polynomial_coefficient(expr, x, n - 1)?;
10054    let c = coefficient_n_minus_1 / (Atom::num(n) * d.pow(n - 1));
10055    let x_atom = Atom::var(x);
10056    let a = (expr - (&c + &d * x_atom).pow(n)).together();
10057    if neq!(a, 0) && is_free_of(&a, x) {
10058        Some(PseudoBinomialParts { a, c, d, n })
10059    } else {
10060        None
10061    }
10062}
10063
10064fn pseudo_binomial_pair_q(u: &Atom, v: &Atom, x: Symbol) -> bool {
10065    match (pseudo_binomial_parts(u, x), pseudo_binomial_parts(v, x)) {
10066        (Some(first), Some(second)) => {
10067            first.c == second.c && first.d == second.d && first.n == second.n
10068        }
10069        _ => false,
10070    }
10071}
10072
10073fn normalize_pseudo_binomial(expr: &Atom, x: Symbol) -> Option<Atom> {
10074    let parts = pseudo_binomial_parts(expr, x)?;
10075    Some(parts.a + (parts.c + parts.d * Atom::var(x)).pow(parts.n))
10076}
10077
10078fn polynomial_difference_is_zero(left: &Atom, right: &Atom) -> bool {
10079    (left - right).together().as_view().is_zero()
10080}
10081
10082fn rubi_polynomial_eq_q(left: &Atom, right: &Atom, x: Symbol) -> bool {
10083    if left == right {
10084        return true;
10085    }
10086
10087    let Some(mut left_terms) = collect_polynomial_terms(left, x) else {
10088        return false;
10089    };
10090    let Some(right_terms) = collect_polynomial_terms(right, x) else {
10091        return false;
10092    };
10093
10094    for (degree, right_coefficient) in right_terms {
10095        let left_coefficient = left_terms.remove(&degree).unwrap_or_else(|| Atom::num(0));
10096        if !rubi_algebraic_zero_q(&(left_coefficient - right_coefficient)) {
10097            return false;
10098        }
10099    }
10100
10101    left_terms
10102        .into_values()
10103        .all(|coefficient| rubi_algebraic_zero_q(&coefficient))
10104}
10105
10106/// Recognition result for an expression that is a perfect affine power.
10107struct RubiPerfectAffinePower {
10108    degree: i64,
10109    a: Atom,
10110    b: Atom,
10111    power: Atom,
10112}
10113
10114fn rubi_perfect_affine_power(expr: &Atom, x: Symbol) -> Option<RubiPerfectAffinePower> {
10115    if !rubi_poly_q(expr, x) {
10116        return None;
10117    }
10118
10119    let degree = rubi_expon(expr.as_view(), x)?;
10120    if degree <= 1 {
10121        return None;
10122    }
10123
10124    let constant = rubi_coeff(expr, x, 0)?;
10125    if eqq!(constant, 0) {
10126        return None;
10127    }
10128
10129    let a = rubi_rt(&constant, degree);
10130    let b = rubi_rt(&rubi_coeff(expr, x, degree)?, degree);
10131    let power = (&a + &b * Atom::var(x)).pow(degree);
10132    rubi_polynomial_eq_q(expr, &power, x).then_some(RubiPerfectAffinePower {
10133        degree,
10134        a,
10135        b,
10136        power,
10137    })
10138}
10139
10140/// Recognition result for an expression that is a perfect binomial power.
10141struct RubiPerfectBinomialPower {
10142    degree: i64,
10143    a: Atom,
10144    b: Atom,
10145    power: Atom,
10146}
10147
10148fn rubi_perfect_binomial_power(
10149    expr: &Atom,
10150    x: Symbol,
10151    variable_power: i64,
10152) -> Option<RubiPerfectBinomialPower> {
10153    let variable_power = Atom::num(variable_power);
10154    if !rubi_poly_q_power(expr, x, &variable_power) {
10155        return None;
10156    }
10157
10158    let degree = rubi_expon_power(expr, x, &variable_power)?;
10159    if degree <= 1 {
10160        return None;
10161    }
10162
10163    let constant = rubi_coeff_power(expr, x, &variable_power, 0)?;
10164    if eqq!(constant, 0) {
10165        return None;
10166    }
10167
10168    let a = rubi_rt(&constant, degree);
10169    let b = rubi_rt(&rubi_coeff_power(expr, x, &variable_power, degree)?, degree);
10170    let power = (&a + &b * Atom::var(x).pow(&variable_power)).pow(degree);
10171    rubi_polynomial_eq_q(expr, &power, x).then_some(RubiPerfectBinomialPower {
10172        degree,
10173        a,
10174        b,
10175        power,
10176    })
10177}
10178
10179fn rubi_int_hide_inverse_function_free_q(expr: &Atom, x: Symbol) -> bool {
10180    rubi_int_hide(expr, x).is_some_and(|primitive| rubi_inverse_function_free_q(&primitive, x))
10181}
10182
10183fn rubi_int_hide_logarithm_condition(expr: &Atom, x: Symbol, direct_condition: bool) -> bool {
10184    direct_condition || rubi_int_hide_inverse_function_free_q(expr, x)
10185}
10186
10187fn remove_integer_content(expr: &Atom, x: Symbol) -> Atom {
10188    let Some(terms) = collect_polynomial_terms(expr, x) else {
10189        return expr.to_owned();
10190    };
10191
10192    let mut content = 0_i64;
10193    for coefficient in terms.values() {
10194        let Some(coefficient) = integer_i64(coefficient) else {
10195            return expr.to_owned();
10196        };
10197        content = integer_gcd(content, coefficient);
10198    }
10199
10200    if content <= 1 {
10201        return expr.to_owned();
10202    }
10203
10204    (expr / Atom::num(content)).expand()
10205}
10206
10207fn integer_gcd(mut left: i64, mut right: i64) -> i64 {
10208    left = left.abs();
10209    right = right.abs();
10210    while right != 0 {
10211        let remainder = left % right;
10212        left = right;
10213        right = remainder;
10214    }
10215    left
10216}
10217
10218fn rubi_gcd(left: &Atom, right: &Atom) -> Option<i64> {
10219    Some(integer_gcd(integer_i64(left)?, integer_i64(right)?))
10220}
10221
10222fn rubi_floor(numerator: i64, denominator: i64) -> Option<i64> {
10223    if denominator == 0 {
10224        return None;
10225    }
10226
10227    Some(numerator.div_euclid(denominator))
10228}
10229
10230fn rubi_binomial_coefficient(n: i64, k: i64) -> Option<Atom> {
10231    if n < 0 {
10232        return None;
10233    }
10234    if k < 0 || k > n {
10235        return Some(Atom::num(0));
10236    }
10237
10238    let k = k.min(n - k);
10239    let mut coefficient = Atom::num(1);
10240    for i in 1..=k {
10241        coefficient = coefficient * Atom::num(n - k + i) / Atom::num(i);
10242    }
10243    Some(coefficient)
10244}
10245
10246#[cfg(test)]
10247fn integrate_polynomial(expr: &Atom, x: Symbol) -> Option<Atom> {
10248    let terms = collect_polynomial_terms(expr, x)?;
10249    let variable = Atom::var(x);
10250    let mut primitive = Atom::num(0);
10251    for (degree, coefficient) in terms {
10252        primitive += coefficient * variable.pow(degree + 1) / Atom::num(degree + 1);
10253    }
10254
10255    #[cfg(feature = "trace")]
10256    trace_direct_polynomial_integration("integrate_polynomial", expr);
10257    Some(primitive)
10258}
10259
10260fn polynomial_quotient_remainder_linear(
10261    expr: &Atom,
10262    constant: impl RubiAtomArgument,
10263    slope: impl RubiAtomArgument,
10264    x: Symbol,
10265) -> Option<(Atom, Atom)> {
10266    let constant = constant.into_rubi_atom();
10267    let slope = slope.into_rubi_atom();
10268    if slope.is_zero() || !is_free_of((&constant, &slope), x) {
10269        return None;
10270    }
10271
10272    let mut remainder_terms = collect_polynomial_terms(expr, x)?;
10273    let mut quotient_terms = BTreeMap::new();
10274    while let Some((&degree, coefficient)) = remainder_terms.iter().next_back() {
10275        let coefficient = coefficient.expand();
10276        if coefficient.is_zero() {
10277            remainder_terms.remove(&degree);
10278            continue;
10279        }
10280
10281        if degree == 0 {
10282            break;
10283        }
10284
10285        let quotient_degree = degree - 1;
10286        let quotient_coefficient = (coefficient / &slope).expand();
10287        add_polynomial_term(
10288            &mut quotient_terms,
10289            quotient_degree,
10290            quotient_coefficient.to_owned(),
10291        );
10292        add_polynomial_term(
10293            &mut remainder_terms,
10294            degree,
10295            -(&quotient_coefficient * &slope),
10296        );
10297        add_polynomial_term(
10298            &mut remainder_terms,
10299            quotient_degree,
10300            -(quotient_coefficient * &constant),
10301        );
10302    }
10303
10304    Some((
10305        polynomial_from_terms(&quotient_terms, x),
10306        polynomial_from_terms(&remainder_terms, x),
10307    ))
10308}
10309
10310// TODO: convert to Symbolica polynomial
10311fn polynomial_quotient_remainder(
10312    numerator: &Atom,
10313    denominator: &Atom,
10314    x: Symbol,
10315) -> Option<(Atom, Atom)> {
10316    let denominator_terms = collect_polynomial_terms(denominator, x)?;
10317    let (&denominator_degree, denominator_lead) = denominator_terms.iter().next_back()?;
10318    if polynomial_coefficient_zero_q(denominator_lead) {
10319        return None;
10320    }
10321    if denominator_degree == 0 {
10322        return Some(((numerator / denominator_lead).expand(), Atom::num(0)));
10323    }
10324
10325    let mut remainder_terms = collect_polynomial_terms(numerator, x)?;
10326    let mut quotient_terms = BTreeMap::new();
10327    while let Some((&degree, coefficient)) = remainder_terms.iter().next_back() {
10328        let coefficient = coefficient.expand();
10329        if polynomial_coefficient_zero_q(&coefficient) {
10330            remainder_terms.remove(&degree);
10331            continue;
10332        }
10333
10334        if degree < denominator_degree {
10335            break;
10336        }
10337
10338        let quotient_degree = degree - denominator_degree;
10339        let quotient_coefficient = (coefficient / denominator_lead).expand();
10340        add_polynomial_term(
10341            &mut quotient_terms,
10342            quotient_degree,
10343            quotient_coefficient.to_owned(),
10344        );
10345        for (term_degree, term_coefficient) in &denominator_terms {
10346            add_polynomial_term(
10347                &mut remainder_terms,
10348                quotient_degree + term_degree,
10349                -(&quotient_coefficient * term_coefficient),
10350            );
10351        }
10352    }
10353
10354    Some((
10355        polynomial_from_terms(&quotient_terms, x),
10356        polynomial_from_terms(&remainder_terms, x),
10357    ))
10358}
10359
10360fn linear_polynomial_remainder_condition(
10361    numerator: &Atom,
10362    denominator_terms: &BTreeMap<i64, Atom>,
10363    x: Symbol,
10364) -> Option<ConditionResult> {
10365    let Some(lead) = denominator_terms.get(&1) else {
10366        return Some(ConditionResult::False);
10367    };
10368    if lead.is_zero() {
10369        return Some(ConditionResult::False);
10370    }
10371
10372    let constant = denominator_terms
10373        .get(&0)
10374        .cloned()
10375        .unwrap_or_else(|| Atom::num(0));
10376    let Some(numerator_terms) = collect_polynomial_terms(numerator, x) else {
10377        return None;
10378    };
10379    let Some((&degree, _)) = numerator_terms.iter().next_back() else {
10380        return Some(ConditionResult::True);
10381    };
10382
10383    let root_numerator = -constant;
10384    let mut scaled_remainder = Atom::num(0);
10385    for (term_degree, coefficient) in numerator_terms {
10386        let root_power = if term_degree == 0 {
10387            Atom::num(1)
10388        } else {
10389            root_numerator.pow(term_degree)
10390        };
10391        let lead_degree = degree - term_degree;
10392        let lead_power = if lead_degree == 0 {
10393            Atom::num(1)
10394        } else {
10395            lead.pow(lead_degree)
10396        };
10397        scaled_remainder += coefficient * root_power * lead_power;
10398    }
10399
10400    let simplified = rubi_simplify(&scaled_remainder);
10401    if simplified.is_zero() {
10402        return Some(ConditionResult::True);
10403    }
10404
10405    match simplified.zero_test(16, 1e-12) {
10406        ConditionResult::True => Some(ConditionResult::True),
10407        ConditionResult::False => Some(ConditionResult::False),
10408        ConditionResult::Inconclusive => None,
10409    }
10410}
10411
10412fn add_polynomial_term_unexpanded(terms: &mut BTreeMap<i64, Atom>, degree: i64, coefficient: Atom) {
10413    let updated = terms
10414        .remove(&degree)
10415        .map(|existing| existing + &coefficient)
10416        .unwrap_or(coefficient);
10417    terms.insert(degree, updated);
10418}
10419
10420fn rubi_polynomial_quotient(
10421    numerator: impl RubiAtomArgument,
10422    denominator: impl RubiAtomArgument,
10423    x: Symbol,
10424) -> Option<Atom> {
10425    let numerator = numerator.into_rubi_atom();
10426    let denominator = denominator.into_rubi_atom();
10427    let (quotient, _remainder) =
10428        polynomial_quotient_remainder_mathematica(&numerator, &denominator, x)?;
10429    Some(quotient)
10430}
10431
10432fn rubi_polynomial_remainder(
10433    numerator: impl RubiAtomArgument,
10434    denominator: impl RubiAtomArgument,
10435    x: Symbol,
10436) -> Option<Atom> {
10437    let numerator = numerator.into_rubi_atom();
10438    let denominator = denominator.into_rubi_atom();
10439    let (_quotient, remainder) =
10440        polynomial_quotient_remainder_mathematica(&numerator, &denominator, x)?;
10441    Some(remainder)
10442}
10443
10444/// Return the indexed Mathematica `Root` of a rational cubic when that root is rational.
10445/// Real roots precede nonreal roots and are ordered increasingly. Factoring over `Q`
10446/// identifies rational candidates; the remaining quadratic determines each candidate's
10447/// exact position without approximating its other roots.
10448fn rubi_rational_root(polynomial: &Atom, x: Symbol, index: usize) -> Option<Atom> {
10449    if !(1..=3).contains(&index) {
10450        return None;
10451    }
10452
10453    let variables = Arc::new(vec![x.into()]);
10454    let polynomial_q: MultivariatePolynomial<_, u8> =
10455        polynomial.try_to_polynomial(&Q, Some(variables)).ok()?;
10456    if polynomial_q.degree(0) != 3 {
10457        return None;
10458    }
10459
10460    let x_atom = Atom::var(x);
10461    for (factor, _) in polynomial_q.factor() {
10462        if factor.degree(0) != 1 {
10463            continue;
10464        }
10465
10466        let factor = factor.to_expression();
10467        let constant = rubi_coeff(&factor, x, 0)?;
10468        let linear = rubi_coeff(&factor, x, 1)?;
10469        let candidate = rubi_together_simplify(&(-constant / linear));
10470        if !rational_q(&candidate) {
10471            continue;
10472        }
10473
10474        let quotient = rubi_polynomial_quotient(polynomial, &(&x_atom - &candidate), x)?;
10475        let a = rubi_coeff(&quotient, x, 2)?;
10476        let b = rubi_coeff(&quotient, x, 1)?;
10477        let c = rubi_coeff(&quotient, x, 0)?;
10478        let discriminant = rubi_together_simplify(&(b.pow(2) - Atom::num(4) * &a * &c));
10479        let (discriminant_numerator, _) = rubi_numeric_rational(&discriminant)?;
10480
10481        if discriminant_numerator < 0 {
10482            if index == 1 {
10483                return Some(candidate);
10484            }
10485            continue;
10486        }
10487
10488        let centered = Atom::num(2) * &a * &candidate + &b;
10489        let side = rubi_together_simplify(&(&a * &centered));
10490        let distance = rubi_together_simplify(&(centered.pow(2) - &discriminant));
10491        let (side_numerator, _) = rubi_numeric_rational(&side)?;
10492        let (distance_numerator, _) = rubi_numeric_rational(&distance)?;
10493        let at_index = match index {
10494            1 => side_numerator <= 0 && distance_numerator >= 0,
10495            2 => distance_numerator <= 0,
10496            3 => side_numerator >= 0 && distance_numerator >= 0,
10497            _ => unreachable!(),
10498        };
10499        if at_index {
10500            return Some(candidate);
10501        }
10502    }
10503
10504    None
10505}
10506
10507fn rubi_polynomial_divide(
10508    numerator: impl RubiAtomArgument,
10509    denominator: impl RubiAtomArgument,
10510    x: Symbol,
10511) -> Option<Atom> {
10512    let numerator = numerator.into_rubi_atom();
10513    let denominator = denominator.into_rubi_atom();
10514    let (quotient, remainder) = polynomial_quotient_remainder(&numerator, &denominator, x)?;
10515    let x_atom = Atom::var(x);
10516
10517    // IntegrationUtilityFunctions.m PolynomialDivide[u,v,x] collects each
10518    // quotient coefficient separately instead of globally expanding the
10519    // result. This grouping is observable by later ordered Int rules.
10520    let quotient_terms = collect_polynomial_terms(&quotient, x)?;
10521    let quotient = quotient_terms
10522        .into_iter()
10523        .map(|(degree, coefficient)| {
10524            rubi_simp(&rubi_together(&(coefficient * x_atom.pow(degree))), x)
10525        })
10526        .fold(Atom::num(0), |sum, term| sum + term);
10527
10528    let remainder = rubi_together(&remainder);
10529    if remainder.is_zero() {
10530        return Some(quotient);
10531    }
10532    let free = rubi_free_factors(&remainder, x);
10533    let nonfree = rubi_nonfree_factors(&remainder, x);
10534    let remainder_terms = collect_polynomial_terms(&nonfree, x)?;
10535    let minimum_degree = *remainder_terms.keys().next()?;
10536    let mut monomial = x_atom.pow(minimum_degree);
10537    if negq!(rubi_coeff(&nonfree, x, 0)?) {
10538        monomial = -monomial;
10539    }
10540    let normalized_remainder = remainder_terms
10541        .into_iter()
10542        .map(|(degree, coefficient)| {
10543            rubi_simp(
10544                &rubi_together(&(coefficient * x_atom.pow(degree) / &monomial)),
10545                x,
10546            )
10547        })
10548        .fold(Atom::num(0), |sum, term| sum + term);
10549    let denominator = if rubi_binomial_q(denominator.as_view(), x) {
10550        rubi_expand_to_sum(&denominator, x)
10551    } else {
10552        denominator
10553    };
10554
10555    Some(quotient + free * monomial * normalized_remainder / denominator)
10556}
10557
10558fn normalize_polynomial_gcd(expr: Atom, x: Symbol) -> Option<Atom> {
10559    let terms = collect_polynomial_terms(&expr, x)?;
10560    let Some((degree, leading_coefficient)) = terms.iter().next_back() else {
10561        return Some(Atom::num(1));
10562    };
10563    if *degree == 0 {
10564        return Some(Atom::num(1));
10565    }
10566    if leading_coefficient.is_zero() {
10567        return None;
10568    }
10569
10570    Some((expr / leading_coefficient).expand().cancel())
10571}
10572
10573fn rubi_poly_gcd(left: &Atom, right: &Atom, x: Symbol) -> Option<Atom> {
10574    // Rubi: NonfreeFactors[PolynomialGCD[u,v],x]. Reconvert the left
10575    // polynomial with the right polynomial's extended variable map so both
10576    // operands use exactly the same multivariate ring.
10577    let initial_left = left.try_to_polynomial::<_, u32>(&Q, None).ok()?;
10578    let right_polynomial = right
10579        .try_to_polynomial::<_, u32>(&Q, Some(initial_left.variables().to_owned()))
10580        .ok()?;
10581    let left_polynomial = left
10582        .try_to_polynomial::<_, u32>(&Q, Some(right_polynomial.variables().to_owned()))
10583        .ok()?;
10584    if left_polynomial
10585        .variables()
10586        .iter()
10587        .any(|variable| !matches!(variable, PolyVariable::Symbol(_)))
10588    {
10589        return rubi_poly_gcd_algebraic_fallback(left, right, x);
10590    }
10591    let gcd = left_polynomial.gcd(&right_polynomial).to_expression();
10592
10593    Some(rubi_nonfree_factors(&gcd, x))
10594}
10595
10596fn rubi_poly_gcd_algebraic_fallback(left: &Atom, right: &Atom, x: Symbol) -> Option<Atom> {
10597    let left_terms = collect_polynomial_terms(left, x)?;
10598    let right_terms = collect_polynomial_terms(right, x)?;
10599    if polynomial_terms_nonzero_constant(&left_terms)
10600        || polynomial_terms_nonzero_constant(&right_terms)
10601    {
10602        return Some(Atom::num(1));
10603    }
10604    if polynomial_monomial_coprime_to_nonzero_constant(&left_terms, &right_terms)
10605        || polynomial_monomial_coprime_to_nonzero_constant(&right_terms, &left_terms)
10606    {
10607        return Some(Atom::num(1));
10608    }
10609    if let Some(gcd) = rubi_poly_gcd_common_power_step(&left_terms, &right_terms, x) {
10610        return Some(gcd);
10611    }
10612    if let Some(gcd) = rubi_poly_gcd_quadratic_remainder(&left_terms, &right_terms, x) {
10613        return Some(gcd);
10614    }
10615    if let Some(gcd) = rubi_poly_gcd_quadratic_remainder(&right_terms, &left_terms, x) {
10616        return Some(gcd);
10617    }
10618    if let Some(gcd) = rubi_poly_gcd_linear_quadratic(&left_terms, &right_terms, x) {
10619        return Some(gcd);
10620    }
10621    if let Some(gcd) = rubi_poly_gcd_linear_quadratic(&right_terms, &left_terms, x) {
10622        return Some(gcd);
10623    }
10624
10625    let mut a = polynomial_from_terms(&left_terms, x);
10626    let mut b = polynomial_from_terms(&right_terms, x);
10627    if a.is_zero() {
10628        return normalize_polynomial_gcd(b, x);
10629    }
10630    if b.is_zero() {
10631        return normalize_polynomial_gcd(a, x);
10632    }
10633
10634    while !b.is_zero() {
10635        let (_quotient, remainder) = polynomial_quotient_remainder(&a, &b, x)?;
10636        a = b;
10637        b = remainder.expand().cancel();
10638    }
10639
10640    normalize_polynomial_gcd(a, x)
10641}
10642
10643fn rubi_poly_gcd_common_power_step(
10644    left_terms: &BTreeMap<i64, Atom>,
10645    right_terms: &BTreeMap<i64, Atom>,
10646    x: Symbol,
10647) -> Option<Atom> {
10648    let step = polynomial_terms_common_positive_degree_gcd(left_terms, right_terms)?;
10649    if step <= 1 {
10650        return None;
10651    }
10652
10653    let compressed_left = polynomial_from_terms(&compress_polynomial_terms(left_terms, step)?, x);
10654    let compressed_right = polynomial_from_terms(&compress_polynomial_terms(right_terms, step)?, x);
10655    let compressed_gcd = rubi_poly_gcd(&compressed_left, &compressed_right, x)?;
10656    Some(substitute_symbol(
10657        &compressed_gcd,
10658        x,
10659        Atom::var(x).pow(step),
10660    ))
10661}
10662
10663fn polynomial_terms_common_positive_degree_gcd(
10664    left_terms: &BTreeMap<i64, Atom>,
10665    right_terms: &BTreeMap<i64, Atom>,
10666) -> Option<i64> {
10667    let mut step = 0_i64;
10668    for degree in left_terms.keys().chain(right_terms.keys()).copied() {
10669        if degree < 0 {
10670            return None;
10671        }
10672        if degree == 0 {
10673            continue;
10674        }
10675        step = if step == 0 {
10676            degree
10677        } else {
10678            integer_gcd(step, degree)
10679        };
10680    }
10681    (step > 1).then_some(step)
10682}
10683
10684fn compress_polynomial_terms(
10685    terms: &BTreeMap<i64, Atom>,
10686    step: i64,
10687) -> Option<BTreeMap<i64, Atom>> {
10688    let mut compressed = BTreeMap::new();
10689    for (degree, coefficient) in terms {
10690        if degree % step != 0 {
10691            return None;
10692        }
10693        compressed.insert(degree / step, coefficient.to_owned());
10694    }
10695    Some(compressed)
10696}
10697
10698fn rubi_poly_gcd_quadratic_remainder(
10699    quadratic_terms: &BTreeMap<i64, Atom>,
10700    other_terms: &BTreeMap<i64, Atom>,
10701    x: Symbol,
10702) -> Option<Atom> {
10703    let quadratic_degree = *quadratic_terms.keys().next_back()?;
10704    let other_degree = *other_terms.keys().next_back()?;
10705    if quadratic_degree != 2 || other_degree < 2 || other_degree > 4 {
10706        return None;
10707    }
10708
10709    let quadratic = polynomial_from_terms(quadratic_terms, x);
10710    let remainder_terms =
10711        polynomial_remainder_terms_unexpanded(other_terms.to_owned(), quadratic_terms)?;
10712    let nonzero_remainder_terms: BTreeMap<_, _> = remainder_terms
10713        .into_iter()
10714        .filter_map(|(degree, coefficient)| {
10715            (!coefficient.is_zero()).then_some((degree, coefficient))
10716        })
10717        .collect();
10718
10719    let Some((&remainder_degree, _)) = nonzero_remainder_terms.iter().next_back() else {
10720        return normalize_polynomial_gcd(quadratic, x);
10721    };
10722    if remainder_degree == 0 {
10723        return Some(Atom::num(1));
10724    }
10725    if remainder_degree == 1 {
10726        return rubi_poly_gcd_linear_quadratic_remainder(
10727            &nonzero_remainder_terms,
10728            quadratic_terms,
10729            x,
10730        );
10731    }
10732
10733    None
10734}
10735
10736fn rubi_poly_gcd_linear_quadratic_remainder(
10737    linear_terms: &BTreeMap<i64, Atom>,
10738    quadratic_terms: &BTreeMap<i64, Atom>,
10739    x: Symbol,
10740) -> Option<Atom> {
10741    let linear_degree = *linear_terms.keys().next_back()?;
10742    let quadratic_degree = *quadratic_terms.keys().next_back()?;
10743    if linear_degree != 1 || quadratic_degree != 2 {
10744        return None;
10745    }
10746
10747    let remainder_terms =
10748        polynomial_remainder_terms_unexpanded(quadratic_terms.to_owned(), linear_terms)?;
10749    if remainder_terms
10750        .values()
10751        .any(|coefficient| !coefficient.is_zero())
10752    {
10753        return Some(Atom::num(1));
10754    }
10755
10756    normalize_polynomial_gcd(polynomial_from_terms(linear_terms, x), x)
10757}
10758
10759fn polynomial_remainder_terms_unexpanded(
10760    mut remainder_terms: BTreeMap<i64, Atom>,
10761    denominator_terms: &BTreeMap<i64, Atom>,
10762) -> Option<BTreeMap<i64, Atom>> {
10763    let (&denominator_degree, denominator_lead) = denominator_terms.iter().next_back()?;
10764    if denominator_lead.is_zero() {
10765        return None;
10766    }
10767
10768    while let Some((&degree, _)) = remainder_terms.iter().next_back() {
10769        if degree < denominator_degree {
10770            break;
10771        }
10772
10773        let Some(coefficient) = remainder_terms.remove(&degree) else {
10774            break;
10775        };
10776        let coefficient = coefficient.expand();
10777        if coefficient.is_zero() {
10778            continue;
10779        }
10780
10781        let quotient_degree = degree - denominator_degree;
10782        let quotient_coefficient = &coefficient / denominator_lead;
10783        for (term_degree, term_coefficient) in denominator_terms {
10784            if *term_degree == denominator_degree {
10785                continue;
10786            }
10787            add_polynomial_term_unexpanded(
10788                &mut remainder_terms,
10789                quotient_degree + term_degree,
10790                -(&quotient_coefficient * term_coefficient),
10791            );
10792        }
10793    }
10794
10795    Some(remainder_terms)
10796}
10797
10798fn rubi_poly_gcd_linear_quadratic(
10799    linear_terms: &BTreeMap<i64, Atom>,
10800    quadratic_terms: &BTreeMap<i64, Atom>,
10801    x: Symbol,
10802) -> Option<Atom> {
10803    let linear_degree = *linear_terms.keys().next_back()?;
10804    let quadratic_degree = *quadratic_terms.keys().next_back()?;
10805    if linear_degree != 1 || quadratic_degree != 2 {
10806        return None;
10807    }
10808
10809    let linear = polynomial_from_terms(linear_terms, x);
10810    let quadratic = polynomial_from_terms(quadratic_terms, x);
10811    match linear_polynomial_remainder_condition(&quadratic, linear_terms, x)? {
10812        ConditionResult::True => normalize_polynomial_gcd(linear, x),
10813        ConditionResult::False => Some(Atom::num(1)),
10814        ConditionResult::Inconclusive => None,
10815    }
10816}
10817
10818fn polynomial_terms_nonzero_constant(terms: &BTreeMap<i64, Atom>) -> bool {
10819    terms.len() == 1 && terms.get(&0).is_some_and(|constant| !constant.is_zero())
10820}
10821
10822fn polynomial_monomial_coprime_to_nonzero_constant(
10823    monomial_terms: &BTreeMap<i64, Atom>,
10824    other_terms: &BTreeMap<i64, Atom>,
10825) -> bool {
10826    monomial_terms.len() == 1
10827        && monomial_terms
10828            .keys()
10829            .next()
10830            .is_some_and(|degree| *degree > 0)
10831        && other_terms
10832            .get(&0)
10833            .is_some_and(|constant| !constant.is_zero())
10834}
10835
10836fn rubi_minimum_monomial_exponent(expr: &Atom, x: Symbol) -> Option<i64> {
10837    collect_polynomial_terms(expr, x)?.keys().next().copied()
10838}
10839
10840fn rubi_star(multiplier: impl RubiAtomArgument, expr: impl RubiAtomArgument) -> Atom {
10841    let multiplier = multiplier.into_rubi_atom();
10842    let expr = expr.into_rubi_atom();
10843    if multiplier.is_one() {
10844        return expr;
10845    }
10846    if rubi_algebraic_zero_q(&multiplier) {
10847        return Atom::num(0);
10848    }
10849    if let AtomView::Add(add) = expr.as_view() {
10850        let mut sum = Atom::num(0);
10851        for term in add {
10852            sum += rubi_star(multiplier.to_owned(), term.to_owned());
10853        }
10854        return sum;
10855    }
10856
10857    multiplier * expr
10858}
10859
10860fn rubi_int_hide(expr: &Atom, x: Symbol) -> Option<Atom> {
10861    // Rubi's IntHide only disables step display around Int. Rust has no step
10862    // display, so preserve Int's deferred result instead of failing the RHS.
10863    Some(rubi_rhs_int(expr, x))
10864}
10865
10866fn rubi_integral_free_q(expr: &Atom) -> bool {
10867    fn recur(expr: AtomView<'_>) -> bool {
10868        match expr {
10869            AtomView::Fun(fun) => {
10870                let symbols = rubi_symbols();
10871                fun.get_symbol() != symbols.rubi_int
10872                    && fun.get_symbol() != symbols.unintegrable
10873                    && fun.into_iter().all(recur)
10874            }
10875            AtomView::Add(add) => add.into_iter().all(recur),
10876            AtomView::Mul(mul) => mul.into_iter().all(recur),
10877            AtomView::Pow(pow) => {
10878                let (base, exponent) = pow.get_base_exp();
10879                recur(base) && recur(exponent)
10880            }
10881            AtomView::Num(_) | AtomView::Var(_) => true,
10882        }
10883    }
10884
10885    recur(expr.as_view())
10886}
10887
10888fn rubi_calculus_free_q(expr: &Atom, x: Symbol) -> bool {
10889    fn recur(expr: AtomView<'_>, x: Symbol) -> bool {
10890        match expr {
10891            AtomView::Fun(function) => {
10892                let symbol = function.get_symbol();
10893                if rubi_held_form_symbol(symbol) {
10894                    return false;
10895                }
10896                if rubi_calculus_function_symbol(symbol)
10897                    && function.get_nargs() >= 2
10898                    && matches!(
10899                        function.get(1),
10900                        AtomView::Var(variable) if variable.get_symbol() == x
10901                    )
10902                {
10903                    return false;
10904                }
10905                function.into_iter().all(|argument| recur(argument, x))
10906            }
10907            AtomView::Add(add) => add.into_iter().all(|term| recur(term, x)),
10908            AtomView::Mul(mul) => mul.into_iter().all(|factor| recur(factor, x)),
10909            AtomView::Pow(power) => recur(power.get_base(), x) && recur(power.get_exp(), x),
10910            AtomView::Num(_) | AtomView::Var(_) => true,
10911        }
10912    }
10913
10914    recur(expr.as_view(), x)
10915}
10916
10917fn rubi_finished_primitive_q(expr: &Atom) -> bool {
10918    rubi_integral_free_q(expr) && !rubi_contains_unintegrable(expr)
10919}
10920
10921fn rubi_rule_deferred_primitive_q(expr: &Atom, integrand: &Atom, x: Symbol) -> bool {
10922    (rubi_contains_unintegrable(expr) || !rubi_integral_free_q(expr))
10923        && !eqq!(expr, rubi_deferred_integral(integrand, x))
10924}
10925
10926fn polynomial_inverse_mod(poly: &Atom, modulus: &Atom, x: Symbol) -> Option<Atom> {
10927    if let Some(inverse) = polynomial_inverse_mod_powered_linear(poly, modulus, x) {
10928        return Some(inverse);
10929    }
10930    if let Some(inverse) = polynomial_inverse_mod_squared_quadratic(poly, modulus, x) {
10931        return Some(inverse);
10932    }
10933    if let Some(inverse) = polynomial_inverse_mod_small_degree(poly, modulus, x) {
10934        return Some(inverse);
10935    }
10936
10937    let mut old_r = poly.expand();
10938    let mut r = modulus.expand();
10939    let mut old_s = Atom::num(1);
10940    let mut s = Atom::num(0);
10941
10942    while !r.expand().is_zero() {
10943        let (q, remainder) = polynomial_quotient_remainder(&old_r, &r, x)?;
10944        let next_r = remainder.expand();
10945        let next_s = (&old_s - q * &s).expand();
10946        old_r = r;
10947        r = next_r;
10948        old_s = s;
10949        s = next_s;
10950    }
10951
10952    if polynomial_degree(&old_r, x)? != 0 {
10953        return None;
10954    }
10955    let constant = polynomial_coefficient(&old_r, x, 0)?;
10956    if constant.expand().is_zero() {
10957        return None;
10958    }
10959
10960    let inverse = (old_s / constant).expand();
10961    let (_quotient, remainder) = polynomial_quotient_remainder(&inverse, modulus, x)?;
10962    Some(remainder.expand())
10963}
10964
10965fn polynomial_inverse_mod_powered_linear(poly: &Atom, modulus: &Atom, x: Symbol) -> Option<Atom> {
10966    let AtomView::Pow(power) = modulus.as_view() else {
10967        return None;
10968    };
10969    let (base, exponent) = power.get_base_exp();
10970    let exponent = integer_i64_view(exponent)?;
10971    if exponent <= 1 {
10972        return None;
10973    }
10974
10975    let base = base.to_owned();
10976    if polynomial_degree(&base, x)? != 1 {
10977        return None;
10978    }
10979
10980    let mut inverse = polynomial_inverse_mod_small_degree(poly, &base, x)?;
10981    let mut lifted_power = 1_i64;
10982    while lifted_power < exponent {
10983        lifted_power = (2 * lifted_power).min(exponent);
10984        let lifted_modulus = base.pow(lifted_power);
10985        let modulus_terms = collect_polynomial_terms(&lifted_modulus, x)?;
10986        let lifted = &inverse * (Atom::num(2) - poly * &inverse);
10987        let remainder_terms = polynomial_remainder_mod_small(&lifted, &modulus_terms, x)?;
10988        inverse = polynomial_from_terms(&remainder_terms, x);
10989    }
10990
10991    Some(inverse)
10992}
10993
10994fn polynomial_inverse_mod_squared_quadratic(
10995    poly: &Atom,
10996    modulus: &Atom,
10997    x: Symbol,
10998) -> Option<Atom> {
10999    let AtomView::Pow(power) = modulus.as_view() else {
11000        return None;
11001    };
11002    let (base, exponent) = power.get_base_exp();
11003    if integer_i64_view(exponent)? != 2 {
11004        return None;
11005    }
11006    let base = base.to_owned();
11007    if polynomial_degree(&base, x)? != 2 {
11008        return None;
11009    }
11010
11011    let inverse_mod_base = polynomial_inverse_mod_small_degree(poly, &base, x)?;
11012    let lifted = &inverse_mod_base * (Atom::num(2) - poly * &inverse_mod_base);
11013    let modulus_terms = collect_polynomial_terms(modulus, x)?;
11014    let remainder_terms = polynomial_remainder_mod_small(&lifted, &modulus_terms, x)?;
11015    Some(polynomial_from_terms(&remainder_terms, x))
11016}
11017
11018fn polynomial_inverse_mod_small_degree(poly: &Atom, modulus: &Atom, x: Symbol) -> Option<Atom> {
11019    let modulus_terms = collect_polynomial_terms(modulus, x)?;
11020    let (&degree, lead) = modulus_terms.iter().next_back()?;
11021    if lead.is_zero() || !(degree == 1 || degree == 2) {
11022        return None;
11023    }
11024
11025    let remainder_terms = polynomial_remainder_mod_small(poly, &modulus_terms, x)?;
11026    let coefficient = |degree| {
11027        remainder_terms
11028            .get(&degree)
11029            .cloned()
11030            .unwrap_or_else(|| Atom::num(0))
11031    };
11032
11033    let r0 = coefficient(0);
11034    let r1 = coefficient(1);
11035    if degree == 1 {
11036        let q0 = modulus_terms
11037            .get(&0)
11038            .cloned()
11039            .unwrap_or_else(|| Atom::num(0));
11040        let q1 = modulus_terms.get(&1)?;
11041        let value = &r0 - &r1 * &q0 / q1;
11042        if value.is_zero() {
11043            return None;
11044        }
11045        return Some(Atom::num(1) / value);
11046    }
11047
11048    let q0 = modulus_terms
11049        .get(&0)
11050        .cloned()
11051        .unwrap_or_else(|| Atom::num(0));
11052    let q1 = modulus_terms
11053        .get(&1)
11054        .cloned()
11055        .unwrap_or_else(|| Atom::num(0));
11056    let q2 = modulus_terms.get(&2)?;
11057
11058    if r1.is_zero() {
11059        if r0.is_zero() {
11060            return None;
11061        }
11062        return Some(Atom::num(1) / r0);
11063    }
11064
11065    let adjusted_r0 = &r0 - &r1 * &q1 / q2;
11066    let determinant = &r0 * &adjusted_r0 + &r1 * &r1 * &q0 / q2;
11067    if determinant.is_zero() {
11068        return None;
11069    }
11070
11071    let s0 = adjusted_r0 / &determinant;
11072    let s1 = -r1 / determinant;
11073    Some(s0 + s1 * Atom::var(x))
11074}
11075
11076fn polynomial_remainder_mod_small(
11077    expr: &Atom,
11078    modulus_terms: &BTreeMap<i64, Atom>,
11079    x: Symbol,
11080) -> Option<BTreeMap<i64, Atom>> {
11081    fn recur(
11082        expr: &Atom,
11083        modulus_terms: &BTreeMap<i64, Atom>,
11084        x: Symbol,
11085    ) -> Option<BTreeMap<i64, Atom>> {
11086        match expr.as_view() {
11087            _ if is_free_of(expr, x) => {
11088                let mut terms = BTreeMap::new();
11089                add_polynomial_term_unexpanded(&mut terms, 0, expr.to_owned());
11090                Some(terms)
11091            }
11092            AtomView::Var(variable) if variable.get_symbol() == x => {
11093                let mut terms = BTreeMap::new();
11094                add_polynomial_term_unexpanded(&mut terms, 1, Atom::num(1));
11095                polynomial_reduce_mod_terms(terms, modulus_terms)
11096            }
11097            AtomView::Add(add) => {
11098                let mut terms = BTreeMap::new();
11099                for term in add {
11100                    terms = polynomial_add_terms(terms, recur(&term.to_owned(), modulus_terms, x)?);
11101                }
11102                polynomial_reduce_mod_terms(terms, modulus_terms)
11103            }
11104            AtomView::Mul(mul) => {
11105                let mut terms = BTreeMap::new();
11106                add_polynomial_term(&mut terms, 0, Atom::num(1));
11107                for factor in mul {
11108                    terms = polynomial_mul_mod_terms(
11109                        terms,
11110                        recur(&factor.to_owned(), modulus_terms, x)?,
11111                        modulus_terms,
11112                    )?;
11113                }
11114                Some(terms)
11115            }
11116            AtomView::Pow(power) => {
11117                let exponent = integer_i64_view(power.get_exp())?;
11118                if exponent < 0 {
11119                    return None;
11120                }
11121                let base = recur(&power.get_base().to_owned(), modulus_terms, x)?;
11122                polynomial_pow_mod_terms(base, exponent, modulus_terms)
11123            }
11124            _ => None,
11125        }
11126    }
11127
11128    recur(expr, modulus_terms, x)
11129}
11130
11131fn polynomial_add_terms(
11132    mut left: BTreeMap<i64, Atom>,
11133    right: BTreeMap<i64, Atom>,
11134) -> BTreeMap<i64, Atom> {
11135    for (degree, coefficient) in right {
11136        add_polynomial_term_unexpanded(&mut left, degree, coefficient);
11137    }
11138    left
11139}
11140
11141fn polynomial_mul_mod_terms(
11142    left: BTreeMap<i64, Atom>,
11143    right: BTreeMap<i64, Atom>,
11144    modulus_terms: &BTreeMap<i64, Atom>,
11145) -> Option<BTreeMap<i64, Atom>> {
11146    let mut product = BTreeMap::new();
11147    for (left_degree, left_coefficient) in &left {
11148        for (right_degree, right_coefficient) in &right {
11149            add_polynomial_term_unexpanded(
11150                &mut product,
11151                left_degree + right_degree,
11152                left_coefficient * right_coefficient,
11153            );
11154        }
11155    }
11156
11157    polynomial_reduce_mod_terms(product, modulus_terms)
11158}
11159
11160fn polynomial_pow_mod_terms(
11161    base: BTreeMap<i64, Atom>,
11162    exponent: i64,
11163    modulus_terms: &BTreeMap<i64, Atom>,
11164) -> Option<BTreeMap<i64, Atom>> {
11165    let mut power = BTreeMap::new();
11166    add_polynomial_term_unexpanded(&mut power, 0, Atom::num(1));
11167    for _ in 0..exponent {
11168        power = polynomial_mul_mod_terms(power, base.to_owned(), modulus_terms)?;
11169    }
11170    Some(power)
11171}
11172
11173fn polynomial_reduce_mod_terms(
11174    mut terms: BTreeMap<i64, Atom>,
11175    modulus_terms: &BTreeMap<i64, Atom>,
11176) -> Option<BTreeMap<i64, Atom>> {
11177    let (&modulus_degree, modulus_lead) = modulus_terms.iter().next_back()?;
11178    if modulus_lead.is_zero() {
11179        return None;
11180    }
11181
11182    while let Some((&degree, coefficient)) = terms.iter().next_back() {
11183        if degree < modulus_degree {
11184            break;
11185        }
11186
11187        let coefficient = coefficient.to_owned();
11188        terms.remove(&degree);
11189        if coefficient.is_zero() {
11190            continue;
11191        }
11192
11193        let quotient_degree = degree - modulus_degree;
11194        let quotient_coefficient = &coefficient / modulus_lead;
11195        for (term_degree, term_coefficient) in modulus_terms {
11196            if *term_degree == modulus_degree {
11197                continue;
11198            }
11199            add_polynomial_term_unexpanded(
11200                &mut terms,
11201                quotient_degree + term_degree,
11202                -(&quotient_coefficient * term_coefficient),
11203            );
11204        }
11205    }
11206
11207    Some(terms)
11208}
11209
11210fn polynomial_quotient_remainder_rational_dividend(
11211    numerator: impl RubiAtomArgument,
11212    rational_denominator: &Atom,
11213    polynomial_divisor: &Atom,
11214    x: Symbol,
11215) -> Option<(Atom, Atom)> {
11216    let numerator = numerator.into_rubi_atom();
11217    let inverse = polynomial_inverse_mod(rational_denominator, polynomial_divisor, x)?;
11218    let (_quotient, remainder) =
11219        polynomial_quotient_remainder(&(&numerator * inverse).expand(), polynomial_divisor, x)?;
11220    let scaled_numerator = (&numerator - rational_denominator * &remainder).expand();
11221    let (scaled_quotient, check) =
11222        polynomial_quotient_remainder(&scaled_numerator, polynomial_divisor, x)?;
11223    if !eqq!(check, 0) {
11224        return None;
11225    }
11226
11227    Some((scaled_quotient / rational_denominator, remainder.expand()))
11228}
11229
11230fn polynomial_quotient_remainder_mathematica(
11231    numerator: &Atom,
11232    denominator: &Atom,
11233    x: Symbol,
11234) -> Option<(Atom, Atom)> {
11235    let numerator = numerator.together();
11236    if let Some((rational_numerator, rational_denominator)) =
11237        rational_numerator_denominator(&numerator)
11238        && !rational_denominator.is_one()
11239    {
11240        return polynomial_quotient_remainder_rational_dividend(
11241            rational_numerator,
11242            &rational_denominator,
11243            denominator,
11244            x,
11245        );
11246    }
11247
11248    polynomial_quotient_remainder(&numerator, denominator, x)
11249}
11250
11251fn laurent_quotient_remainder_by_polynomial(
11252    numerator: &Atom,
11253    denominator: &Atom,
11254    x: Symbol,
11255) -> Option<(Atom, Atom)> {
11256    if let Some((rational_numerator, rational_denominator)) =
11257        rational_numerator_denominator(numerator)
11258        && !rational_denominator.is_one()
11259    {
11260        return polynomial_quotient_remainder_rational_dividend(
11261            rational_numerator,
11262            &rational_denominator,
11263            denominator,
11264            x,
11265        );
11266    }
11267
11268    let denominator_terms = collect_polynomial_terms(denominator, x)?;
11269    let (&denominator_degree, denominator_lead) = denominator_terms.iter().next_back()?;
11270    if denominator_degree <= 0 || denominator_lead.is_zero() {
11271        return None;
11272    }
11273
11274    let mut remainder_terms = collect_laurent_terms(numerator, x)?;
11275    let mut quotient_terms = BTreeMap::new();
11276    while let Some((&degree, coefficient)) = remainder_terms.iter().next_back() {
11277        let coefficient = coefficient.expand();
11278        if coefficient.is_zero() {
11279            remainder_terms.remove(&degree);
11280            continue;
11281        }
11282
11283        if degree < denominator_degree {
11284            break;
11285        }
11286
11287        let quotient_degree = degree - denominator_degree;
11288        let quotient_coefficient = (coefficient / denominator_lead).expand();
11289        add_polynomial_term(
11290            &mut quotient_terms,
11291            quotient_degree,
11292            quotient_coefficient.to_owned(),
11293        );
11294        for (term_degree, term_coefficient) in &denominator_terms {
11295            add_polynomial_term(
11296                &mut remainder_terms,
11297                quotient_degree + term_degree,
11298                -(&quotient_coefficient * term_coefficient),
11299            );
11300        }
11301    }
11302
11303    Some((
11304        polynomial_from_terms(&quotient_terms, x),
11305        polynomial_from_terms(&remainder_terms, x),
11306    ))
11307}
11308
11309fn rubi_expand_integrand(expr: &Atom, x: Symbol) -> Atom {
11310    rubi_expand_integrand_changed(expr, x).unwrap_or_else(|| expr.to_owned())
11311}
11312
11313fn rubi_expand_integrand_changed(expr: &Atom, x: Symbol) -> Option<Atom> {
11314    #[cfg(feature = "trace")]
11315    let trace_start = RUBI_SETTINGS
11316        .trace_helpers
11317        .load(AtomicOrdering::Relaxed)
11318        .then(std::time::Instant::now);
11319    for rule in rubi_expand_integrand_rules() {
11320        #[cfg(feature = "trace")]
11321        if RUBI_SETTINGS
11322            .trace_helper_scan
11323            .load(AtomicOrdering::Relaxed)
11324            && rubi_trace_rule_matches(rule)
11325        {
11326            eprintln!("ExpandIntegrand try {}: {expr}", rule.id);
11327        }
11328        let expanded = matcher_helper_rule(expr, x, rule, rubi_symbols().rubi_expand_integrand);
11329        if let Some(expanded) = expanded {
11330            #[cfg(feature = "trace")]
11331            if let Some(start) = trace_start {
11332                eprintln!("ExpandIntegrand helper rules {:?}", start.elapsed());
11333            }
11334            // Mathematica stops at the first applicable DownValue even when
11335            // its RHS evaluates to the original expression. Continuing to a
11336            // later row changes ExpandIntegrand's evaluation semantics and can
11337            // turn an unchanged earlier result into recursive expansion.
11338            return Some(expanded);
11339        }
11340    }
11341    #[cfg(feature = "trace")]
11342    if let Some(start) = trace_start {
11343        eprintln!("ExpandIntegrand after helper rules {:?}", start.elapsed());
11344    }
11345    None
11346}
11347
11348fn rubi_affine_log_parts(expr: &Atom, x: Symbol) -> Option<(Atom, Atom, Atom)> {
11349    if let Some(argument) = rubi_log_argument(expr) {
11350        return Some((Atom::num(0), Atom::num(1), argument));
11351    }
11352
11353    let terms = rubi_add_terms(expr);
11354    let mut free_terms = Atom::num(0);
11355    let mut log_term = None;
11356    for term in terms {
11357        if is_free_of(&term, x) {
11358            free_terms += term;
11359            continue;
11360        }
11361
11362        let (coefficient, argument) = rubi_log_term_parts(&term, x)?;
11363        if let Some((existing_coefficient, existing_argument)) = log_term {
11364            if existing_argument != argument {
11365                return None;
11366            }
11367            log_term = Some((existing_coefficient + coefficient, existing_argument));
11368        } else {
11369            log_term = Some((coefficient, argument));
11370        }
11371    }
11372
11373    let (coefficient, argument) = log_term?;
11374    Some((free_terms, coefficient, argument))
11375}
11376
11377fn rubi_log_term_parts(expr: &Atom, x: Symbol) -> Option<(Atom, Atom)> {
11378    if let Some(argument) = rubi_log_argument(expr) {
11379        return Some((Atom::num(1), argument));
11380    }
11381
11382    let mut coefficient = Atom::num(1);
11383    let mut argument = None;
11384    for factor in rubi_product_factors(expr) {
11385        if let Some(log_argument) = rubi_log_argument(&factor) {
11386            if argument.is_some() {
11387                return None;
11388            }
11389            argument = Some(log_argument);
11390        } else {
11391            if !is_free_of(&factor, x) {
11392                return None;
11393            }
11394            coefficient *= factor;
11395        }
11396    }
11397
11398    Some((coefficient, argument?))
11399}
11400
11401fn rubi_log_argument(expr: &Atom) -> Option<Atom> {
11402    let AtomView::Fun(function) = expr.as_view() else {
11403        return None;
11404    };
11405    if function.get_symbol() != symbol!("log") || function.get_nargs() != 1 {
11406        return None;
11407    }
11408    Some(function.get(0).to_owned())
11409}
11410
11411fn rubi_expand_integrand_sum(expr: &Atom, x: Symbol) -> Option<Atom> {
11412    let expanded = rubi_expand_integrand(expr, x);
11413    rubi_sum_q(&expanded).then_some(expanded)
11414}
11415
11416fn rubi_even_binomial_split_sum(
11417    px: &Atom,
11418    a: &Atom,
11419    b: &Atom,
11420    n: &Atom,
11421    x: Symbol,
11422) -> Option<Atom> {
11423    let half_n = integer_i64(&(n / Atom::num(2)))?;
11424    if half_n <= 0 {
11425        return None;
11426    }
11427
11428    let x_atom = Atom::var(x);
11429    let denominator = a + b * x_atom.pow(n);
11430    let mut v_sum = Atom::num(0);
11431    for ii in 0..half_n {
11432        let lower = rubi_coeff(px, x, ii)?;
11433        let upper = rubi_coeff(px, x, half_n + ii)?;
11434        v_sum += x_atom.pow(ii) * (lower + upper * x_atom.pow(half_n)) / &denominator;
11435    }
11436
11437    Some(v_sum)
11438}
11439
11440fn rubi_even_power_binomial_split_sum(
11441    px: &Atom,
11442    a: &Atom,
11443    b: &Atom,
11444    n: &Atom,
11445    p: &Atom,
11446    x: Symbol,
11447) -> Option<Atom> {
11448    let q = rubi_expon(px.as_view(), x)?;
11449    let half_n = integer_i64(&(n / Atom::num(2)))?;
11450    if half_n <= 0 {
11451        return None;
11452    }
11453
11454    let x_atom = Atom::var(x);
11455    let base = a + b * x_atom.pow(n);
11456    let mut transformed = Atom::num(0);
11457    for j in 0..half_n {
11458        let mut inner = Atom::num(0);
11459        let mut degree = j;
11460        while degree <= q + half_n {
11461            let coefficient = rubi_coeff(px, x, degree)?;
11462            if !coefficient.is_zero() {
11463                inner += coefficient * x_atom.pow(degree - j);
11464            }
11465            degree += half_n;
11466        }
11467        if !inner.is_zero() {
11468            transformed += x_atom.pow(j) * inner * base.pow(p);
11469        }
11470    }
11471
11472    Some(transformed)
11473}
11474
11475fn rubi_expand_hyperbolic_trig_expand(
11476    u: &Atom,
11477    f: &Atom,
11478    v: &Atom,
11479    m: &Atom,
11480    n: &Atom,
11481) -> Option<Atom> {
11482    let m = positive_integer_i64(m)?;
11483    let n = positive_integer_i64(n)?;
11484    let (sinh_nv, cosh_nv) = rubi_multiple_angle_sinh_cosh(v, n);
11485    let expanded = if f == &Atom::var(symbol!("sinh")) {
11486        sinh_nv.pow(Atom::num(m)).expand()
11487    } else if f == &Atom::var(symbol!("cosh")) {
11488        cosh_nv.pow(Atom::num(m)).expand()
11489    } else {
11490        return None;
11491    };
11492
11493    Some(match expanded.as_view() {
11494        AtomView::Add(add) => {
11495            let mut sum = Atom::num(0);
11496            for term in add {
11497                sum += u * term.to_owned();
11498            }
11499            sum
11500        }
11501        _ => u * expanded,
11502    })
11503}
11504
11505fn rubi_multiple_angle_sinh_cosh(v: &Atom, n: i64) -> (Atom, Atom) {
11506    if n == 0 {
11507        return (Atom::num(0), Atom::num(1));
11508    }
11509
11510    let sinh_v = v.sinh();
11511    let cosh_v = v.cosh();
11512    let mut sinh_nv = sinh_v.to_owned();
11513    let mut cosh_nv = cosh_v.to_owned();
11514
11515    for _ in 1..n {
11516        let next_sinh = (&sinh_nv * &cosh_v + &cosh_nv * &sinh_v).expand();
11517        let next_cosh = (&cosh_nv * &cosh_v + &sinh_nv * &sinh_v).expand();
11518        sinh_nv = next_sinh;
11519        cosh_nv = next_cosh;
11520    }
11521
11522    (sinh_nv, cosh_nv)
11523}
11524
11525fn rubi_expand_hyperbolic_trig_to_exp(u: &Atom, v: &Atom, x: Symbol) -> Atom {
11526    let w = rubi_hyperbolic_trig_to_exp(v.as_view());
11527    let simplified = match w.as_view() {
11528        AtomView::Add(add) => add
11529            .into_iter()
11530            .map(|term| rubi_simplify_integrand(&(u * term.to_owned()), x))
11531            .fold(Atom::num(0), |sum, term| sum + term),
11532        _ => rubi_simplify_integrand(&(u * w), x),
11533    };
11534
11535    let free = rubi_free_factors(&simplified, x);
11536    let nonfree = rubi_nonfree_factors(&simplified, x);
11537    rubi_expand_integrand(&(&free * &nonfree), x)
11538}
11539
11540fn rubi_hyperbolic_trig_to_exp(expr: AtomView<'_>) -> Atom {
11541    match expr {
11542        AtomView::Add(add) => add
11543            .into_iter()
11544            .map(rubi_hyperbolic_trig_to_exp)
11545            .fold(Atom::num(0), |sum, term| sum + term),
11546        AtomView::Mul(mul) => mul
11547            .into_iter()
11548            .map(rubi_hyperbolic_trig_to_exp)
11549            .fold(Atom::num(1), |product, factor| product * factor),
11550        AtomView::Pow(power) => {
11551            let (base, exponent) = power.get_base_exp();
11552            let expand_square = integer_i64_view(exponent) == Some(2)
11553                && matches!(
11554                    base,
11555                    AtomView::Fun(function)
11556                        if function.get_nargs() == 1
11557                            && rubi_hyperbolic_function_symbol(function.get_symbol())
11558                );
11559            let converted =
11560                rubi_hyperbolic_trig_to_exp(base).pow(rubi_hyperbolic_trig_to_exp(exponent));
11561            if expand_square {
11562                converted.expand()
11563            } else {
11564                converted
11565            }
11566        }
11567        AtomView::Fun(function) if function.get_nargs() == 1 => {
11568            let symbol = function.get_symbol();
11569            let argument = rubi_hyperbolic_trig_to_exp(function.get(0));
11570            let exp_pos = argument.exp();
11571            let exp_neg = (-argument.to_owned()).exp();
11572
11573            if symbol == symbol!("sinh") {
11574                (exp_pos - exp_neg) / 2
11575            } else if symbol == symbol!("cosh") {
11576                (exp_pos + exp_neg) / 2
11577            } else if symbol == symbol!("tanh") {
11578                let numerator = exp_pos.to_owned() - exp_neg.to_owned();
11579                let denominator = exp_pos + exp_neg;
11580                numerator / denominator
11581            } else if symbol == symbol!("coth") {
11582                let numerator = exp_pos.to_owned() + exp_neg.to_owned();
11583                let denominator = exp_pos - exp_neg;
11584                numerator / denominator
11585            } else if symbol == symbol!("sech") {
11586                Atom::num(2) / (exp_pos + exp_neg)
11587            } else if symbol == symbol!("csch") {
11588                Atom::num(2) / (exp_pos - exp_neg)
11589            } else {
11590                symbol.call_args(vec![argument])
11591            }
11592        }
11593        AtomView::Fun(function) => {
11594            let args: Vec<_> = function
11595                .into_iter()
11596                .map(rubi_hyperbolic_trig_to_exp)
11597                .collect();
11598            function.get_symbol().call_args(args)
11599        }
11600        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
11601    }
11602}
11603
11604fn rubi_expand_expression(expr: &Atom, x: Symbol) -> Atom {
11605    if rubi_algebraic_function_q(expr, x, false) && !rubi_rational_function_q(expr, x) {
11606        if let Some(expanded) = rubi_expand_algebraic_function(expr, x) {
11607            if rubi_sum_q(&expanded) {
11608                return rubi_expand_cleanup(&expanded, x);
11609            }
11610        }
11611    }
11612
11613    let apart = rubi_smart_apart(expr, x);
11614    if rubi_sum_q(&apart) {
11615        let apart = rubi_collect_common_rational_denominators(&apart, x);
11616        return rubi_expand_cleanup(&apart, x);
11617    }
11618
11619    let rational_factors = rubi_rational_function_factors(expr, x);
11620    let apart = rubi_smart_apart_in(&rational_factors, x, x);
11621    if rubi_sum_q(&apart) {
11622        let apart = rubi_collect_common_rational_denominators(&apart, x);
11623        let nonrational_factors = rubi_nonrational_function_factors(expr, x);
11624        let distributed = map_sum_terms(&apart, |term| term * &nonrational_factors);
11625        return rubi_expand_cleanup(&distributed, x);
11626    }
11627
11628    // IntegrationUtilityFunctions.m applies Expand[u,x] first. Mathematica
11629    // distributes positive powers and products but keeps negative powers such
11630    // as 1/(a^2-b^2*Sin[x]^2)^2 structurally intact.
11631    let expanded = rubi_mathematica_expand(expr, Some(x));
11632    if rubi_sum_q(&expanded) {
11633        return rubi_expand_cleanup(&expanded, x);
11634    }
11635
11636    let expanded = rubi_mathematica_expand(expr, None);
11637    if rubi_sum_q(&expanded) {
11638        return rubi_expand_cleanup(&expanded, x);
11639    }
11640
11641    rubi_simplify_term(expr, x)
11642}
11643
11644fn rubi_mathematica_expand(expr: &Atom, x: Option<Symbol>) -> Atom {
11645    if x.is_some_and(|x| !expr.contains_symbol(x)) {
11646        return expr.to_owned();
11647    }
11648
11649    match expr.as_view() {
11650        AtomView::Add(add) => add
11651            .into_iter()
11652            .map(|term| rubi_mathematica_expand(&term.to_owned(), x))
11653            .fold(Atom::num(0), |sum, term| sum + term),
11654        AtomView::Mul(mul) => mul
11655            .into_iter()
11656            .map(|factor| rubi_mathematica_expand(&factor.to_owned(), x))
11657            .fold(Atom::num(1), |product, factor| {
11658                rubi_mathematica_distribute_product(product, factor, x)
11659            }),
11660        AtomView::Pow(power) => {
11661            let (base, exponent) = power.get_base_exp();
11662            let Some(exponent) = integer_i64_view(exponent) else {
11663                return expr.to_owned();
11664            };
11665            if exponent < 0 {
11666                return expr.to_owned();
11667            }
11668
11669            let expanded_base = rubi_mathematica_expand(&base.to_owned(), x);
11670            (0..exponent).fold(Atom::num(1), |result, _| {
11671                rubi_mathematica_distribute_product(result, expanded_base.to_owned(), x)
11672            })
11673        }
11674        AtomView::Fun(_) | AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
11675    }
11676}
11677
11678fn rubi_mathematica_distribute_product(left: Atom, right: Atom, x: Option<Symbol>) -> Atom {
11679    let left_terms = if x.is_some_and(|x| !left.contains_symbol(x)) {
11680        vec![left]
11681    } else {
11682        rubi_add_terms(&left)
11683    };
11684    let right_terms = if x.is_some_and(|x| !right.contains_symbol(x)) {
11685        vec![right]
11686    } else {
11687        rubi_add_terms(&right)
11688    };
11689    if left_terms.len() == 1 && right_terms.len() == 1 {
11690        return left_terms.into_iter().next().expect("one left term")
11691            * right_terms.into_iter().next().expect("one right term");
11692    }
11693
11694    left_terms
11695        .into_iter()
11696        .flat_map(|left_term| {
11697            right_terms
11698                .iter()
11699                .map(move |right_term| &left_term * right_term)
11700        })
11701        .fold(Atom::num(0), |sum, term| sum + term)
11702}
11703
11704fn rubi_expand_algebraic_function(expr: &Atom, x: Symbol) -> Option<Atom> {
11705    match expr.as_view() {
11706        AtomView::Mul(mul) => {
11707            let factors = mul
11708                .into_iter()
11709                .map(|factor| factor.to_owned())
11710                .collect::<Vec<_>>();
11711            for (index, factor) in factors.iter().enumerate() {
11712                if rubi_sum_q(factor) && !is_free_of(factor.as_view(), x) {
11713                    let rest = product_atoms(
11714                        &factors
11715                            .iter()
11716                            .enumerate()
11717                            .filter_map(|(factor_index, factor)| {
11718                                (factor_index != index).then_some(factor.to_owned())
11719                            })
11720                            .collect::<Vec<_>>(),
11721                    );
11722                    return Some(map_sum_terms(factor, |term| term * &rest));
11723                }
11724
11725                let AtomView::Pow(power) = factor.as_view() else {
11726                    continue;
11727                };
11728                let base = power.get_base().to_owned();
11729                let exponent = power.get_exp().to_owned();
11730                if !rubi_sum_q(&base) || !igtq!(exponent, 0) || freeq!(base, x) {
11731                    continue;
11732                }
11733
11734                let expanded_power = base.pow(exponent).expand();
11735                if !rubi_sum_q(&expanded_power) {
11736                    continue;
11737                }
11738
11739                let rest = product_atoms(
11740                    &factors
11741                        .iter()
11742                        .enumerate()
11743                        .filter_map(|(factor_index, factor)| {
11744                            (factor_index != index).then_some(factor.to_owned())
11745                        })
11746                        .collect::<Vec<_>>(),
11747                );
11748                return Some(map_sum_terms(&expanded_power, |term| term * &rest));
11749            }
11750            None
11751        }
11752        AtomView::Pow(power) => {
11753            let base = power.get_base().to_owned();
11754            let exponent = power.get_exp().to_owned();
11755            if !rubi_sum_q(&base) || !igtq!(exponent, 0) || freeq!(base, x) {
11756                return None;
11757            }
11758            let expanded = base.pow(exponent).expand();
11759            rubi_sum_q(&expanded).then_some(expanded)
11760        }
11761        _ => None,
11762    }
11763}
11764
11765fn rubi_expand_cleanup(expr: &Atom, x: Symbol) -> Atom {
11766    if let Some((cleaned, combined_denominator)) = rubi_expand_cleanup_linear_pair(expr, x) {
11767        let recursively_cleaned = rubi_expand_cleanup(&cleaned, x);
11768        return rubi_restore_expand_cleanup_denominator(
11769            &recursively_cleaned,
11770            &combined_denominator,
11771            x,
11772        );
11773    }
11774
11775    let collected = rubi_collect_reciprocals(expr, x);
11776    let collected = collect_polynomial_terms(&collected, x)
11777        .map(|terms| polynomial_from_terms(&terms, x))
11778        .unwrap_or(collected);
11779    let cleaned = if rubi_sum_q(&collected) {
11780        let simplified = map_sum_terms(&collected, |term| {
11781            let simplified = rubi_simplify_term(term, x);
11782            rubi_factor_rational_polynomial_coefficients(&simplified, x)
11783        });
11784        if rubi_sum_q(&simplified) {
11785            let unified = rubi_unify_sum(&simplified, x);
11786            map_sum_terms(&unified, |term| {
11787                rubi_collect_rational_polynomial_numerator(term, x)
11788            })
11789        } else {
11790            simplified
11791        }
11792    } else {
11793        collected
11794    };
11795
11796    cleaned
11797}
11798
11799fn rubi_collect_common_rational_denominators(expr: &Atom, x: Symbol) -> Atom {
11800    fn contains_dependent_function(expr: &Atom, x: Symbol) -> bool {
11801        match expr.as_view() {
11802            AtomView::Fun(_) => !is_free_of(expr, x),
11803            AtomView::Add(add) => add
11804                .into_iter()
11805                .any(|term| contains_dependent_function(&term.to_owned(), x)),
11806            AtomView::Mul(mul) => mul
11807                .into_iter()
11808                .any(|factor| contains_dependent_function(&factor.to_owned(), x)),
11809            AtomView::Pow(power) => {
11810                contains_dependent_function(&power.get_base().to_owned(), x)
11811                    || contains_dependent_function(&power.get_exp().to_owned(), x)
11812            }
11813            AtomView::Num(_) | AtomView::Var(_) => false,
11814        }
11815    }
11816
11817    if !rubi_sum_q(expr) {
11818        return expr.to_owned();
11819    }
11820    if contains_dependent_function(expr, x) {
11821        return expr.to_owned();
11822    }
11823
11824    // Mathematica Apart keeps a polynomial numerator grouped over each
11825    // denominator. Restore that shape after Symbolica canonicalizes it into
11826    // separate summands so downstream Rubi patterns see the same expression.
11827    let mut polynomial_terms = Vec::new();
11828    let mut groups: Vec<(Atom, Vec<Atom>)> = Vec::new();
11829    let mut saw_ineligible_rational_term = false;
11830    for term in rubi_add_terms(expr) {
11831        let Some((numerator, denominator)) = rational_numerator_denominator(&term) else {
11832            polynomial_terms.push(term);
11833            continue;
11834        };
11835        let denominator = rubi_factor(&denominator);
11836        let nonfree_denominator = rubi_nonfree_factors(&denominator, x);
11837        if denominator.is_one() || nonfree_denominator.is_one() {
11838            polynomial_terms.push(term);
11839            continue;
11840        }
11841        if !rubi_structural_rational_function_q(numerator.as_view(), x)
11842            || !rubi_structural_rational_function_q(nonfree_denominator.as_view(), x)
11843            || !poly_q(&numerator, x)
11844            || !poly_q(&nonfree_denominator, x)
11845        {
11846            saw_ineligible_rational_term = true;
11847            polynomial_terms.push(term);
11848            continue;
11849        }
11850
11851        let free_denominator = rubi_free_factors(&denominator, x);
11852        let normalized_numerator = rubi_cancel(&(numerator / free_denominator));
11853        if let Some((_, numerators)) = groups
11854            .iter_mut()
11855            .find(|(candidate, _)| *candidate == nonfree_denominator)
11856        {
11857            numerators.push(normalized_numerator);
11858        } else {
11859            groups.push((nonfree_denominator, vec![normalized_numerator]));
11860        }
11861    }
11862    if saw_ineligible_rational_term || !groups.iter().any(|(_, numerators)| numerators.len() > 1) {
11863        return expr.to_owned();
11864    }
11865
11866    let polynomial = polynomial_terms
11867        .into_iter()
11868        .fold(Atom::num(0), |sum, term| sum + term);
11869    groups
11870        .into_iter()
11871        .fold(polynomial, |sum, (denominator, numerator_terms)| {
11872            let numerator = numerator_terms
11873                .into_iter()
11874                .fold(Atom::num(0), |numerator, term| numerator + term);
11875            let numerator = collect_polynomial_terms(&numerator, x)
11876                .map(|terms| polynomial_from_terms(&terms, x))
11877                .unwrap_or(numerator);
11878            sum + numerator / denominator
11879        })
11880}
11881
11882fn rubi_collect_rational_polynomial_numerator(expr: &Atom, x: Symbol) -> Atom {
11883    let Some((numerator, denominator)) = rational_numerator_denominator_unexpanded(expr) else {
11884        return expr.to_owned();
11885    };
11886    let Some(terms) = collect_polynomial_terms_without_expanding(&numerator, x)
11887        .or_else(|| collect_polynomial_terms(&numerator, x))
11888    else {
11889        return expr.to_owned();
11890    };
11891    let collected = polynomial_from_terms(&terms, x);
11892    let candidate = collected / denominator;
11893    if rubi_leaf_count(candidate.as_view()) < rubi_leaf_count(expr.as_view()) {
11894        candidate
11895    } else {
11896        expr.to_owned()
11897    }
11898}
11899
11900fn rubi_factor_rational_polynomial_coefficients(expr: &Atom, x: Symbol) -> Atom {
11901    fn factor_coefficients(polynomial: &Atom, x: Symbol) -> Option<Atom> {
11902        let original = polynomial;
11903        let terms = collect_polynomial_terms_without_expanding(polynomial, x)
11904            .or_else(|| collect_polynomial_terms(polynomial, x))?;
11905        let factored = terms
11906            .into_iter()
11907            .map(|(degree, coefficient)| {
11908                let coefficient = rubi_try_factor(coefficient.as_view())
11909                    .filter(|candidate| {
11910                        rubi_leaf_count(candidate.as_view())
11911                            < rubi_leaf_count(coefficient.as_view())
11912                    })
11913                    .unwrap_or(coefficient);
11914                (degree, coefficient)
11915            })
11916            .collect();
11917        let collected = polynomial_from_terms(&factored, x);
11918        let candidate = rubi_try_factor(collected.as_view())
11919            .filter(|candidate| {
11920                rubi_leaf_count(candidate.as_view()) < rubi_leaf_count(collected.as_view())
11921            })
11922            .unwrap_or(collected);
11923        Some(
11924            (rubi_leaf_count(candidate.as_view()) < rubi_leaf_count(original.as_view()))
11925                .then_some(candidate)
11926                .unwrap_or_else(|| original.to_owned()),
11927        )
11928    }
11929
11930    let Some((numerator, denominator)) = rational_numerator_denominator_unexpanded(expr) else {
11931        return expr.to_owned();
11932    };
11933    let Some(numerator) = factor_coefficients(&numerator, x) else {
11934        return expr.to_owned();
11935    };
11936    let Some(denominator) = factor_coefficients(&denominator, x) else {
11937        return expr.to_owned();
11938    };
11939    let candidate = numerator / denominator;
11940    if rubi_leaf_count(candidate.as_view()) < rubi_leaf_count(expr.as_view()) {
11941        candidate
11942    } else {
11943        expr.to_owned()
11944    }
11945}
11946
11947fn rubi_expand_cleanup_linear_pair(expr: &Atom, x: Symbol) -> Option<(Atom, Atom)> {
11948    if !matches!(expr.as_view(), AtomView::Add(_)) {
11949        return None;
11950    }
11951    let terms = rubi_add_terms(expr);
11952    for i in 0..terms.len() {
11953        let Some((v, a, b)) = rubi_linear_denominator_term(&terms[i], x) else {
11954            continue;
11955        };
11956        if !freeq!([a, b], x) {
11957            continue;
11958        }
11959        for j in (i + 1)..terms.len() {
11960            let Some((w, c, d)) = rubi_linear_denominator_term(&terms[j], x) else {
11961                continue;
11962            };
11963            if !(freeq!([c, d], x) && eqq!(&b * &c + &a * &d, 0) && eqq!(&d * &v + &b * &w, 0)) {
11964                continue;
11965            }
11966
11967            let rest = terms
11968                .iter()
11969                .enumerate()
11970                .filter_map(|(index, term)| (index != i && index != j).then_some(term.to_owned()))
11971                .fold(Atom::num(0), |sum, term| sum + term);
11972            let denominator = &a * &c + &b * &d * Atom::var(x).pow(2);
11973            let combined = (&c * &v + &a * &w) / &denominator;
11974            return Some((rest + combined, denominator));
11975        }
11976    }
11977
11978    None
11979}
11980
11981fn rubi_restore_expand_cleanup_denominator(expr: &Atom, denominator: &Atom, x: Symbol) -> Atom {
11982    map_sum_terms(expr, |term| {
11983        let Some((numerator, current_denominator)) =
11984            rational_numerator_denominator_unexpanded(term)
11985        else {
11986            return term.to_owned();
11987        };
11988        let factors = rubi_product_factors(&current_denominator);
11989        for i in 0..factors.len() {
11990            for j in (i + 1)..factors.len() {
11991                let pair = factors[i].to_owned() * &factors[j];
11992                let Some(ratio) = rubi_polynomial_proportional_factor(&pair, denominator, x) else {
11993                    continue;
11994                };
11995
11996                let restored_denominator = factors
11997                    .iter()
11998                    .enumerate()
11999                    .filter_map(|(index, factor)| {
12000                        (index != i && index != j).then_some(factor.to_owned())
12001                    })
12002                    .fold(denominator.to_owned(), |product, factor| product * factor);
12003                return numerator / ratio / restored_denominator;
12004            }
12005        }
12006        term.to_owned()
12007    })
12008}
12009
12010fn rubi_polynomial_proportional_factor(left: &Atom, right: &Atom, x: Symbol) -> Option<Atom> {
12011    let left_terms = collect_polynomial_terms(left, x)?;
12012    let right_terms = collect_polynomial_terms(right, x)?;
12013    if left_terms.keys().ne(right_terms.keys()) {
12014        return None;
12015    }
12016
12017    let degree = *left_terms.keys().next()?;
12018    let left_coefficient = left_terms.get(&degree)?;
12019    let right_coefficient = right_terms.get(&degree)?;
12020    if right_coefficient.is_zero() {
12021        return None;
12022    }
12023    let ratio = rubi_cancel(&(left_coefficient / right_coefficient));
12024    if ratio.is_zero() || !freeq!(ratio, x) {
12025        return None;
12026    }
12027
12028    left_terms
12029        .iter()
12030        .all(|(degree, coefficient)| {
12031            right_terms
12032                .get(degree)
12033                .is_some_and(|right_coefficient| eqq!(coefficient, &ratio * right_coefficient))
12034        })
12035        .then_some(ratio)
12036}
12037
12038fn rubi_collect_reciprocals(expr: &Atom, x: Symbol) -> Atom {
12039    if !matches!(expr.as_view(), AtomView::Add(_)) {
12040        return expr.to_owned();
12041    }
12042    let terms = rubi_add_terms(expr);
12043
12044    for i in 0..terms.len() {
12045        let (e, a, b) = match rubi_linear_denominator_term(&terms[i], x) {
12046            Some(parts) if freeq!([parts.0, parts.1, parts.2], x) => parts,
12047            _ => continue,
12048        };
12049        for j in (i + 1)..terms.len() {
12050            let (f, c, d) = match rubi_linear_denominator_term(&terms[j], x) {
12051                Some(parts) if freeq!([parts.0, parts.1, parts.2], x) => parts,
12052                _ => continue,
12053            };
12054            if !eqq!(&b * &c + &a * &d, 0) {
12055                continue;
12056            }
12057
12058            let rest = terms
12059                .iter()
12060                .enumerate()
12061                .filter_map(|(index, term)| (index != i && index != j).then_some(term.to_owned()))
12062                .fold(Atom::num(0), |sum, term| sum + term);
12063            let denominator = &a * &c + &b * &d * Atom::var(x).pow(2);
12064            if eqq!(&d * &e + &b * &f, 0) {
12065                let combined = (&c * &e + &a * &f) / denominator;
12066                return rubi_collect_reciprocals(&(rest + combined), x);
12067            }
12068            if eqq!(&c * &e + &a * &f, 0) {
12069                let combined = (&d * &e + &b * &f) * Atom::var(x) / denominator;
12070                return rubi_collect_reciprocals(&(rest + combined), x);
12071            }
12072        }
12073    }
12074
12075    expr.to_owned()
12076}
12077
12078fn rubi_linear_denominator_term(term: &Atom, x: Symbol) -> Option<(Atom, Atom, Atom)> {
12079    let (numerator, denominator) = rational_numerator_denominator(term)?;
12080    if denominator == Atom::num(1) {
12081        return None;
12082    }
12083    let (a, b) = linear_coefficients(denominator.as_view(), x)?;
12084    (!b.is_zero()).then_some((numerator, a, b))
12085}
12086
12087fn rubi_rational_function_factors(expr: &Atom, x: Symbol) -> Atom {
12088    match expr.as_view() {
12089        AtomView::Mul(mul) => mul
12090            .into_iter()
12091            .map(|factor| {
12092                if rubi_structural_rational_function_q(factor, x) {
12093                    factor.to_owned()
12094                } else {
12095                    Atom::num(1)
12096                }
12097            })
12098            .fold(Atom::num(1), |product, factor| product * factor),
12099        _ if rubi_structural_rational_function_q(expr.as_view(), x) => expr.to_owned(),
12100        _ => Atom::num(1),
12101    }
12102}
12103
12104fn rubi_nonrational_function_factors(expr: &Atom, x: Symbol) -> Atom {
12105    match expr.as_view() {
12106        AtomView::Mul(mul) => mul
12107            .into_iter()
12108            .map(|factor| {
12109                if rubi_structural_rational_function_q(factor, x) {
12110                    Atom::num(1)
12111                } else {
12112                    factor.to_owned()
12113                }
12114            })
12115            .fold(Atom::num(1), |product, factor| product * factor),
12116        _ if rubi_structural_rational_function_q(expr.as_view(), x) => Atom::num(1),
12117        _ => expr.to_owned(),
12118    }
12119}
12120
12121fn rubi_structural_rational_function_q(expr: AtomView<'_>, x: Symbol) -> bool {
12122    if atom_q(expr) || is_free_of(expr, x) {
12123        return true;
12124    }
12125
12126    match expr {
12127        AtomView::Pow(power) if integer_i64_view(power.get_exp()).is_some() => {
12128            rubi_structural_rational_function_q(power.get_base(), x)
12129        }
12130        AtomView::Mul(mul) => mul
12131            .into_iter()
12132            .all(|factor| rubi_structural_rational_function_q(factor, x)),
12133        AtomView::Add(add) => add
12134            .into_iter()
12135            .all(|term| rubi_structural_rational_function_q(term, x)),
12136        _ => false,
12137    }
12138}
12139
12140fn rubi_simplify_term(expr: &Atom, x: Symbol) -> Atom {
12141    // IntegrationUtilityFunctions.m: SimplifyTerm always selects w because
12142    // both branches of its source If are w.
12143    let simplified = rubi_mathematica_simplify(expr);
12144    let together = rubi_together(&simplified);
12145    rubi_normalize_integrand(&together, x)
12146}
12147
12148fn rubi_unify_sum(expr: &Atom, x: Symbol) -> Atom {
12149    if !matches!(expr.as_view(), AtomView::Add(_)) {
12150        return rubi_simplify_term(expr, x);
12151    }
12152    if poly_q(expr, x) {
12153        return expr.to_owned();
12154    }
12155    let terms = rubi_add_terms(expr);
12156
12157    let mut unified: Vec<Atom> = Vec::new();
12158    'terms: for term in terms {
12159        for existing in &mut unified {
12160            let ratio = rubi_simplify(&(existing.to_owned() / &term));
12161            if freeq!(ratio, x) {
12162                *existing = (Atom::num(1) + ratio) * &term;
12163                continue 'terms;
12164            }
12165        }
12166        unified.push(term);
12167    }
12168
12169    unified
12170        .into_iter()
12171        .fold(Atom::num(0), |sum, term| sum + term)
12172}
12173
12174fn map_sum_terms(expr: &Atom, mut f: impl FnMut(&Atom) -> Atom) -> Atom {
12175    match expr.as_view() {
12176        AtomView::Add(add) => add
12177            .into_iter()
12178            .map(|term| f(&term.to_owned()))
12179            .fold(Atom::num(0), |sum, term| sum + term),
12180        _ => f(expr),
12181    }
12182}
12183
12184fn rubi_factor_apart_terms(expr: &Atom, x: Symbol) -> Atom {
12185    // Mathematica Apart factors coefficient polynomials and collects each
12186    // partial-fraction numerator in x by default. Restore that structural
12187    // result before KernelSubst; otherwise affine sequence patterns can spend
12188    // exponential time partitioning an uncollected sum.
12189    let normalize_term = |term: Atom| {
12190        let factored = term.factor();
12191        let Some((numerator, denominator)) = rational_numerator_denominator_unexpanded(&factored)
12192        else {
12193            return factored;
12194        };
12195        numerator.collect_symbol::<u16>(x) / denominator
12196    };
12197
12198    match expr.as_view() {
12199        AtomView::Add(add) => add
12200            .into_iter()
12201            .map(|term| normalize_term(term.to_owned()))
12202            .fold(Atom::num(0), |sum, term| sum + term),
12203        _ => normalize_term(expr.to_owned()),
12204    }
12205}
12206
12207fn rubi_expand_apart_polynomial_quotient(expr: &Atom, x: Symbol) -> Atom {
12208    let mut polynomial_quotient = Atom::num(0);
12209    let mut proper_fractions = Atom::num(0);
12210    for term in rubi_add_terms(expr) {
12211        let denominator = rational_numerator_denominator_unexpanded(&term)
12212            .map(|(_, denominator)| denominator)
12213            .unwrap_or_else(|| Atom::num(1));
12214        if is_free_of(&denominator, x) {
12215            polynomial_quotient += rubi_mathematica_expand(&term, Some(x));
12216        } else {
12217            proper_fractions += term;
12218        }
12219    }
12220
12221    let polynomial_quotient = collect_polynomial_terms_without_expanding(&polynomial_quotient, x)
12222        .map(|terms| {
12223            let terms = terms
12224                .into_iter()
12225                .map(|(degree, coefficient)| (degree, rubi_together(&coefficient)))
12226                .collect();
12227            polynomial_from_terms(&terms, x)
12228        })
12229        .unwrap_or(polynomial_quotient);
12230    polynomial_quotient + proper_fractions
12231}
12232
12233fn rubi_smart_apart(expr: &Atom, x: Symbol) -> Atom {
12234    rubi_smart_apart_impl(expr, None, x)
12235}
12236
12237fn rubi_smart_apart_in(expr: &Atom, variable: Symbol, x: Symbol) -> Atom {
12238    rubi_smart_apart_impl(expr, Some(variable), x)
12239}
12240
12241fn rubi_smart_apart_impl(expr: &Atom, variable: Option<Symbol>, x: Symbol) -> Atom {
12242    #[cfg(feature = "trace")]
12243    let trace_start = RUBI_SETTINGS
12244        .trace_helpers
12245        .load(AtomicOrdering::Relaxed)
12246        .then(std::time::Instant::now);
12247    if variable.is_none()
12248        && let Some(rationalized) = rubi_smart_apart_squared_square_root_sum_denominator(expr, x)
12249    {
12250        #[cfg(feature = "trace")]
12251        if let Some(start) = trace_start {
12252            eprintln!(
12253                "SmartApart squared square-root sum denominator {:?}",
12254                start.elapsed()
12255            );
12256        }
12257        return rationalized;
12258    }
12259    let mut kernels = Vec::new();
12260    rubi_make_assoc_list(expr, x, &mut kernels);
12261    if !kernels.is_empty() {
12262        let substitutions: Vec<(Symbol, Atom)> = kernels
12263            .into_iter()
12264            .enumerate()
12265            .map(|(index, kernel)| {
12266                let symbol = Symbol::parse(format!("RubiSmartApart{index}"), "ruby")
12267                    .expect("SmartApart temporary symbol should parse");
12268                (symbol, kernel)
12269            })
12270            .collect();
12271
12272        let gensymed = rubi_gensym_subst(expr, &substitutions);
12273        let apart = rubi_factor_apart_terms(&rubi_mathematica_apart(&gensymed, variable, x), x);
12274        #[cfg(feature = "trace")]
12275        if let Some(start) = trace_start {
12276            eprintln!("SmartApart gensym apart {:?}", start.elapsed());
12277        }
12278        return rubi_kernel_subst(&apart, &substitutions).unwrap_or_else(|| expr.to_owned());
12279    }
12280
12281    let apart = rubi_factor_apart_terms(&rubi_mathematica_apart(expr, variable, x), x);
12282    if let Some(rationalized) = rubi_smart_apart_square_root_denominator(expr, x) {
12283        if rationalized != apart && rubi_sum_q(&rationalized) {
12284            #[cfg(feature = "trace")]
12285            if let Some(start) = trace_start {
12286                eprintln!("SmartApart square-root denominator {:?}", start.elapsed());
12287            }
12288            return rationalized;
12289        }
12290    }
12291    if let Some(rationalized) = rubi_smart_apart_fractional_power_denominator(expr, x) {
12292        if rationalized != apart && rubi_sum_q(&rationalized) {
12293            #[cfg(feature = "trace")]
12294            if let Some(start) = trace_start {
12295                eprintln!(
12296                    "SmartApart fractional-power denominator {:?}",
12297                    start.elapsed()
12298                );
12299            }
12300            return rationalized;
12301        }
12302    }
12303    #[cfg(feature = "trace")]
12304    if let Some(start) = trace_start {
12305        eprintln!("SmartApart plain apart {:?}", start.elapsed());
12306    }
12307    apart
12308}
12309
12310fn rubi_smart_apart_squared_square_root_sum_denominator(expr: &Atom, x: Symbol) -> Option<Atom> {
12311    let mut numerator_factors = Vec::new();
12312    let mut standalone = None;
12313    let mut squared_sum_base = None;
12314    for factor in rubi_product_factors(expr) {
12315        let AtomView::Pow(power) = factor.as_view() else {
12316            numerator_factors.push(factor);
12317            continue;
12318        };
12319        let base = power.get_base().to_owned();
12320        let exponent = power.get_exp().to_owned();
12321        if integer_i64(&exponent) == Some(-2)
12322            && rubi_add_terms(&base).len() == 2
12323            && squared_sum_base.is_none()
12324        {
12325            squared_sum_base = Some(base);
12326        } else if rubi_fraction_parts(&exponent) == Some((-1, 2)) && standalone.is_none() {
12327            standalone = Some(base.pow(Atom::num((1, 2))));
12328        } else {
12329            numerator_factors.push(factor);
12330        }
12331    }
12332    let numerator = product_atoms(&numerator_factors);
12333    if !rubi_structural_rational_function_q(numerator.as_view(), x) {
12334        return None;
12335    }
12336    let standalone = standalone?;
12337    let sum_terms = rubi_add_terms(&squared_sum_base?);
12338    let [left, right] = sum_terms.as_slice() else {
12339        return None;
12340    };
12341    let other = if left == &standalone {
12342        right
12343    } else if right == &standalone {
12344        left
12345    } else {
12346        return None;
12347    };
12348
12349    let (standalone_coefficient, standalone_radical) = rubi_single_square_root_factor(&standalone)?;
12350    let (other_coefficient, other_radical) = rubi_single_square_root_factor(other)?;
12351    let standalone_square =
12352        standalone_coefficient.pow(2) * rubi_square_root_radicand(&standalone_radical)?;
12353    let other_square = other_coefficient.pow(2) * rubi_square_root_radicand(&other_radical)?;
12354    if !rubi_structural_rational_function_q(standalone_square.as_view(), x)
12355        || !rubi_structural_rational_function_q(other_square.as_view(), x)
12356    {
12357        return None;
12358    }
12359
12360    // Apart rationalizes 1/(r (r+s)^2) with (r-s)^2.  Split the result into
12361    // rational coefficients before restoring the two square-root factors so
12362    // Symbolica cannot recombine them into opaque algebraic kernels.
12363    let difference = (&standalone_square - &other_square).expand().cancel();
12364    if difference.is_zero() {
12365        return None;
12366    }
12367    let denominator_square = difference.pow(2);
12368    let standalone_coefficient =
12369        (&numerator * (&standalone_square + &other_square) / &denominator_square).apart(x);
12370    let other_coefficient = (-Atom::num(2) * &numerator / denominator_square).apart(x);
12371    let rationalized = map_sum_terms(&standalone_coefficient, |coefficient| {
12372        coefficient / &standalone
12373    }) + map_sum_terms(&other_coefficient, |coefficient| coefficient * other);
12374
12375    let residual = (rationalized.to_owned() - expr).together();
12376    (rubi_sum_q(&rationalized) && rubi_algebraic_zero_q(&residual)).then_some(rationalized)
12377}
12378
12379fn rubi_mathematica_apart(expr: &Atom, variable: Option<Symbol>, x: Symbol) -> Atom {
12380    if let Some(variable) = variable {
12381        // SmartApart[u,v,x] calls Apart[...,v].
12382        let apart = expr.apart(variable);
12383        return rubi_expand_apart_polynomial_quotient(&apart, variable);
12384    }
12385
12386    // SmartApart[u,x] calls Mathematica's Apart[...] without a variable. If
12387    // only the numerator is nonrational, Apart distributes that numerator but
12388    // does not partial-fraction the rational denominator with respect to x.
12389    if !rubi_rational_function_q(expr, x)
12390        && rational_numerator_denominator_unexpanded(expr).is_some_and(|(_, denominator)| {
12391            rubi_structural_rational_function_q(denominator.as_view(), x)
12392        })
12393    {
12394        let expanded = rubi_distribute_explicit_product_sums(expr);
12395        if rubi_sum_q(&expanded) {
12396            return rubi_factor_apart_terms(&expanded, x);
12397        }
12398    }
12399
12400    // Mathematica's variable-free Apart expands a top-level affine expression
12401    // in a logarithmic kernel, while Symbolica keeps that factor intact.
12402    let default_kernels = rubi_mathematica_default_apart_kernels(expr);
12403    let has_powered_logarithmic_factor = rubi_product_factors(expr).into_iter().any(|factor| {
12404        let AtomView::Pow(power) = factor.as_view() else {
12405            return false;
12406        };
12407        integer_i64_view(power.get_exp()).is_some_and(|exponent| exponent > 1)
12408            && rubi_contains_function_symbol(&power.get_base().to_owned(), Symbol::LOG)
12409    });
12410    for (index, kernel) in default_kernels.iter().cloned().enumerate() {
12411        let AtomView::Fun(function) = kernel.as_view() else {
12412            continue;
12413        };
12414        if function.get_symbol() != Symbol::LOG {
12415            continue;
12416        }
12417        let top_level_add_factor_contains_kernel = rubi_product_factors(expr)
12418            .into_iter()
12419            .filter(|factor| matches!(factor.as_view(), AtomView::Add(_)))
12420            .any(|factor| {
12421                rubi_add_terms(&factor).into_iter().any(|term| {
12422                    term == kernel
12423                        || rubi_product_factors(&term)
12424                            .into_iter()
12425                            .any(|factor| factor == kernel)
12426                })
12427            });
12428        if !has_powered_logarithmic_factor || !top_level_add_factor_contains_kernel {
12429            continue;
12430        }
12431        let temporary = Symbol::parse(format!("RubiDefaultApartKernel{index}"), "ruby")
12432            .expect("the internal Apart kernel symbol should parse");
12433        let temporary_atom = Atom::var(temporary);
12434        let transformed = expr
12435            .replace(kernel.to_pattern())
12436            .with(temporary_atom.to_pattern());
12437        if rubi_expon(transformed.as_view(), temporary) != Some(1)
12438            || rational_numerator_denominator_unexpanded(&transformed)
12439                .is_some_and(|(_, denominator)| denominator.contains_symbol(temporary))
12440        {
12441            continue;
12442        }
12443        let apart = transformed.apart(temporary);
12444        // Mathematica Apart expands its polynomial quotient in the selected
12445        // kernel; Symbolica may leave a polynomial factor intact.
12446        let apart = rubi_expand_apart_polynomial_quotient(&apart, temporary)
12447            .replace(temporary_atom.to_pattern())
12448            .with(kernel.to_pattern());
12449        if apart != *expr {
12450            return apart;
12451        }
12452    }
12453
12454    // Retain Symbolica's direct canonical-kernel behavior for all other
12455    // variable-free Apart calls.
12456    if let Some(kernel) = default_kernels.first()
12457        && let Ok(indeterminate) = Indeterminate::try_from(kernel.to_owned())
12458    {
12459        return expr.apart(&indeterminate);
12460    }
12461    if let Some(apart) = rubi_mathematica_default_apart_power_kernel(expr, x) {
12462        return apart;
12463    }
12464
12465    expr.apart(x)
12466}
12467
12468fn rubi_distribute_explicit_product_sums(expr: &Atom) -> Atom {
12469    let AtomView::Mul(mul) = expr.as_view() else {
12470        return expr.to_owned();
12471    };
12472
12473    let mut terms = vec![Atom::num(1)];
12474    for factor in mul {
12475        let factor = factor.to_owned();
12476        let factor_terms = rubi_add_terms(&factor);
12477        if factor_terms.len() == 1 {
12478            for term in &mut terms {
12479                *term *= &factor;
12480            }
12481            continue;
12482        }
12483
12484        terms = terms
12485            .into_iter()
12486            .flat_map(|term| {
12487                factor_terms
12488                    .iter()
12489                    .map(move |factor_term| &term * factor_term)
12490            })
12491            .collect();
12492    }
12493
12494    terms.into_iter().sum()
12495}
12496
12497fn rubi_mathematica_default_apart_power_kernel(expr: &Atom, x: Symbol) -> Option<Atom> {
12498    fn collect_exponents(expr: &Atom, x: Symbol, exponents: &mut Vec<Atom>) {
12499        match expr.as_view() {
12500            AtomView::Pow(power) if power.get_base() == InlineVar::new(x).as_view() => {
12501                let exponent = power.get_exp().to_owned();
12502                if is_free_of(&exponent, x)
12503                    && integer_i64(&exponent).is_none()
12504                    && !exponents.iter().any(|existing| existing == &exponent)
12505                {
12506                    exponents.push(exponent);
12507                }
12508            }
12509            AtomView::Pow(power) => {
12510                collect_exponents(&power.get_base().to_owned(), x, exponents);
12511                collect_exponents(&power.get_exp().to_owned(), x, exponents);
12512            }
12513            AtomView::Add(add) => {
12514                for term in add {
12515                    collect_exponents(&term.to_owned(), x, exponents);
12516                }
12517            }
12518            AtomView::Mul(mul) => {
12519                for factor in mul {
12520                    collect_exponents(&factor.to_owned(), x, exponents);
12521                }
12522            }
12523            AtomView::Fun(function) => {
12524                for argument in function {
12525                    collect_exponents(&argument.to_owned(), x, exponents);
12526                }
12527            }
12528            AtomView::Num(_) | AtomView::Var(_) => {}
12529        }
12530    }
12531
12532    let mut exponents = Vec::new();
12533    collect_exponents(expr, x, &mut exponents);
12534    exponents.sort_by_key(|exponent| !rubi_pos_q(exponent));
12535    let kernel_exponent = exponents
12536        .into_iter()
12537        .find(|candidate| exponents_are_integer_multiples(expr, x, candidate))?;
12538    let temporary = fresh_substitution_symbol()?;
12539    let temporary_atom = Atom::var(temporary.symbol());
12540    let transformed =
12541        rubi_subst_power_target_aux(expr, x, &Atom::var(x), &kernel_exponent, &temporary_atom);
12542    if transformed == *expr || transformed.contains_symbol(x) {
12543        return None;
12544    }
12545
12546    let apart = transformed.apart(temporary.symbol());
12547    // Mathematica Apart returns the polynomial quotient expanded termwise in
12548    // the selected kernel while preserving proper-fraction numerators.
12549    let apart = rubi_expand_apart_polynomial_quotient(&apart, temporary.symbol());
12550    let apart = rubi_factor_apart_terms(&apart, temporary.symbol());
12551    let restored = apart
12552        .replace(temporary_atom.to_pattern())
12553        .with(Atom::var(x).pow(kernel_exponent).to_pattern());
12554    (restored != *expr).then_some(restored)
12555}
12556
12557fn exponents_are_integer_multiples(expr: &Atom, x: Symbol, candidate: &Atom) -> bool {
12558    fn check(expr: &Atom, x: Symbol, candidate: &Atom, saw_power: &mut bool) -> bool {
12559        match expr.as_view() {
12560            AtomView::Pow(power) if power.get_base() == InlineVar::new(x).as_view() => {
12561                let exponent = power.get_exp().to_owned();
12562                if is_free_of(&exponent, x) && integer_i64(&exponent).is_none() {
12563                    *saw_power = true;
12564                    return integer_i64(&rubi_simplify(&(exponent / candidate)))
12565                        .is_some_and(|ratio| ratio != 0);
12566                }
12567                true
12568            }
12569            AtomView::Pow(power) => {
12570                check(&power.get_base().to_owned(), x, candidate, saw_power)
12571                    && check(&power.get_exp().to_owned(), x, candidate, saw_power)
12572            }
12573            AtomView::Add(add) => add
12574                .into_iter()
12575                .all(|term| check(&term.to_owned(), x, candidate, saw_power)),
12576            AtomView::Mul(mul) => mul
12577                .into_iter()
12578                .all(|factor| check(&factor.to_owned(), x, candidate, saw_power)),
12579            AtomView::Fun(function) => function
12580                .into_iter()
12581                .all(|argument| check(&argument.to_owned(), x, candidate, saw_power)),
12582            AtomView::Num(_) | AtomView::Var(_) => true,
12583        }
12584    }
12585
12586    let mut saw_power = false;
12587    check(expr, x, candidate, &mut saw_power) && saw_power
12588}
12589
12590fn rubi_mathematica_default_apart_kernels(expr: &Atom) -> Vec<Atom> {
12591    fn collect(expr: &Atom, kernels: &mut Vec<Atom>) {
12592        match expr.as_view() {
12593            AtomView::Fun(_) => {
12594                if !kernels.iter().any(|kernel| kernel == expr) {
12595                    kernels.push(expr.to_owned());
12596                }
12597            }
12598            AtomView::Pow(power) => collect(&power.get_base().to_owned(), kernels),
12599            AtomView::Add(add) => {
12600                for term in add {
12601                    collect(&term.to_owned(), kernels);
12602                }
12603            }
12604            AtomView::Mul(mul) => {
12605                for factor in mul {
12606                    collect(&factor.to_owned(), kernels);
12607                }
12608            }
12609            AtomView::Num(_) | AtomView::Var(_) => {}
12610        }
12611    }
12612
12613    fn head_name(expr: &Atom) -> String {
12614        let AtomView::Fun(function) = expr.as_view() else {
12615            return String::new();
12616        };
12617        function
12618            .get_symbol()
12619            .get_stripped_ascii_name()
12620            .unwrap_or_default()
12621            .to_owned()
12622    }
12623
12624    let mut kernels = Vec::new();
12625    collect(expr, &mut kernels);
12626    kernels.sort_by(|left, right| head_name(right).cmp(&head_name(left)).then(right.cmp(left)));
12627    kernels
12628}
12629
12630fn rubi_smart_apart_fractional_power_denominator(expr: &Atom, x: Symbol) -> Option<Atom> {
12631    let (numerator, denominator) = rational_numerator_denominator(expr)?;
12632    let terms = rubi_add_terms(&denominator);
12633    if terms.len() < 2 {
12634        return None;
12635    }
12636
12637    let mut radical = None;
12638    let mut radical_coefficient = Atom::num(0);
12639    let mut nonradical = Atom::num(0);
12640    let mut radical_base = Atom::num(0);
12641    let mut radical_numerator = 0;
12642    let mut radical_denominator = 0;
12643
12644    for term in terms {
12645        if let Some((coefficient, term_radical, base, power_numerator, power_denominator)) =
12646            rubi_single_fractional_power_factor(&term, x)
12647        {
12648            if let Some(existing) = &radical {
12649                if existing != &term_radical {
12650                    return None;
12651                }
12652            } else {
12653                radical = Some(term_radical);
12654                radical_base = base;
12655                radical_numerator = power_numerator;
12656                radical_denominator = power_denominator;
12657            }
12658            radical_coefficient += coefficient;
12659        } else {
12660            if !rubi_structural_rational_function_q(term.as_view(), x) {
12661                return None;
12662            }
12663            nonradical += term;
12664        }
12665    }
12666
12667    let _ = radical?;
12668    if radical_denominator <= 2
12669        || radical_numerator <= 0
12670        || nonradical.is_zero()
12671        || radical_coefficient.is_zero()
12672    {
12673        return None;
12674    }
12675
12676    // Mathematica Apart rationalizes this denominator before decomposing the
12677    // rational coefficients. Symbolica currently stops after polynomial
12678    // division (see symbolica_apart_sixth_root_denominator_mre), so reproduce
12679    // Apart's finite geometric identity inside the shared SmartApart adapter.
12680    let degree = radical_denominator;
12681    let mut conjugate = Atom::num(0);
12682    for power in 0..degree {
12683        let power_numerator = radical_numerator.checked_mul(power)?;
12684        let radical_power = (-&radical_coefficient).pow(power)
12685            * radical_base
12686                .to_owned()
12687                .pow(Atom::num((power_numerator, radical_denominator)));
12688        let rational_power = nonradical.pow(degree - 1 - power);
12689        conjugate += radical_power * rational_power;
12690    }
12691
12692    let signed_radical_power = if (degree - 1) % 2 == 0 {
12693        radical_coefficient.pow(degree) * radical_base.pow(radical_numerator)
12694    } else {
12695        -radical_coefficient.pow(degree) * radical_base.pow(radical_numerator)
12696    };
12697    let rationalized_denominator = (nonradical.pow(degree) + signed_radical_power)
12698        .expand()
12699        .cancel();
12700    if !rubi_structural_rational_function_q(rationalized_denominator.as_view(), x) {
12701        return None;
12702    }
12703
12704    let rationalized_numerator = (numerator * conjugate).expand();
12705    let mut rationalized = Atom::num(0);
12706    for term in rubi_add_terms(&rationalized_numerator) {
12707        let rational_factors = rubi_rational_function_factors(&term, x);
12708        let nonrational_factors = rubi_nonrational_function_factors(&term, x);
12709        let coefficient_apart =
12710            rubi_factor_apart_terms(&(rational_factors / &rationalized_denominator).apart(x), x);
12711        rationalized += map_sum_terms(&coefficient_apart, |coefficient| {
12712            coefficient * &nonrational_factors
12713        });
12714    }
12715
12716    let residual = (rationalized.to_owned() - expr).together();
12717    rubi_algebraic_zero_q(&residual).then_some(rationalized)
12718}
12719
12720fn rubi_single_fractional_power_factor(
12721    expr: &Atom,
12722    x: Symbol,
12723) -> Option<(Atom, Atom, Atom, i64, i64)> {
12724    let mut radical = None;
12725    let mut coefficient_factors = Vec::new();
12726    for factor in rubi_product_factors(expr) {
12727        let AtomView::Pow(power) = factor.as_view() else {
12728            coefficient_factors.push(factor);
12729            continue;
12730        };
12731        let base = power.get_base().to_owned();
12732        let exponent = power.get_exp().to_owned();
12733        let Some((numerator, denominator)) = rubi_fraction_parts(&exponent) else {
12734            coefficient_factors.push(factor);
12735            continue;
12736        };
12737        if radical.is_some() {
12738            return None;
12739        }
12740        radical = Some((factor, base, numerator, denominator));
12741    }
12742
12743    let (radical, base, numerator, denominator) = radical?;
12744    let coefficient = product_atoms(&coefficient_factors);
12745    if !rubi_structural_rational_function_q(coefficient.as_view(), x)
12746        || !rubi_structural_rational_function_q(base.as_view(), x)
12747    {
12748        return None;
12749    }
12750    Some((coefficient, radical, base, numerator, denominator))
12751}
12752
12753fn rubi_smart_apart_square_root_denominator(expr: &Atom, x: Symbol) -> Option<Atom> {
12754    let (numerator, denominator) = rational_numerator_denominator_unexpanded(expr)?;
12755    let numerator = rubi_mathematica_expand(&numerator, Some(x));
12756    // Mathematica Apart expands denominator products before rationalizing
12757    // algebraic square-root coefficients, but Expand does not descend into a
12758    // fractional power's base.
12759    let denominator = rubi_mathematica_expand(&denominator, Some(x));
12760    let terms = rubi_add_terms(&denominator);
12761    if terms.len() < 2 {
12762        return None;
12763    }
12764
12765    if let Some(rationalized) =
12766        rubi_smart_apart_two_square_root_denominator(&numerator, &terms, expr, x)
12767    {
12768        return Some(rationalized);
12769    }
12770
12771    let mut radical_coefficient = Atom::num(0);
12772    let mut radical_term = Atom::num(0);
12773    let mut radical = None;
12774    let mut nonradical = Atom::num(0);
12775    for term in terms {
12776        if let Some((coefficient, term_radical)) = rubi_single_square_root_factor(&term) {
12777            if let Some(radical) = &radical {
12778                if radical != &term_radical {
12779                    return None;
12780                }
12781            } else {
12782                radical = Some(term_radical);
12783            }
12784            radical_coefficient += coefficient;
12785            radical_term += term;
12786        } else {
12787            nonradical += term;
12788        }
12789    }
12790
12791    let radical = radical?;
12792    let radicand = rubi_square_root_radicand(&radical)?;
12793    if nonradical.is_zero() || rubi_contains_subexpression(nonradical.as_view(), radical.as_view())
12794    {
12795        return None;
12796    }
12797
12798    let conjugate = &nonradical - &radical_term;
12799    let rationalized_denominator = (nonradical.pow(2) - radical_coefficient.pow(2) * radicand)
12800        .expand()
12801        .cancel();
12802    if rubi_contains_subexpression(rationalized_denominator.as_view(), radical.as_view()) {
12803        return None;
12804    }
12805
12806    let rationalized = if !rubi_contains_subexpression(numerator.as_view(), radical.as_view()) {
12807        // Keep the rational and radical coefficients separate: Symbolica
12808        // canonically recombines base*sqrt(base) into base^(3/2).
12809        let nonradical_numerator = (numerator.to_owned() * &nonradical).expand();
12810        let radical_numerator = (-numerator * &radical_coefficient).expand();
12811        (nonradical_numerator / &rationalized_denominator).apart(x)
12812            + &radical * (radical_numerator / &rationalized_denominator).apart(x)
12813    } else {
12814        let rationalized_numerator = (numerator * conjugate).expand();
12815        rubi_apart_linear_radical_numerator(
12816            &rationalized_numerator,
12817            &rationalized_denominator,
12818            &radical,
12819            x,
12820        )
12821        .unwrap_or_else(|| {
12822            rubi_split_additive_fraction_numerators_by_radical(
12823                &(rationalized_numerator / rationalized_denominator)
12824                    .apart(x)
12825                    .cancel(),
12826                &radical,
12827            )
12828        })
12829    }
12830    .expand();
12831    let residual = (rationalized.to_owned() - expr).together();
12832    rubi_algebraic_zero_q(&residual).then_some(rationalized)
12833}
12834
12835fn rubi_smart_apart_two_square_root_denominator(
12836    numerator: &Atom,
12837    denominator_terms: &[Atom],
12838    original: &Atom,
12839    x: Symbol,
12840) -> Option<Atom> {
12841    // Mathematica's variable-free Apart expands polynomial factors around a
12842    // difference of radicals before conjugating it.  Collect the expanded
12843    // terms by their square-root factor so that, for example,
12844    // (1+x^2)^2*(-Sqrt[x]+Sqrt[x/(1+x^2)^2]) is still recognized as a
12845    // two-radical denominator.
12846    let mut radical_terms: Vec<(Atom, Atom)> = Vec::new();
12847    for term in denominator_terms {
12848        let (coefficient, radical) = rubi_single_square_root_factor(term)?;
12849        if let Some((_, existing_coefficient)) = radical_terms
12850            .iter_mut()
12851            .find(|(existing_radical, _)| existing_radical == &radical)
12852        {
12853            *existing_coefficient += coefficient;
12854        } else {
12855            radical_terms.push((radical, coefficient));
12856        }
12857    }
12858    let [first, second] = radical_terms.as_slice() else {
12859        return None;
12860    };
12861    let (first_radical, first_coefficient) = first;
12862    let (second_radical, second_coefficient) = second;
12863    if first_radical == second_radical {
12864        return None;
12865    }
12866
12867    let first_coefficient = rubi_factor(first_coefficient);
12868    let second_coefficient = rubi_factor(second_coefficient);
12869    let first_radicand = rubi_square_root_radicand(first_radical)?;
12870    let second_radicand = rubi_square_root_radicand(second_radical)?;
12871    let conjugate = &first_coefficient * first_radical - &second_coefficient * second_radical;
12872    let rationalized_denominator = (first_coefficient.pow(2) * first_radicand
12873        - second_coefficient.pow(2) * second_radicand)
12874        .expand()
12875        .cancel();
12876    if rubi_contains_subexpression(rationalized_denominator.as_view(), first_radical.as_view())
12877        || rubi_contains_subexpression(rationalized_denominator.as_view(), second_radical.as_view())
12878    {
12879        return None;
12880    }
12881
12882    // Distribute over the conjugate's two radical terms, while retaining each
12883    // grouped polynomial coefficient.  Expanding those coefficients first
12884    // prevents Symbolica's Apart from cancelling the common factor that
12885    // Mathematica cancels before partial-fraction decomposition.
12886    let rationalized_numerator = map_sum_terms(&conjugate, |term| numerator * term);
12887    let rationalized = rubi_apart_two_radical_numerator(
12888        &rationalized_numerator,
12889        &rationalized_denominator,
12890        first_radical,
12891        second_radical,
12892        x,
12893    )?;
12894    let residual = (rationalized.to_owned() - original).together();
12895    rubi_algebraic_zero_q(&residual).then_some(rationalized)
12896}
12897
12898fn rubi_apart_two_radical_numerator(
12899    numerator: &Atom,
12900    denominator: &Atom,
12901    first_radical: &Atom,
12902    second_radical: &Atom,
12903    x: Symbol,
12904) -> Option<Atom> {
12905    let apart_coefficient = |numerator: Atom| {
12906        let cancelled = (numerator / denominator).cancel().factor();
12907        let decomposed = cancelled.apart(x);
12908        rubi_factor_apart_terms(&decomposed, x)
12909    };
12910    let mut apart = Atom::num(0);
12911    for term in rubi_add_terms(numerator) {
12912        match rubi_single_square_root_factor(&term) {
12913            None => apart += apart_coefficient(term),
12914            Some((coefficient, radical)) if radical == *first_radical => {
12915                let coefficient_apart = apart_coefficient(coefficient);
12916                apart += map_sum_terms(&coefficient_apart, |coefficient_term| {
12917                    first_radical * coefficient_term
12918                });
12919            }
12920            Some((coefficient, radical)) if radical == *second_radical => {
12921                let coefficient_apart = apart_coefficient(coefficient);
12922                apart += map_sum_terms(&coefficient_apart, |coefficient_term| {
12923                    second_radical * coefficient_term
12924                });
12925            }
12926            Some(_) => return None,
12927        }
12928    }
12929    Some(apart)
12930}
12931
12932fn rubi_apart_linear_radical_numerator(
12933    numerator: &Atom,
12934    denominator: &Atom,
12935    radical: &Atom,
12936    x: Symbol,
12937) -> Option<Atom> {
12938    let (nonradical_numerator, radical_numerator) =
12939        rubi_split_linear_radical_numerator(numerator, radical)?;
12940    let mut apart = Atom::num(0);
12941    if !nonradical_numerator.is_zero() {
12942        apart += (nonradical_numerator / denominator).apart(x);
12943    }
12944    if !radical_numerator.is_zero() {
12945        apart += radical * (radical_numerator / denominator).apart(x);
12946    }
12947    Some(apart)
12948}
12949
12950fn rubi_split_linear_radical_numerator(numerator: &Atom, radical: &Atom) -> Option<(Atom, Atom)> {
12951    let mut nonradical_numerator = Atom::num(0);
12952    let mut radical_numerator = Atom::num(0);
12953
12954    for term in rubi_add_terms(numerator) {
12955        if !rubi_contains_subexpression(term.as_view(), radical.as_view()) {
12956            nonradical_numerator += term;
12957            continue;
12958        }
12959
12960        let factors = rubi_product_factors(&term);
12961        let Some(index) = factors.iter().position(|factor| factor == radical) else {
12962            return None;
12963        };
12964        let mut coefficient_factors = factors;
12965        let _ = coefficient_factors.remove(index);
12966        let coefficient = product_atoms(&coefficient_factors);
12967        if rubi_contains_subexpression(coefficient.as_view(), radical.as_view()) {
12968            return None;
12969        }
12970        radical_numerator += coefficient;
12971    }
12972
12973    Some((nonradical_numerator, radical_numerator))
12974}
12975
12976fn rubi_square_root_radicand(expr: &Atom) -> Option<Atom> {
12977    let AtomView::Pow(power) = expr.as_view() else {
12978        return None;
12979    };
12980    (rubi_fraction_parts(&power.get_exp().to_owned()) == Some((1, 2)))
12981        .then(|| power.get_base().to_owned())
12982}
12983
12984fn rubi_single_square_root_factor(expr: &Atom) -> Option<(Atom, Atom)> {
12985    let factors = rubi_product_factors(expr);
12986    let mut radical = None;
12987    let mut coefficient_factors = Vec::new();
12988    for factor in factors {
12989        if let Some((coefficient, factor_radical)) = rubi_square_root_factor_parts(&factor) {
12990            if radical.is_some() {
12991                return None;
12992            }
12993            coefficient_factors.push(coefficient);
12994            radical = Some(factor_radical);
12995        } else {
12996            coefficient_factors.push(factor);
12997        }
12998    }
12999
13000    Some((product_atoms(&coefficient_factors), radical?))
13001}
13002
13003fn rubi_square_root_factor_parts(expr: &Atom) -> Option<(Atom, Atom)> {
13004    let AtomView::Pow(power) = expr.as_view() else {
13005        return None;
13006    };
13007    let (numerator, denominator) = rubi_fraction_parts(&power.get_exp().to_owned())?;
13008    if denominator != 2 || numerator <= 0 || numerator % 2 == 0 {
13009        return None;
13010    }
13011
13012    let base = power.get_base().to_owned();
13013    let coefficient = base.pow((numerator - 1) / 2);
13014    let radical = base.pow((1, 2));
13015    Some((coefficient, radical))
13016}
13017
13018fn rubi_contains_subexpression(expr: AtomView<'_>, needle: AtomView<'_>) -> bool {
13019    if expr == needle {
13020        return true;
13021    }
13022
13023    match expr {
13024        AtomView::Add(add) => add
13025            .into_iter()
13026            .any(|term| rubi_contains_subexpression(term, needle)),
13027        AtomView::Mul(mul) => mul
13028            .into_iter()
13029            .any(|factor| rubi_contains_subexpression(factor, needle)),
13030        AtomView::Pow(power) => {
13031            rubi_contains_subexpression(power.get_base(), needle)
13032                || rubi_contains_subexpression(power.get_exp(), needle)
13033        }
13034        AtomView::Fun(fun) => fun
13035            .into_iter()
13036            .any(|argument| rubi_contains_subexpression(argument, needle)),
13037        AtomView::Num(_) | AtomView::Var(_) => false,
13038    }
13039}
13040
13041fn rubi_split_additive_fraction_numerators_by_radical(expr: &Atom, radical: &Atom) -> Atom {
13042    map_sum_terms(expr, |term| {
13043        let Some((numerator, denominator)) = rational_numerator_denominator(term) else {
13044            return term.to_owned();
13045        };
13046        if denominator.is_one() || !rubi_sum_q(&numerator) {
13047            return term.to_owned();
13048        }
13049
13050        let (radical_terms, nonradical_terms) = rubi_add_terms(&numerator).into_iter().fold(
13051            (Atom::num(0), Atom::num(0)),
13052            |(radical_sum, nonradical_sum), numerator_term| {
13053                if rubi_contains_subexpression(numerator_term.as_view(), radical.as_view()) {
13054                    (radical_sum + numerator_term, nonradical_sum)
13055                } else {
13056                    (radical_sum, nonradical_sum + numerator_term)
13057                }
13058            },
13059        );
13060
13061        let mut split = Atom::num(0);
13062        if !nonradical_terms.is_zero() {
13063            split += nonradical_terms / &denominator;
13064        }
13065        if !radical_terms.is_zero() {
13066            split += radical_terms / &denominator;
13067        }
13068        split
13069    })
13070}
13071
13072fn rubi_make_assoc_list(expr: &Atom, x: Symbol, kernels: &mut Vec<Atom>) {
13073    match expr.as_view() {
13074        AtomView::Num(_) | AtomView::Var(_) => {}
13075        AtomView::Pow(power) if integer_i64_view(power.get_exp()).is_some() => {
13076            rubi_make_assoc_list(&power.get_base().to_owned(), x, kernels);
13077        }
13078        AtomView::Add(add) => {
13079            for term in add {
13080                rubi_make_assoc_list(&term.to_owned(), x, kernels);
13081            }
13082        }
13083        AtomView::Mul(mul) => {
13084            for factor in mul {
13085                rubi_make_assoc_list(&factor.to_owned(), x, kernels);
13086            }
13087        }
13088        _ if is_free_of(expr, x) && !kernels.iter().any(|kernel| kernel == expr) => {
13089            kernels.push(expr.to_owned());
13090        }
13091        _ => {}
13092    }
13093}
13094
13095fn rubi_gensym_subst(expr: &Atom, substitutions: &[(Symbol, Atom)]) -> Atom {
13096    match expr.as_view() {
13097        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
13098        AtomView::Pow(power) if integer_i64_view(power.get_exp()).is_some() => {
13099            rubi_gensym_subst(&power.get_base().to_owned(), substitutions)
13100                .pow(power.get_exp().to_owned())
13101        }
13102        AtomView::Add(add) => add
13103            .into_iter()
13104            .map(|term| rubi_gensym_subst(&term.to_owned(), substitutions))
13105            .fold(Atom::num(0), |sum, term| sum + term),
13106        AtomView::Mul(mul) => mul
13107            .into_iter()
13108            .map(|factor| rubi_gensym_subst(&factor.to_owned(), substitutions))
13109            .fold(Atom::num(1), |product, factor| product * factor),
13110        _ => substitutions
13111            .iter()
13112            .find_map(|(symbol, kernel)| (kernel == expr).then(|| Atom::var(*symbol)))
13113            .unwrap_or_else(|| expr.to_owned()),
13114    }
13115}
13116
13117fn rubi_kernel_subst(expr: &Atom, substitutions: &[(Symbol, Atom)]) -> Option<Atom> {
13118    match expr.as_view() {
13119        AtomView::Var(variable) => substitutions
13120            .iter()
13121            .find_map(|(symbol, kernel)| {
13122                (variable.get_symbol() == *symbol).then(|| kernel.to_owned())
13123            })
13124            .or_else(|| Some(expr.to_owned())),
13125        AtomView::Pow(power) => {
13126            let base = rubi_kernel_subst(&power.get_base().to_owned(), substitutions)?;
13127            let exponent = power.get_exp().to_owned();
13128            if integer_i64(&exponent).is_some_and(|exponent| exponent < 0) && base.is_zero() {
13129                return None;
13130            }
13131            Some(base.pow(exponent))
13132        }
13133        AtomView::Add(add) => add.into_iter().try_fold(Atom::num(0), |sum, term| {
13134            rubi_kernel_subst(&term.to_owned(), substitutions).map(|term| sum + term)
13135        }),
13136        AtomView::Mul(mul) => mul.into_iter().try_fold(Atom::num(1), |product, factor| {
13137            rubi_kernel_subst(&factor.to_owned(), substitutions).map(|factor| product * factor)
13138        }),
13139        _ => Some(expr.to_owned()),
13140    }
13141}
13142
13143fn rubi_expand_integrand_or_self(expr: &Atom, x: Symbol) -> Atom {
13144    rubi_expand_integrand(expr, x)
13145}
13146
13147fn rubi_match_polynomial_times_larger_linear_power_q(u: &Atom, m: &Atom, x: Symbol) -> bool {
13148    let Some(m_integer) = integer_i64(m) else {
13149        return false;
13150    };
13151    if m_integer <= 0 {
13152        return false;
13153    }
13154
13155    fn linear_integer_power_above_q(factor: &Atom, m_integer: i64, x: Symbol) -> bool {
13156        let AtomView::Pow(power) = factor.as_view() else {
13157            return false;
13158        };
13159        let (base, exponent) = power.get_base_exp();
13160        let Some(power_integer) = integer_i64_view(exponent) else {
13161            return false;
13162        };
13163        power_integer > m_integer
13164            && linear_coefficients(base, x).is_some_and(|(c, d)| freeq!([c, d], x) && !d.is_zero())
13165    }
13166
13167    match u.as_view() {
13168        AtomView::Mul(mul) => mul
13169            .into_iter()
13170            .any(|factor| linear_integer_power_above_q(&factor.to_owned(), m_integer, x)),
13171        _ => linear_integer_power_above_q(u, m_integer, x),
13172    }
13173}
13174
13175fn rubi_rational_function_expand(expr: &Atom, x: Symbol) -> Option<Atom> {
13176    if let Some(expanded) = rubi_rational_function_expand_fractional_power_product(expr, x) {
13177        if expanded != *expr {
13178            return Some(expanded);
13179        }
13180    }
13181
13182    if let Some(expanded) = rubi_expand_integrand_changed(expr, x) {
13183        if expanded != *expr && !rubi_rational_function_expand_exception(expr, x) {
13184            return Some(expanded);
13185        }
13186    }
13187
13188    let rational_factors = rubi_rational_function_factors(expr, x);
13189    let expanded_rational = rubi_expand_integrand(&rational_factors, x);
13190    let nonrational_factors = rubi_nonrational_function_factors(expr, x);
13191    let expanded = if rubi_sum_q(&expanded_rational) {
13192        map_sum_terms(&expanded_rational, |term| term * &nonrational_factors)
13193    } else {
13194        expanded_rational * nonrational_factors
13195    };
13196
13197    (expanded != *expr).then_some(expanded)
13198}
13199
13200fn rubi_rational_function_expand_fractional_power_product(expr: &Atom, x: Symbol) -> Option<Atom> {
13201    let factors = rubi_product_factors(expr);
13202    for (index, factor) in factors.iter().enumerate() {
13203        let AtomView::Pow(power) = factor.as_view() else {
13204            continue;
13205        };
13206        let base = power.get_base().to_owned();
13207        let exponent = power.get_exp().to_owned();
13208        if base == Atom::var(x) || !fractionq!(exponent) {
13209            continue;
13210        }
13211
13212        let rest = product_atoms(
13213            &factors
13214                .iter()
13215                .enumerate()
13216                .filter_map(|(factor_index, factor)| {
13217                    (factor_index != index).then_some(factor.to_owned())
13218                })
13219                .collect::<Vec<_>>(),
13220        );
13221        let expanded_rest = rubi_rational_function_expand(&rest, x).unwrap_or(rest);
13222        return Some(if rubi_sum_q(&expanded_rest) {
13223            map_sum_terms(&expanded_rest, |term| term * factor)
13224        } else {
13225            expanded_rest * factor
13226        });
13227    }
13228
13229    None
13230}
13231
13232fn rubi_rational_function_expand_exception(expr: &Atom, x: Symbol) -> bool {
13233    let Some((numerator, denominator)) = rational_numerator_denominator(expr) else {
13234        return false;
13235    };
13236    let Some((_a, _b, n)) = rubi_constant_plus_monomial_parts(&denominator, x) else {
13237        return false;
13238    };
13239    let Some(n_integer) = integer_i64(&n) else {
13240        return false;
13241    };
13242
13243    let mut monomial_exponent = None;
13244    let mut linear_power = None;
13245    for factor in rubi_product_factors(&numerator) {
13246        if factor == Atom::var(x) {
13247            if monomial_exponent.is_some() {
13248                return false;
13249            }
13250            monomial_exponent = Some(Atom::num(1));
13251            continue;
13252        }
13253
13254        if let AtomView::Pow(power) = factor.as_view() {
13255            let base = power.get_base().to_owned();
13256            let exponent = power.get_exp().to_owned();
13257            if base == Atom::var(x) {
13258                if monomial_exponent.is_some() {
13259                    return false;
13260                }
13261                monomial_exponent = Some(exponent);
13262                continue;
13263            }
13264            if linear_coefficients(base.as_view(), x)
13265                .is_some_and(|(c, d)| !d.is_zero() && freeq!([c, d, exponent.to_owned()], x))
13266            {
13267                if linear_power.is_some() {
13268                    return false;
13269                }
13270                linear_power = Some(());
13271                continue;
13272            }
13273        }
13274
13275        if linear_coefficients(factor.as_view(), x)
13276            .is_some_and(|(c, d)| !d.is_zero() && freeq!([c, d], x))
13277        {
13278            if linear_power.is_some() {
13279                return false;
13280            }
13281            linear_power = Some(());
13282            continue;
13283        }
13284
13285        if !is_free_of(&factor, x) {
13286            return false;
13287        }
13288    }
13289
13290    monomial_exponent
13291        .as_ref()
13292        .and_then(integer_i64)
13293        .is_some_and(|m_integer| m_integer == n_integer - 1)
13294        && linear_power.is_some()
13295}
13296
13297fn rubi_rational_function_q(expr: &Atom, x: Symbol) -> bool {
13298    rubi_structural_rational_function_q(expr.as_view(), x)
13299}
13300
13301fn rubi_rational_function_exponents<T: AtomCore>(expr: T, x: Symbol) -> Option<(i64, i64)> {
13302    let normalized = expr.as_atom_view().together();
13303    if poly_q(&normalized, x) {
13304        return Some((rubi_expon(normalized.as_view(), x)?, 0));
13305    }
13306
13307    let (numerator, denominator) = rational_numerator_denominator(&normalized)?;
13308    if !poly_q(&numerator, x) || !poly_q(&denominator, x) {
13309        return None;
13310    }
13311
13312    Some((
13313        rubi_expon(numerator.as_view(), x)?,
13314        rubi_expon(denominator.as_view(), x)?,
13315    ))
13316}
13317
13318fn rubi_match_optional_multiplier_affine_integer_power(expr: &Atom, affine: &Atom) -> bool {
13319    fn integer_power_of_affine(factor: &Atom, affine: &Atom) -> bool {
13320        if factor == affine {
13321            return true;
13322        }
13323
13324        let AtomView::Pow(power) = factor.as_view() else {
13325            return false;
13326        };
13327        let (base, exponent) = power.get_base_exp();
13328        base.to_owned() == *affine && integer_q(&exponent.to_owned())
13329    }
13330
13331    rubi_split_product(|factor| integer_power_of_affine(factor, affine), expr).is_some()
13332}
13333
13334fn rubi_match_optional_scaled_trig_power_same_angle_q(u: &Atom, angle: &Atom, x: Symbol) -> bool {
13335    if eqq!(u, 1) {
13336        return true;
13337    }
13338
13339    let (base, exponent) = match u.as_view() {
13340        AtomView::Pow(power) => {
13341            let (base, exponent) = power.get_base_exp();
13342            (base.to_owned(), exponent.to_owned())
13343        }
13344        _ => (u.to_owned(), Atom::num(1)),
13345    };
13346    if !is_free_of(&exponent, x) {
13347        return false;
13348    }
13349
13350    rubi_split_product(|factor| rubi_trig_same_angle_q(factor, angle), &base)
13351        .is_some_and(|(_, rest)| is_free_of(&rest, x))
13352}
13353
13354fn rubi_trig_same_angle_q(expr: &Atom, angle: &Atom) -> bool {
13355    match expr.as_view() {
13356        AtomView::Fun(function) if function.get_nargs() == 1 => {
13357            let symbol = function.get_symbol();
13358            rubi_inert_or_builtin_trig_symbol_q(symbol)
13359                && function
13360                    .into_iter()
13361                    .next()
13362                    .is_some_and(|argument| argument.to_owned() == *angle)
13363        }
13364        _ => false,
13365    }
13366}
13367
13368fn rubi_deactivate_trig(expr: &Atom, x: Symbol) -> Atom {
13369    if let Some(deactivated) = rubi_deactivate_trig_linear_trig_power_product(expr, x) {
13370        return rubi_fix_and_unify_inert_trig_function(&deactivated, x);
13371    }
13372
13373    if let Some(deactivated) = rubi_deactivate_trig_rules()
13374        .iter()
13375        .find_map(|rule| matcher_helper_rule(expr, x, rule, rubi_symbols().rubi_deactivate_trig))
13376        .filter(|deactivated| !rubi_inert_trig_free_q(deactivated))
13377    {
13378        return rubi_fix_and_unify_inert_trig_function(&deactivated, x);
13379    }
13380
13381    rubi_fix_and_unify_inert_trig_function(&rubi_deactivate_trig_aux(expr, x), x)
13382}
13383
13384fn rubi_fix_and_unify_inert_trig_function(expr: &Atom, x: Symbol) -> Atom {
13385    let fixed = rubi_fix_inert_trig_function(expr, x);
13386    rubi_unify_inert_trig_function(&fixed, x)
13387}
13388
13389fn rubi_deactivate_trig_linear_trig_power_product(expr: &Atom, x: Symbol) -> Option<Atom> {
13390    let factors: Vec<Atom> = match expr.as_view() {
13391        AtomView::Mul(mul) => mul.into_iter().map(|factor| factor.to_owned()).collect(),
13392        _ => vec![expr.to_owned()],
13393    }
13394    .into_iter()
13395    .map(|factor| rubi_mathematica_trig_quotient(&factor).unwrap_or(factor))
13396    .collect();
13397
13398    for (index, factor) in factors.iter().enumerate() {
13399        let Some((a, b, trig, e, f, n)) = rubi_trig_binomial_power_parts(factor, x) else {
13400            continue;
13401        };
13402        let mut remaining = Atom::num(1);
13403        for (factor_index, other_factor) in factors.iter().enumerate() {
13404            if factor_index != index {
13405                remaining *= other_factor.to_owned();
13406            }
13407        }
13408        if remaining.is_one() {
13409            continue;
13410        }
13411        let linear_power = rubi_optional_linear_power_factor(&remaining, x)?;
13412        if !is_free_of((&a, &b, &e, &f, &n), x) {
13413            continue;
13414        }
13415
13416        let argument = e + f * Atom::var(x);
13417        let deactivated_trig = rubi_deactivate_trig(&trig.call((argument,)), x);
13418        return Some(linear_power * (a + b * deactivated_trig).pow(n));
13419    }
13420
13421    None
13422}
13423
13424fn rubi_trig_binomial_power_parts(
13425    expr: &Atom,
13426    x: Symbol,
13427) -> Option<(Atom, Atom, Symbol, Atom, Atom, Atom)> {
13428    let (base, n) = match expr.as_view() {
13429        AtomView::Pow(power) => (power.get_base().to_owned(), power.get_exp().to_owned()),
13430        _ => (expr.to_owned(), Atom::num(1)),
13431    };
13432    let mut a = Atom::num(0);
13433    let mut trig_term = None;
13434    for term in rubi_sum_terms(&base) {
13435        if let Some(parts) = rubi_scaled_linear_trig_call(&term, x) {
13436            if trig_term.is_some() {
13437                return None;
13438            }
13439            trig_term = Some(parts);
13440        } else {
13441            if !is_free_of(&term, x) {
13442                return None;
13443            }
13444            a += term;
13445        }
13446    }
13447    let (b, trig, e, f) = trig_term?;
13448    Some((a, b, trig, e, f, n))
13449}
13450
13451fn rubi_scaled_linear_trig_call(expr: &Atom, x: Symbol) -> Option<(Atom, Symbol, Atom, Atom)> {
13452    let (coefficient, call) = match expr.as_view() {
13453        AtomView::Mul(mul) => {
13454            let mut coefficient = Atom::num(1);
13455            let mut call = None;
13456            for factor in mul {
13457                let factor = factor.to_owned();
13458                if rubi_linear_trig_call_parts(&factor, x).is_some() {
13459                    if call.is_some() {
13460                        return None;
13461                    }
13462                    call = Some(factor);
13463                } else {
13464                    coefficient *= factor;
13465                }
13466            }
13467            (coefficient, call?)
13468        }
13469        _ => (Atom::num(1), expr.to_owned()),
13470    };
13471    let (trig, e, f) = rubi_linear_trig_call_parts(&call, x)?;
13472    if !is_free_of(&coefficient, x) {
13473        return None;
13474    }
13475    Some((coefficient, trig, e, f))
13476}
13477
13478fn rubi_linear_trig_call_parts(expr: &Atom, x: Symbol) -> Option<(Symbol, Atom, Atom)> {
13479    let AtomView::Fun(function) = expr.as_view() else {
13480        return None;
13481    };
13482    if function.get_nargs() != 1 {
13483        return None;
13484    }
13485    let symbol = function.get_symbol();
13486    if !rubi_builtin_trig_symbol_q(symbol) && !rubi_hyperbolic_function_symbol(symbol) {
13487        return None;
13488    }
13489    let argument = function.get(0).to_owned();
13490    let (e, f) = linear_coefficients(argument.as_view(), x)?;
13491    if f.is_zero() {
13492        return None;
13493    }
13494    Some((symbol, e, f))
13495}
13496
13497fn rubi_optional_linear_power_factor(expr: &Atom, x: Symbol) -> Option<Atom> {
13498    if expr == &Atom::num(1) {
13499        return Some(Atom::num(1));
13500    }
13501    let (base, m) = match expr.as_view() {
13502        AtomView::Pow(power) => (power.get_base().to_owned(), power.get_exp().to_owned()),
13503        _ => (expr.to_owned(), Atom::num(1)),
13504    };
13505    if !is_free_of(&m, x) {
13506        return None;
13507    }
13508    let (c, d) = linear_coefficients(base.as_view(), x)?;
13509    if d.is_zero() || !is_free_of((&c, &d), x) {
13510        return None;
13511    }
13512    Some((c + d * Atom::var(x)).pow(m))
13513}
13514
13515fn rubi_deactivate_trig_aux(expr: &Atom, x: Symbol) -> Atom {
13516    if let Some(canonical) = rubi_mathematica_trig_quotient(expr)
13517        && canonical != *expr
13518    {
13519        return rubi_deactivate_trig_aux(&canonical, x);
13520    }
13521    if let Some(canonical) = rubi_mathematica_hyperbolic_quotient(expr)
13522        && canonical != *expr
13523    {
13524        return rubi_deactivate_trig_aux(&canonical, x);
13525    }
13526
13527    match expr.as_view() {
13528        AtomView::Fun(function)
13529            if function.get_nargs() == 1 && rubi_builtin_trig_symbol_q(function.get_symbol()) =>
13530        {
13531            let argument = function.get(0).to_owned();
13532            if rubi_linear_q(argument.as_view(), x) {
13533                let inert_symbol = rubi_inert_symbol_for_builtin_trig(function.get_symbol())
13534                    .expect("built-in trig guard should map to an inert symbol");
13535                return rubi_reduce_inert_trig(inert_symbol, rubi_expand_to_sum(&argument, x));
13536            }
13537            let argument = rubi_deactivate_trig_aux(&argument, x);
13538            rubi_inert_trig_call(function.get_symbol(), argument)
13539        }
13540        AtomView::Fun(function)
13541            if function.get_nargs() == 1
13542                && rubi_hyperbolic_function_symbol(function.get_symbol()) =>
13543        {
13544            let argument = function.get(0).to_owned();
13545            if rubi_linear_q(argument.as_view(), x) {
13546                let i = Atom::i();
13547                let argument = rubi_expand_to_sum(&(i.to_owned() * argument), x);
13548                return match function.get_symbol().get_stripped_ascii_name() {
13549                    Some("sinh") => -i * rubi_reduce_inert_trig(rubi_symbols().inert_sin, argument),
13550                    Some("cosh") => rubi_reduce_inert_trig(rubi_symbols().inert_cos, argument),
13551                    Some("tanh") => -i * rubi_reduce_inert_trig(rubi_symbols().inert_tan, argument),
13552                    Some("coth") => i * rubi_reduce_inert_trig(rubi_symbols().inert_cot, argument),
13553                    Some("sech") => rubi_reduce_inert_trig(rubi_symbols().inert_sec, argument),
13554                    Some("csch") => i * rubi_reduce_inert_trig(rubi_symbols().inert_csc, argument),
13555                    _ => unreachable!("guard only allows known hyperbolic functions"),
13556                };
13557            }
13558            let argument = rubi_deactivate_trig_aux(&argument, x);
13559            function.get_symbol().call((argument,))
13560        }
13561        AtomView::Fun(function) => {
13562            let args: Vec<_> = function
13563                .into_iter()
13564                .map(|argument| rubi_deactivate_trig_aux(&argument.to_owned(), x))
13565                .collect();
13566            function.get_symbol().call_args(args)
13567        }
13568        AtomView::Add(add) => add
13569            .into_iter()
13570            .map(|term| rubi_deactivate_trig_aux(&term.to_owned(), x))
13571            .fold(Atom::num(0), |sum, term| sum + term),
13572        AtomView::Mul(mul) => {
13573            if let Some(canonical) = rubi_mathematica_trig_quotient(expr) {
13574                return rubi_deactivate_trig_aux(&canonical, x);
13575            }
13576            if let Some(canonical) = rubi_mathematica_hyperbolic_quotient(expr) {
13577                return rubi_deactivate_trig_aux(&canonical, x);
13578            }
13579            mul.into_iter()
13580                .map(|factor| {
13581                    let factor = factor.to_owned();
13582                    if let Some(canonical) = rubi_mathematica_trig_quotient(&factor) {
13583                        rubi_deactivate_trig_aux(&canonical, x)
13584                    } else if let Some(canonical) = rubi_mathematica_hyperbolic_quotient(&factor) {
13585                        rubi_deactivate_trig_aux(&canonical, x)
13586                    } else {
13587                        rubi_deactivate_trig_aux(&factor, x)
13588                    }
13589                })
13590                .fold(Atom::num(1), |product, factor| product * factor)
13591        }
13592        AtomView::Pow(power) => rubi_deactivate_trig_aux(&power.get_base().to_owned(), x)
13593            .pow(rubi_deactivate_trig_aux(&power.get_exp().to_owned(), x)),
13594        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
13595    }
13596}
13597
13598fn rubi_mathematica_trig_quotient(expr: &Atom) -> Option<Atom> {
13599    if let Some((family, argument, exponent)) = rubi_reciprocal_builtin_trig_power(expr)
13600        && exponent > 0
13601    {
13602        return rubi_reciprocal_trig_family_call(family, argument).map(|base| base.pow(exponent));
13603    }
13604
13605    let AtomView::Mul(mul) = expr.as_view() else {
13606        return None;
13607    };
13608    let factors: Vec<_> = mul.into_iter().map(|factor| factor.to_owned()).collect();
13609    if factors.len() < 2 {
13610        return None;
13611    }
13612
13613    let canonical_factors = factors
13614        .iter()
13615        .map(|factor| rubi_mathematica_trig_quotient(factor).unwrap_or_else(|| factor.to_owned()))
13616        .collect::<Vec<_>>();
13617    if canonical_factors != factors {
13618        let canonical = product_atoms(&canonical_factors);
13619        return Some(rubi_mathematica_trig_quotient(&canonical).unwrap_or(canonical));
13620    }
13621
13622    for left_index in 0..factors.len() {
13623        let Some((left_family, left_argument, left_exponent)) =
13624            rubi_positive_builtin_trig_power(&factors[left_index])
13625        else {
13626            continue;
13627        };
13628        for right_index in (left_index + 1)..factors.len() {
13629            let Some((right_family, right_argument, right_exponent)) =
13630                rubi_positive_builtin_trig_power(&factors[right_index])
13631            else {
13632                continue;
13633            };
13634            if left_argument != right_argument
13635                || !matches!(
13636                    (left_family, right_family),
13637                    (RubiTrigFamily::Sin, RubiTrigFamily::Csc)
13638                        | (RubiTrigFamily::Csc, RubiTrigFamily::Sin)
13639                        | (RubiTrigFamily::Cos, RubiTrigFamily::Sec)
13640                        | (RubiTrigFamily::Sec, RubiTrigFamily::Cos)
13641                        | (RubiTrigFamily::Tan, RubiTrigFamily::Cot)
13642                        | (RubiTrigFamily::Cot, RubiTrigFamily::Tan)
13643                )
13644            {
13645                continue;
13646            }
13647
13648            let cancellation_exponent = left_exponent.min(right_exponent);
13649            let mut canonical_factors = Vec::with_capacity(factors.len());
13650            for (index, factor) in factors.iter().enumerate() {
13651                if index != left_index && index != right_index {
13652                    canonical_factors.push(factor.to_owned());
13653                }
13654            }
13655            if left_exponent > cancellation_exponent {
13656                canonical_factors.push(
13657                    rubi_trig_family_call(left_family, left_argument.to_owned())
13658                        .pow(left_exponent - cancellation_exponent),
13659                );
13660            }
13661            if right_exponent > cancellation_exponent {
13662                canonical_factors.push(
13663                    rubi_trig_family_call(right_family, right_argument)
13664                        .pow(right_exponent - cancellation_exponent),
13665                );
13666            }
13667            return Some(product_atoms(&canonical_factors));
13668        }
13669    }
13670
13671    for left_index in 0..factors.len() {
13672        let Some((left_family, left_argument, left_exponent)) =
13673            rubi_positive_builtin_trig_power(&factors[left_index])
13674        else {
13675            continue;
13676        };
13677        for right_index in (left_index + 1)..factors.len() {
13678            let Some((right_family, right_argument, right_exponent)) =
13679                rubi_positive_builtin_trig_power(&factors[right_index])
13680            else {
13681                continue;
13682            };
13683            if left_argument != right_argument {
13684                continue;
13685            }
13686
13687            let replacement = match (left_family, right_family) {
13688                (RubiTrigFamily::Cos, RubiTrigFamily::Tan)
13689                | (RubiTrigFamily::Tan, RubiTrigFamily::Cos) => left_argument.sin(),
13690                (RubiTrigFamily::Sin, RubiTrigFamily::Cot)
13691                | (RubiTrigFamily::Cot, RubiTrigFamily::Sin) => left_argument.cos(),
13692                (RubiTrigFamily::Sin, RubiTrigFamily::Sec)
13693                | (RubiTrigFamily::Sec, RubiTrigFamily::Sin) => left_argument.tan(),
13694                (RubiTrigFamily::Cos, RubiTrigFamily::Csc)
13695                | (RubiTrigFamily::Csc, RubiTrigFamily::Cos) => left_argument.cot(),
13696                (RubiTrigFamily::Tan, RubiTrigFamily::Csc)
13697                | (RubiTrigFamily::Csc, RubiTrigFamily::Tan) => left_argument.sec(),
13698                (RubiTrigFamily::Cot, RubiTrigFamily::Sec)
13699                | (RubiTrigFamily::Sec, RubiTrigFamily::Cot) => left_argument.csc(),
13700                _ => continue,
13701            };
13702
13703            let cancellation_exponent = left_exponent.min(right_exponent);
13704            let mut canonical_factors = Vec::with_capacity(factors.len() + 1);
13705            for (index, factor) in factors.iter().enumerate() {
13706                if index != left_index && index != right_index {
13707                    canonical_factors.push(factor.to_owned());
13708                }
13709            }
13710            if left_exponent > cancellation_exponent {
13711                canonical_factors.push(
13712                    rubi_trig_family_call(left_family, left_argument.to_owned())
13713                        .pow(left_exponent - cancellation_exponent),
13714                );
13715            }
13716            if right_exponent > cancellation_exponent {
13717                canonical_factors.push(
13718                    rubi_trig_family_call(right_family, right_argument)
13719                        .pow(right_exponent - cancellation_exponent),
13720                );
13721            }
13722            canonical_factors.push(replacement.pow(cancellation_exponent));
13723            let canonical = product_atoms(&canonical_factors);
13724            if canonical != *expr {
13725                return Some(canonical);
13726            }
13727        }
13728    }
13729
13730    for numerator_index in 0..factors.len() {
13731        let Some((numerator_family, numerator_argument, numerator_exponent)) =
13732            rubi_positive_builtin_trig_power(&factors[numerator_index])
13733        else {
13734            continue;
13735        };
13736
13737        for denominator_index in 0..factors.len() {
13738            if denominator_index == numerator_index {
13739                continue;
13740            }
13741            let Some((denominator_family, denominator_argument, denominator_exponent)) =
13742                rubi_reciprocal_builtin_trig_power(&factors[denominator_index])
13743            else {
13744                continue;
13745            };
13746            if denominator_exponent <= 0 || numerator_argument != denominator_argument {
13747                continue;
13748            }
13749
13750            let quotient = match (numerator_family, denominator_family) {
13751                (RubiTrigFamily::Cos, RubiTrigFamily::Sin) => rubi_mathematica_trig_quotient_power(
13752                    numerator_argument.to_owned(),
13753                    numerator_exponent,
13754                    RubiTrigFamily::Cos,
13755                    RubiTrigFamily::Cot,
13756                    RubiTrigFamily::Csc,
13757                    denominator_exponent,
13758                ),
13759                (RubiTrigFamily::Sin, RubiTrigFamily::Cos) => rubi_mathematica_trig_quotient_power(
13760                    numerator_argument.to_owned(),
13761                    numerator_exponent,
13762                    RubiTrigFamily::Sin,
13763                    RubiTrigFamily::Tan,
13764                    RubiTrigFamily::Sec,
13765                    denominator_exponent,
13766                ),
13767                (RubiTrigFamily::Cot, RubiTrigFamily::Csc) => rubi_mathematica_trig_quotient_power(
13768                    numerator_argument.to_owned(),
13769                    numerator_exponent,
13770                    RubiTrigFamily::Cot,
13771                    RubiTrigFamily::Cos,
13772                    RubiTrigFamily::Sin,
13773                    denominator_exponent,
13774                ),
13775                (RubiTrigFamily::Tan, RubiTrigFamily::Sec) => rubi_mathematica_trig_quotient_power(
13776                    numerator_argument.to_owned(),
13777                    numerator_exponent,
13778                    RubiTrigFamily::Tan,
13779                    RubiTrigFamily::Sin,
13780                    RubiTrigFamily::Cos,
13781                    denominator_exponent,
13782                ),
13783                (RubiTrigFamily::Sin, RubiTrigFamily::Tan) => rubi_mathematica_trig_quotient_power(
13784                    numerator_argument.to_owned(),
13785                    numerator_exponent,
13786                    RubiTrigFamily::Sin,
13787                    RubiTrigFamily::Cos,
13788                    RubiTrigFamily::Cot,
13789                    denominator_exponent,
13790                ),
13791                (RubiTrigFamily::Cos, RubiTrigFamily::Cot) => rubi_mathematica_trig_quotient_power(
13792                    numerator_argument.to_owned(),
13793                    numerator_exponent,
13794                    RubiTrigFamily::Cos,
13795                    RubiTrigFamily::Sin,
13796                    RubiTrigFamily::Tan,
13797                    denominator_exponent,
13798                ),
13799                (RubiTrigFamily::Tan, RubiTrigFamily::Sin) => rubi_mathematica_trig_quotient_power(
13800                    numerator_argument.to_owned(),
13801                    numerator_exponent,
13802                    RubiTrigFamily::Tan,
13803                    RubiTrigFamily::Sec,
13804                    RubiTrigFamily::Csc,
13805                    denominator_exponent,
13806                ),
13807                (RubiTrigFamily::Cot, RubiTrigFamily::Cos) => rubi_mathematica_trig_quotient_power(
13808                    numerator_argument.to_owned(),
13809                    numerator_exponent,
13810                    RubiTrigFamily::Cot,
13811                    RubiTrigFamily::Csc,
13812                    RubiTrigFamily::Sec,
13813                    denominator_exponent,
13814                ),
13815                (RubiTrigFamily::Sec, RubiTrigFamily::Tan) => rubi_mathematica_trig_quotient_power(
13816                    numerator_argument.to_owned(),
13817                    numerator_exponent,
13818                    RubiTrigFamily::Sec,
13819                    RubiTrigFamily::Csc,
13820                    RubiTrigFamily::Cot,
13821                    denominator_exponent,
13822                ),
13823                (RubiTrigFamily::Csc, RubiTrigFamily::Cot) => rubi_mathematica_trig_quotient_power(
13824                    numerator_argument.to_owned(),
13825                    numerator_exponent,
13826                    RubiTrigFamily::Csc,
13827                    RubiTrigFamily::Sec,
13828                    RubiTrigFamily::Tan,
13829                    denominator_exponent,
13830                ),
13831                _ => continue,
13832            };
13833
13834            let mut canonical_factors = Vec::with_capacity(factors.len() - 1);
13835            for (index, factor) in factors.iter().enumerate() {
13836                if index != numerator_index && index != denominator_index {
13837                    canonical_factors.push(factor.to_owned());
13838                }
13839            }
13840            canonical_factors.push(quotient);
13841            let canonical = product_atoms(&canonical_factors);
13842            if canonical != *expr {
13843                return Some(canonical);
13844            }
13845        }
13846    }
13847
13848    None
13849}
13850
13851fn rubi_positive_builtin_trig_power(expr: &Atom) -> Option<(RubiTrigFamily, Atom, i64)> {
13852    if let Some((symbol, argument)) = rubi_trig_function(expr)
13853        && rubi_builtin_trig_symbol_q(symbol)
13854    {
13855        return Some((rubi_trig_symbol_family(symbol)?, argument, 1));
13856    }
13857
13858    let AtomView::Pow(power) = expr.as_view() else {
13859        return None;
13860    };
13861    let exponent = integer_i64_view(power.get_exp())?;
13862    if exponent <= 0 {
13863        return None;
13864    }
13865    let base = power.get_base().to_owned();
13866    let (symbol, argument) = rubi_trig_function(&base)?;
13867    if !rubi_builtin_trig_symbol_q(symbol) {
13868        return None;
13869    }
13870    Some((rubi_trig_symbol_family(symbol)?, argument, exponent))
13871}
13872
13873fn rubi_mathematica_trig_quotient_power(
13874    argument: Atom,
13875    numerator_exponent: i64,
13876    numerator_family: RubiTrigFamily,
13877    quotient_family: RubiTrigFamily,
13878    reciprocal_family: RubiTrigFamily,
13879    denominator_exponent: i64,
13880) -> Atom {
13881    if numerator_exponent >= denominator_exponent {
13882        rubi_trig_family_call(numerator_family, argument.to_owned())
13883            .pow(numerator_exponent - denominator_exponent)
13884            * rubi_trig_family_call(quotient_family, argument).pow(denominator_exponent)
13885    } else {
13886        rubi_trig_family_call(quotient_family, argument.to_owned()).pow(numerator_exponent)
13887            * rubi_trig_family_call(reciprocal_family, argument)
13888                .pow(denominator_exponent - numerator_exponent)
13889    }
13890}
13891
13892fn rubi_reciprocal_builtin_trig_power(expr: &Atom) -> Option<(RubiTrigFamily, Atom, i64)> {
13893    let AtomView::Pow(power) = expr.as_view() else {
13894        return None;
13895    };
13896    let exponent = integer_i64_view(power.get_exp())?;
13897    if exponent >= 0 {
13898        return None;
13899    }
13900    let base = power.get_base().to_owned();
13901    let (symbol, argument) = rubi_trig_function(&base)?;
13902    if !rubi_builtin_trig_symbol_q(symbol) {
13903        return None;
13904    }
13905    Some((rubi_trig_symbol_family(symbol)?, argument, -exponent))
13906}
13907
13908fn rubi_trig_family_call(family: RubiTrigFamily, argument: Atom) -> Atom {
13909    match family {
13910        RubiTrigFamily::Sin => argument.sin(),
13911        RubiTrigFamily::Cos => argument.cos(),
13912        RubiTrigFamily::Tan => argument.tan(),
13913        RubiTrigFamily::Cot => argument.cot(),
13914        RubiTrigFamily::Sec => argument.sec(),
13915        RubiTrigFamily::Csc => argument.csc(),
13916    }
13917}
13918
13919fn rubi_reciprocal_trig_family_call(family: RubiTrigFamily, argument: Atom) -> Option<Atom> {
13920    match family {
13921        RubiTrigFamily::Sin => Some(argument.csc()),
13922        RubiTrigFamily::Cos => Some(argument.sec()),
13923        RubiTrigFamily::Tan => Some(argument.cot()),
13924        RubiTrigFamily::Cot => Some(argument.tan()),
13925        RubiTrigFamily::Sec => Some(argument.cos()),
13926        RubiTrigFamily::Csc => Some(argument.sin()),
13927    }
13928}
13929
13930fn rubi_mathematica_hyperbolic_quotient(expr: &Atom) -> Option<Atom> {
13931    if let Some((family, argument, exponent)) = rubi_reciprocal_hyperbolic_power(expr) {
13932        return Some(
13933            rubi_hyperbolic_family_call(rubi_reciprocal_hyperbolic_family(family), argument)
13934                .pow(exponent),
13935        );
13936    }
13937
13938    let AtomView::Mul(mul) = expr.as_view() else {
13939        return None;
13940    };
13941    let factors: Vec<_> = mul.into_iter().map(|factor| factor.to_owned()).collect();
13942    if factors.len() < 2 {
13943        return None;
13944    }
13945
13946    let canonical_factors = factors
13947        .iter()
13948        .map(|factor| {
13949            rubi_mathematica_hyperbolic_quotient(factor).unwrap_or_else(|| factor.to_owned())
13950        })
13951        .collect::<Vec<_>>();
13952    if canonical_factors != factors {
13953        let canonical = product_atoms(&canonical_factors);
13954        return Some(rubi_mathematica_hyperbolic_quotient(&canonical).unwrap_or(canonical));
13955    }
13956
13957    for power_index in 0..factors.len() {
13958        let AtomView::Pow(power) = factors[power_index].as_view() else {
13959            continue;
13960        };
13961        let Some((power_symbol, power_argument)) =
13962            rubi_hyperbolic_function(&power.get_base().to_owned())
13963        else {
13964            continue;
13965        };
13966        let Some(power_family) = rubi_hyperbolic_symbol_family(power_symbol) else {
13967            continue;
13968        };
13969        let power_exponent = power.get_exp().to_owned();
13970
13971        for bare_index in 0..factors.len() {
13972            if bare_index == power_index {
13973                continue;
13974            }
13975            let Some((bare_symbol, bare_argument)) = rubi_hyperbolic_function(&factors[bare_index])
13976            else {
13977                continue;
13978            };
13979            if bare_argument != power_argument {
13980                continue;
13981            }
13982            let Some(replacement_family) = rubi_hyperbolic_product_replacement_family(
13983                power_family,
13984                rubi_hyperbolic_symbol_family(bare_symbol)?,
13985            ) else {
13986                continue;
13987            };
13988
13989            let mut canonical_factors = Vec::with_capacity(factors.len());
13990            for (index, factor) in factors.iter().enumerate() {
13991                if index != power_index && index != bare_index {
13992                    canonical_factors.push(factor.to_owned());
13993                }
13994            }
13995            canonical_factors.push(
13996                rubi_hyperbolic_family_call(power_family, power_argument.to_owned())
13997                    .pow(power_exponent.to_owned() - 1),
13998            );
13999            if let Some(family) = replacement_family {
14000                canonical_factors.push(rubi_hyperbolic_family_call(
14001                    family,
14002                    power_argument.to_owned(),
14003                ));
14004            }
14005            let canonical = product_atoms(&canonical_factors);
14006            if canonical != *expr {
14007                return Some(rubi_mathematica_hyperbolic_quotient(&canonical).unwrap_or(canonical));
14008            }
14009        }
14010    }
14011
14012    for left_index in 0..factors.len() {
14013        let Some((left_family, left_argument, left_exponent)) =
14014            rubi_positive_hyperbolic_power(&factors[left_index])
14015        else {
14016            continue;
14017        };
14018        for right_index in (left_index + 1)..factors.len() {
14019            let Some((right_family, right_argument, right_exponent)) =
14020                rubi_positive_hyperbolic_power(&factors[right_index])
14021            else {
14022                continue;
14023            };
14024            if left_argument != right_argument {
14025                continue;
14026            }
14027
14028            let Some(replacement_family) =
14029                rubi_hyperbolic_product_replacement_family(left_family, right_family)
14030            else {
14031                continue;
14032            };
14033
14034            let cancellation_exponent = left_exponent.min(right_exponent);
14035            let mut canonical_factors = Vec::with_capacity(factors.len() + 1);
14036            for (index, factor) in factors.iter().enumerate() {
14037                if index != left_index && index != right_index {
14038                    canonical_factors.push(factor.to_owned());
14039                }
14040            }
14041            if left_exponent > cancellation_exponent {
14042                canonical_factors.push(
14043                    rubi_hyperbolic_family_call(left_family, left_argument.to_owned())
14044                        .pow(left_exponent - cancellation_exponent),
14045                );
14046            }
14047            if right_exponent > cancellation_exponent {
14048                canonical_factors.push(
14049                    rubi_hyperbolic_family_call(right_family, right_argument.to_owned())
14050                        .pow(right_exponent - cancellation_exponent),
14051                );
14052            }
14053            if let Some(family) = replacement_family {
14054                canonical_factors.push(
14055                    rubi_hyperbolic_family_call(family, right_argument).pow(cancellation_exponent),
14056                );
14057            }
14058            let canonical = product_atoms(&canonical_factors);
14059            if canonical != *expr {
14060                return Some(rubi_mathematica_hyperbolic_quotient(&canonical).unwrap_or(canonical));
14061            }
14062        }
14063    }
14064
14065    None
14066}
14067
14068fn rubi_hyperbolic_product_replacement_family(
14069    left: RubiTrigFamily,
14070    right: RubiTrigFamily,
14071) -> Option<Option<RubiTrigFamily>> {
14072    match (left, right) {
14073        (RubiTrigFamily::Sin, RubiTrigFamily::Csc)
14074        | (RubiTrigFamily::Csc, RubiTrigFamily::Sin)
14075        | (RubiTrigFamily::Cos, RubiTrigFamily::Sec)
14076        | (RubiTrigFamily::Sec, RubiTrigFamily::Cos)
14077        | (RubiTrigFamily::Tan, RubiTrigFamily::Cot)
14078        | (RubiTrigFamily::Cot, RubiTrigFamily::Tan) => Some(None),
14079        (RubiTrigFamily::Cos, RubiTrigFamily::Tan) | (RubiTrigFamily::Tan, RubiTrigFamily::Cos) => {
14080            Some(Some(RubiTrigFamily::Sin))
14081        }
14082        (RubiTrigFamily::Sin, RubiTrigFamily::Cot) | (RubiTrigFamily::Cot, RubiTrigFamily::Sin) => {
14083            Some(Some(RubiTrigFamily::Cos))
14084        }
14085        (RubiTrigFamily::Sin, RubiTrigFamily::Sec) | (RubiTrigFamily::Sec, RubiTrigFamily::Sin) => {
14086            Some(Some(RubiTrigFamily::Tan))
14087        }
14088        (RubiTrigFamily::Cos, RubiTrigFamily::Csc) | (RubiTrigFamily::Csc, RubiTrigFamily::Cos) => {
14089            Some(Some(RubiTrigFamily::Cot))
14090        }
14091        (RubiTrigFamily::Tan, RubiTrigFamily::Csc) | (RubiTrigFamily::Csc, RubiTrigFamily::Tan) => {
14092            Some(Some(RubiTrigFamily::Sec))
14093        }
14094        (RubiTrigFamily::Cot, RubiTrigFamily::Sec) | (RubiTrigFamily::Sec, RubiTrigFamily::Cot) => {
14095            Some(Some(RubiTrigFamily::Csc))
14096        }
14097        _ => None,
14098    }
14099}
14100
14101fn rubi_positive_hyperbolic_power(expr: &Atom) -> Option<(RubiTrigFamily, Atom, i64)> {
14102    if let Some((symbol, argument)) = rubi_hyperbolic_function(expr) {
14103        return Some((rubi_hyperbolic_symbol_family(symbol)?, argument, 1));
14104    }
14105
14106    let AtomView::Pow(power) = expr.as_view() else {
14107        return None;
14108    };
14109    let exponent = integer_i64_view(power.get_exp())?;
14110    if exponent <= 0 {
14111        return None;
14112    }
14113    let (symbol, argument) = rubi_hyperbolic_function(&power.get_base().to_owned())?;
14114    Some((rubi_hyperbolic_symbol_family(symbol)?, argument, exponent))
14115}
14116
14117fn rubi_reciprocal_hyperbolic_power(expr: &Atom) -> Option<(RubiTrigFamily, Atom, i64)> {
14118    let AtomView::Pow(power) = expr.as_view() else {
14119        return None;
14120    };
14121    let exponent = integer_i64_view(power.get_exp())?;
14122    if exponent >= 0 {
14123        return None;
14124    }
14125    let (symbol, argument) = rubi_hyperbolic_call(&power.get_base().to_owned())?;
14126    Some((rubi_hyperbolic_symbol_family(symbol)?, argument, -exponent))
14127}
14128
14129fn rubi_hyperbolic_call(expr: &Atom) -> Option<(Symbol, Atom)> {
14130    rubi_hyperbolic_function(expr)
14131}
14132
14133fn rubi_hyperbolic_symbol_family(symbol: Symbol) -> Option<RubiTrigFamily> {
14134    match symbol.get_stripped_ascii_name()? {
14135        "sinh" => Some(RubiTrigFamily::Sin),
14136        "cosh" => Some(RubiTrigFamily::Cos),
14137        "tanh" => Some(RubiTrigFamily::Tan),
14138        "coth" => Some(RubiTrigFamily::Cot),
14139        "sech" => Some(RubiTrigFamily::Sec),
14140        "csch" => Some(RubiTrigFamily::Csc),
14141        _ => None,
14142    }
14143}
14144
14145fn rubi_hyperbolic_family_call(family: RubiTrigFamily, argument: Atom) -> Atom {
14146    match family {
14147        RubiTrigFamily::Sin => argument.sinh(),
14148        RubiTrigFamily::Cos => argument.cosh(),
14149        RubiTrigFamily::Tan => argument.tanh(),
14150        RubiTrigFamily::Cot => argument.coth(),
14151        RubiTrigFamily::Sec => argument.sech(),
14152        RubiTrigFamily::Csc => argument.csch(),
14153    }
14154}
14155
14156fn rubi_reciprocal_hyperbolic_family(family: RubiTrigFamily) -> RubiTrigFamily {
14157    match family {
14158        RubiTrigFamily::Sin => RubiTrigFamily::Csc,
14159        RubiTrigFamily::Cos => RubiTrigFamily::Sec,
14160        RubiTrigFamily::Tan => RubiTrigFamily::Cot,
14161        RubiTrigFamily::Cot => RubiTrigFamily::Tan,
14162        RubiTrigFamily::Sec => RubiTrigFamily::Cos,
14163        RubiTrigFamily::Csc => RubiTrigFamily::Sin,
14164    }
14165}
14166
14167fn rubi_reduce_inert_trig(func: Symbol, argument: Atom) -> Atom {
14168    let Some((m, u)) = rubi_pi_coefficient_and_rest(&argument) else {
14169        return func.call((argument,));
14170    };
14171    let Some((numerator, denominator)) = rational_number(&m) else {
14172        return func.call((argument,));
14173    };
14174
14175    rubi_reduce_inert_trig_rational(func, numerator, denominator, u)
14176}
14177
14178fn rubi_reduce_inert_trig_rational(
14179    func: Symbol,
14180    numerator: i64,
14181    denominator: i64,
14182    u: Atom,
14183) -> Atom {
14184    let symbols = rubi_symbols();
14185    if numerator < 0 {
14186        if 4 * numerator >= -denominator {
14187            return func.call((rubi_rational_pi_argument(numerator, denominator, u),));
14188        }
14189        return match func {
14190            symbol if symbol == symbols.inert_sin => {
14191                -rubi_reduce_inert_trig_rational(symbols.inert_sin, -numerator, denominator, -u)
14192            }
14193            symbol if symbol == symbols.inert_cos => {
14194                rubi_reduce_inert_trig_rational(symbols.inert_cos, -numerator, denominator, -u)
14195            }
14196            symbol if symbol == symbols.inert_tan => {
14197                -rubi_reduce_inert_trig_rational(symbols.inert_tan, -numerator, denominator, -u)
14198            }
14199            symbol if symbol == symbols.inert_cot => {
14200                -rubi_reduce_inert_trig_rational(symbols.inert_cot, -numerator, denominator, -u)
14201            }
14202            symbol if symbol == symbols.inert_sec => {
14203                rubi_reduce_inert_trig_rational(symbols.inert_sec, -numerator, denominator, -u)
14204            }
14205            symbol if symbol == symbols.inert_csc => {
14206                -rubi_reduce_inert_trig_rational(symbols.inert_csc, -numerator, denominator, -u)
14207            }
14208            _ => func.call((rubi_rational_pi_argument(numerator, denominator, u),)),
14209        };
14210    }
14211
14212    if numerator >= 2 * denominator {
14213        let modulus = 2 * denominator;
14214        let reduced = numerator.rem_euclid(modulus);
14215        return rubi_reduce_inert_trig_rational(func, reduced, denominator, u);
14216    }
14217
14218    if numerator >= denominator {
14219        return match func {
14220            symbol if symbol == symbols.inert_sin => -rubi_reduce_inert_trig_rational(
14221                symbols.inert_sin,
14222                numerator - denominator,
14223                denominator,
14224                u,
14225            ),
14226            symbol if symbol == symbols.inert_cos => -rubi_reduce_inert_trig_rational(
14227                symbols.inert_cos,
14228                numerator - denominator,
14229                denominator,
14230                u,
14231            ),
14232            symbol if symbol == symbols.inert_tan => rubi_reduce_inert_trig_rational(
14233                symbols.inert_tan,
14234                numerator - denominator,
14235                denominator,
14236                u,
14237            ),
14238            symbol if symbol == symbols.inert_cot => rubi_reduce_inert_trig_rational(
14239                symbols.inert_cot,
14240                numerator - denominator,
14241                denominator,
14242                u,
14243            ),
14244            symbol if symbol == symbols.inert_sec => -rubi_reduce_inert_trig_rational(
14245                symbols.inert_sec,
14246                numerator - denominator,
14247                denominator,
14248                u,
14249            ),
14250            symbol if symbol == symbols.inert_csc => -rubi_reduce_inert_trig_rational(
14251                symbols.inert_csc,
14252                numerator - denominator,
14253                denominator,
14254                u,
14255            ),
14256            _ => func.call((rubi_rational_pi_argument(numerator, denominator, u),)),
14257        };
14258    }
14259
14260    if 2 * numerator >= denominator {
14261        return match func {
14262            symbol if symbol == symbols.inert_sin => rubi_reduce_inert_trig_rational(
14263                symbols.inert_cos,
14264                2 * numerator - denominator,
14265                2 * denominator,
14266                u,
14267            ),
14268            symbol if symbol == symbols.inert_cos => -rubi_reduce_inert_trig_rational(
14269                symbols.inert_sin,
14270                2 * numerator - denominator,
14271                2 * denominator,
14272                u,
14273            ),
14274            symbol if symbol == symbols.inert_tan => -rubi_reduce_inert_trig_rational(
14275                symbols.inert_cot,
14276                2 * numerator - denominator,
14277                2 * denominator,
14278                u,
14279            ),
14280            symbol if symbol == symbols.inert_cot => -rubi_reduce_inert_trig_rational(
14281                symbols.inert_tan,
14282                2 * numerator - denominator,
14283                2 * denominator,
14284                u,
14285            ),
14286            symbol if symbol == symbols.inert_sec => -rubi_reduce_inert_trig_rational(
14287                symbols.inert_csc,
14288                2 * numerator - denominator,
14289                2 * denominator,
14290                u,
14291            ),
14292            symbol if symbol == symbols.inert_csc => rubi_reduce_inert_trig_rational(
14293                symbols.inert_sec,
14294                2 * numerator - denominator,
14295                2 * denominator,
14296                u,
14297            ),
14298            _ => func.call((rubi_rational_pi_argument(numerator, denominator, u),)),
14299        };
14300    }
14301
14302    func.call((rubi_rational_pi_argument(numerator, denominator, u),))
14303}
14304
14305fn rubi_rational_pi_argument(numerator: i64, denominator: i64, u: Atom) -> Atom {
14306    let pi_term = Atom::num(numerator) * Atom::var(Symbol::PI) / Atom::num(denominator);
14307    (pi_term + u).expand()
14308}
14309
14310fn rubi_pi_coefficient_and_rest(argument: &Atom) -> Option<(Atom, Atom)> {
14311    let mut coefficient = Atom::num(0);
14312    let mut rest = Atom::num(0);
14313    let mut found_pi = false;
14314    let expanded = argument.expand();
14315
14316    for term in rubi_sum_terms(&expanded) {
14317        if let Some(term_coefficient) = rubi_pi_term_coefficient(&term) {
14318            coefficient = (coefficient + term_coefficient).expand();
14319            found_pi = true;
14320        } else {
14321            rest += term;
14322        }
14323    }
14324
14325    found_pi.then_some((coefficient, rest.expand()))
14326}
14327
14328fn rubi_pi_term_coefficient(term: &Atom) -> Option<Atom> {
14329    let pi = Atom::var(Symbol::PI);
14330    if term == &pi {
14331        return Some(Atom::num(1));
14332    }
14333
14334    match term.as_view() {
14335        AtomView::Mul(mul) => {
14336            let mut coefficient = Atom::num(1);
14337            let mut found_pi = false;
14338            for factor in mul {
14339                let factor = factor.to_owned();
14340                if factor == pi {
14341                    if found_pi {
14342                        return None;
14343                    }
14344                    found_pi = true;
14345                } else if freeq!(factor, Symbol::PI) {
14346                    coefficient *= factor;
14347                } else {
14348                    return None;
14349                }
14350            }
14351            found_pi.then_some(coefficient.expand())
14352        }
14353        _ => None,
14354    }
14355}
14356
14357fn rubi_activate_trig(expr: &Atom) -> Atom {
14358    match expr.as_view() {
14359        AtomView::Fun(function)
14360            if function.get_nargs() == 1 && rubi_inert_trig_symbol_q(function.get_symbol()) =>
14361        {
14362            let argument = rubi_activate_trig(&function.get(0).to_owned());
14363            let reduced = rubi_reduce_inert_trig(function.get_symbol(), argument.to_owned());
14364            if reduced != *expr {
14365                return rubi_activate_trig(&reduced);
14366            }
14367            rubi_mathematica_evaluate_active_trig_call(function.get_symbol(), argument)
14368        }
14369        AtomView::Fun(function)
14370            if function.get_nargs() == 1
14371                && rubi_active_symbol_for_trig(function.get_symbol()).is_some() =>
14372        {
14373            let argument = rubi_activate_trig(&function.get(0).to_owned());
14374            rubi_mathematica_evaluate_active_trig_call(function.get_symbol(), argument)
14375        }
14376        AtomView::Fun(function) => {
14377            let args: Vec<_> = function
14378                .into_iter()
14379                .map(|argument| rubi_activate_trig(&argument.to_owned()))
14380                .collect();
14381            let activated = function.get_symbol().call_args(args);
14382            rubi_mathematica_imaginary_trig_call(&activated).unwrap_or(activated)
14383        }
14384        AtomView::Add(add) => add
14385            .into_iter()
14386            .map(|term| rubi_activate_trig(&term.to_owned()))
14387            .fold(Atom::num(0), |sum, term| sum + term),
14388        AtomView::Mul(mul) => {
14389            let product = mul
14390                .into_iter()
14391                .map(|factor| rubi_activate_trig(&factor.to_owned()))
14392                .fold(Atom::num(1), |product, factor| product * factor);
14393            rubi_mathematica_inverse_imaginary_hyperbolic_product(&product)
14394                .or_else(|| rubi_mathematica_trig_quotient(&product))
14395                .unwrap_or(product)
14396        }
14397        AtomView::Pow(power) => rubi_activate_trig(&power.get_base().to_owned())
14398            .pow(rubi_activate_trig(&power.get_exp().to_owned())),
14399        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
14400    }
14401}
14402
14403fn rubi_reduce_builtin_trig_pi_shifts(expr: &Atom) -> Atom {
14404    rubi_reduce_builtin_trig_pi_shifts_view(expr.as_view())
14405}
14406
14407fn rubi_reduce_builtin_trig_pi_shifts_view(expr: AtomView<'_>) -> Atom {
14408    match expr {
14409        AtomView::Fun(function)
14410            if function.get_nargs() == 1 && rubi_builtin_trig_symbol_q(function.get_symbol()) =>
14411        {
14412            let argument = rubi_reduce_builtin_trig_pi_shifts_view(function.get(0));
14413            let Some(inert_symbol) = rubi_inert_symbol_for_builtin_trig(function.get_symbol())
14414            else {
14415                return rubi_builtin_trig_call(function.get_symbol(), argument);
14416            };
14417            let reduced = rubi_reduce_inert_trig(inert_symbol, argument.to_owned());
14418            let original = inert_symbol.call((&argument,));
14419            if reduced == original {
14420                rubi_mathematica_evaluate_active_trig_call(function.get_symbol(), argument)
14421            } else {
14422                rubi_reduce_builtin_trig_pi_shifts_view(rubi_activate_trig(&reduced).as_view())
14423            }
14424        }
14425        AtomView::Fun(function) => {
14426            let args: Vec<_> = function
14427                .into_iter()
14428                .map(rubi_reduce_builtin_trig_pi_shifts_view)
14429                .collect();
14430            function.get_symbol().call_args(args)
14431        }
14432        AtomView::Add(add) => add
14433            .into_iter()
14434            .map(rubi_reduce_builtin_trig_pi_shifts_view)
14435            .fold(Atom::num(0), |sum, term| sum + term),
14436        AtomView::Mul(mul) => {
14437            let reduced = mul
14438                .into_iter()
14439                .map(rubi_reduce_builtin_trig_pi_shifts_view)
14440                .fold(Atom::num(1), |product, factor| product * factor);
14441            rubi_mathematica_trig_quotient(&reduced)
14442                .or_else(|| rubi_mathematica_hyperbolic_quotient(&reduced))
14443                .unwrap_or(reduced)
14444        }
14445        AtomView::Pow(power) => {
14446            let reduced = rubi_reduce_builtin_trig_pi_shifts_view(power.get_base())
14447                .pow(rubi_reduce_builtin_trig_pi_shifts_view(power.get_exp()));
14448            rubi_mathematica_trig_quotient(&reduced)
14449                .or_else(|| rubi_mathematica_hyperbolic_quotient(&reduced))
14450                .unwrap_or(reduced)
14451        }
14452        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
14453    }
14454}
14455
14456fn rubi_mathematica_evaluate_active_trig_call(symbol: Symbol, argument: Atom) -> Atom {
14457    let activated = rubi_builtin_trig_call(symbol, argument);
14458    rubi_mathematica_shifted_imaginary_trig_call(&activated)
14459        .or_else(|| rubi_mathematica_imaginary_trig_call(&activated))
14460        .or_else(|| rubi_mathematica_trig_parity_call(&activated))
14461        .unwrap_or(activated)
14462}
14463
14464fn rubi_mathematica_trig_parity_call(expr: &Atom) -> Option<Atom> {
14465    let AtomView::Fun(function) = expr.as_view() else {
14466        return None;
14467    };
14468    if function.get_nargs() != 1 || !rubi_builtin_trig_symbol_q(function.get_symbol()) {
14469        return None;
14470    }
14471
14472    let argument = rubi_positive_form_from_structurally_negative(&function.get(0).to_owned())?;
14473    let positive = rubi_builtin_trig_call(function.get_symbol(), argument);
14474    match rubi_trig_symbol_family(function.get_symbol())? {
14475        RubiTrigFamily::Sin | RubiTrigFamily::Tan | RubiTrigFamily::Cot | RubiTrigFamily::Csc => {
14476            Some(-positive)
14477        }
14478        RubiTrigFamily::Cos | RubiTrigFamily::Sec => Some(positive),
14479    }
14480}
14481
14482fn rubi_mathematica_shifted_imaginary_trig_call(expr: &Atom) -> Option<Atom> {
14483    let AtomView::Fun(function) = expr.as_view() else {
14484        return None;
14485    };
14486    if function.get_nargs() != 1 || !rubi_builtin_trig_symbol_q(function.get_symbol()) {
14487        return None;
14488    }
14489
14490    let (pi_coefficient, rest) = rubi_pi_coefficient_and_rest(&function.get(0).to_owned())?;
14491    let (numerator, denominator) = rational_number(&pi_coefficient)?;
14492    if denominator != 2 || numerator.abs() != 1 {
14493        return None;
14494    }
14495
14496    let argument = rubi_explicit_imaginary_argument(&rest)?;
14497    let sign = if numerator > 0 { 1 } else { -1 };
14498    match function.get_symbol().get_stripped_ascii_name() {
14499        Some("sin") => Some(Atom::num(sign) * argument.cosh()),
14500        Some("cos") => Some(-Atom::num(sign) * Atom::i() * argument.sinh()),
14501        Some("tan") => Some(Atom::i() * argument.coth()),
14502        Some("cot") => Some(-Atom::i() * argument.tanh()),
14503        Some("sec") => Some(Atom::num(sign) * Atom::i() * argument.csch()),
14504        Some("csc") => Some(Atom::num(sign) * argument.sech()),
14505        _ => None,
14506    }
14507}
14508
14509fn rubi_mathematica_imaginary_trig_call(expr: &Atom) -> Option<Atom> {
14510    let AtomView::Fun(function) = expr.as_view() else {
14511        return None;
14512    };
14513    if function.get_nargs() != 1 || !rubi_builtin_trig_symbol_q(function.get_symbol()) {
14514        return None;
14515    }
14516    let argument = rubi_explicit_imaginary_argument(&function.get(0).to_owned())?;
14517    match function.get_symbol().get_stripped_ascii_name() {
14518        Some("sin") => Some(Atom::i() * argument.sinh()),
14519        Some("cos") => Some(argument.cosh()),
14520        Some("tan") => Some(Atom::i() * argument.tanh()),
14521        Some("cot") => Some(-Atom::i() * argument.coth()),
14522        Some("sec") => Some(argument.sech()),
14523        Some("csc") => Some(-Atom::i() * argument.csch()),
14524        _ => None,
14525    }
14526}
14527
14528fn rubi_mathematica_inverse_imaginary_hyperbolic_product(expr: &Atom) -> Option<Atom> {
14529    let AtomView::Mul(mul) = expr.as_view() else {
14530        return None;
14531    };
14532
14533    let mut imaginary_coefficient = None;
14534    let mut inverse_argument = None;
14535    let mut rest = Atom::num(1);
14536    for factor in mul {
14537        let factor = factor.to_owned();
14538        if factor == Atom::i() {
14539            if imaginary_coefficient.replace(Atom::num(1)).is_some() {
14540                return None;
14541            }
14542            continue;
14543        }
14544        if factor == -Atom::i() {
14545            if imaginary_coefficient.replace(-Atom::num(1)).is_some() {
14546                return None;
14547            }
14548            continue;
14549        }
14550        if let AtomView::Fun(function) = factor.as_view()
14551            && function.get_nargs() == 1
14552            && function.get_symbol().get_stripped_ascii_name() == Some("atanh")
14553        {
14554            if inverse_argument
14555                .replace(function.get(0).to_owned())
14556                .is_some()
14557            {
14558                return None;
14559            }
14560            continue;
14561        }
14562        rest *= factor;
14563    }
14564
14565    if !eqq!(rest, 1) {
14566        return None;
14567    }
14568
14569    let imaginary_coefficient = imaginary_coefficient?;
14570    let imaginary_argument = rubi_explicit_imaginary_argument(&inverse_argument?)?;
14571    if eqq!(imaginary_coefficient, 1) {
14572        Some(
14573            rubi_positive_form_from_negative_numeric_factor(&imaginary_argument)
14574                .map_or_else(|| -imaginary_argument.atan(), |argument| argument.atan()),
14575        )
14576    } else if eqq!(imaginary_coefficient, -1) {
14577        Some(
14578            rubi_positive_form_from_negative_numeric_factor(&imaginary_argument)
14579                .map_or_else(|| imaginary_argument.atan(), |argument| -argument.atan()),
14580        )
14581    } else {
14582        None
14583    }
14584}
14585
14586fn rubi_positive_form_from_negative_numeric_factor(expr: &Atom) -> Option<Atom> {
14587    let (numeric, nonnumeric) = rubi_split_numeric_factor(expr);
14588    (numeric < 0).then(|| rational_atom(-numeric) * nonnumeric)
14589}
14590
14591fn rubi_positive_form_from_structurally_negative(expr: &Atom) -> Option<Atom> {
14592    if let Some(positive) = rubi_positive_form_from_negative_numeric_factor(expr) {
14593        return Some(positive);
14594    }
14595
14596    let AtomView::Add(add) = expr.as_view() else {
14597        return None;
14598    };
14599    let terms: Vec<_> = add.into_iter().map(|term| term.to_owned()).collect();
14600    (!terms.is_empty() && terms.iter().all(is_negative_term))
14601        .then(|| terms.into_iter().fold(Atom::num(0), |sum, term| sum - term))
14602}
14603
14604fn rubi_explicit_imaginary_argument(argument: &Atom) -> Option<Atom> {
14605    if argument == &Atom::i() {
14606        return Some(Atom::num(1));
14607    }
14608    if argument == &-Atom::i() {
14609        return Some(-Atom::num(1));
14610    }
14611    if let Some(coefficient) = rubi_pure_imaginary_number_coefficient(argument) {
14612        return Some(coefficient);
14613    }
14614
14615    if let AtomView::Add(add) = argument.as_view() {
14616        let mut result = Atom::num(0);
14617        for term in add {
14618            result += rubi_explicit_imaginary_argument(&term.to_owned())?;
14619        }
14620        return Some(result);
14621    }
14622
14623    let AtomView::Mul(mul) = argument.as_view() else {
14624        return None;
14625    };
14626    let factors: Vec<_> = mul.into_iter().map(|factor| factor.to_owned()).collect();
14627    for (index, factor) in factors.iter().enumerate() {
14628        let coefficient = if factor == &Atom::i() {
14629            Atom::num(1)
14630        } else if factor == &-Atom::i() {
14631            -Atom::num(1)
14632        } else if let Some(coefficient) = rubi_pure_imaginary_number_coefficient(factor) {
14633            coefficient
14634        } else {
14635            continue;
14636        };
14637        let mut rest = coefficient;
14638        for (factor_index, other_factor) in factors.iter().enumerate() {
14639            if factor_index != index {
14640                rest *= other_factor.to_owned();
14641            }
14642        }
14643        return Some(rest);
14644    }
14645
14646    None
14647}
14648
14649fn rubi_pure_imaginary_number_coefficient(expr: &Atom) -> Option<Atom> {
14650    let AtomView::Num(number) = expr.as_view() else {
14651        return None;
14652    };
14653    match number.get_coeff_view() {
14654        CoefficientView::Natural(0, 1, numerator, denominator) if numerator != 0 => {
14655            Some(Atom::num(numerator) / Atom::num(denominator))
14656        }
14657        _ => None,
14658    }
14659}
14660
14661fn rubi_fix_inert_trig_function(expr: &Atom, x: Symbol) -> Atom {
14662    rubi_fix_inert_trig_function_rules()
14663        .iter()
14664        .find_map(|rule| {
14665            matcher_helper_rule(expr, x, rule, rubi_symbols().rubi_fix_inert_trig_function)
14666        })
14667        .unwrap_or_else(|| expr.to_owned())
14668}
14669
14670fn rubi_unify_inert_trig_function(expr: &Atom, x: Symbol) -> Atom {
14671    rubi_unify_inert_trig_function_rules()
14672        .iter()
14673        .find_map(|rule| {
14674            matcher_helper_rule(expr, x, rule, rubi_symbols().rubi_unify_inert_trig_function)
14675        })
14676        .unwrap_or_else(|| expr.to_owned())
14677}
14678
14679fn rubi_builtin_trig_symbol_q(symbol: Symbol) -> bool {
14680    rubi_inert_symbol_for_builtin_trig(symbol).is_some()
14681}
14682
14683fn rubi_trig_q(expr: &Atom) -> bool {
14684    match expr.as_view() {
14685        AtomView::Var(variable) => rubi_builtin_trig_symbol_q(variable.get_symbol()),
14686        AtomView::Fun(function) => rubi_builtin_trig_symbol_q(function.get_symbol()),
14687        AtomView::Num(_) | AtomView::Pow(_) | AtomView::Mul(_) | AtomView::Add(_) => false,
14688    }
14689}
14690
14691fn rubi_inert_trig_symbol_q(symbol: Symbol) -> bool {
14692    rubi_builtin_symbol_for_inert_trig(symbol).is_some()
14693}
14694
14695fn rubi_inert_or_builtin_trig_symbol_q(symbol: Symbol) -> bool {
14696    rubi_inert_trig_symbol_q(symbol) || rubi_builtin_trig_symbol_q(symbol)
14697}
14698
14699fn rubi_trig_or_hyperbolic_q(function_head: &Atom) -> bool {
14700    let AtomView::Var(variable) = function_head.as_view() else {
14701        return false;
14702    };
14703    let symbol = variable.get_symbol();
14704    rubi_builtin_trig_symbol_q(symbol) || rubi_hyperbolic_function_symbol(symbol)
14705}
14706
14707fn rubi_inert_trig_q(function_head: &Atom) -> bool {
14708    let AtomView::Var(variable) = function_head.as_view() else {
14709        return false;
14710    };
14711    rubi_inert_trig_symbol_q(variable.get_symbol())
14712}
14713
14714fn rubi_inert_or_builtin_trig_q(function_head: &Atom) -> bool {
14715    let AtomView::Var(variable) = function_head.as_view() else {
14716        return false;
14717    };
14718    rubi_inert_or_builtin_trig_symbol_q(variable.get_symbol())
14719}
14720
14721fn rubi_function_head_member_q(function_head: impl RubiAtomArgument, symbols: &[Symbol]) -> bool {
14722    rubi_function_head_symbol(function_head.rubi_atom_or_view().as_view())
14723        .is_some_and(|symbol| symbols.contains(&symbol))
14724}
14725
14726fn rubi_function_head_symbol<T: AtomCore>(function_head: T) -> Option<Symbol> {
14727    let AtomView::Var(variable) = function_head.as_atom_view() else {
14728        return None;
14729    };
14730    Some(variable.get_symbol())
14731}
14732
14733fn rubi_symbol_name_eq(symbol: Symbol, name: &str) -> bool {
14734    symbol.get_stripped_name().eq_ignore_ascii_case(name)
14735        || symbol
14736            .get_stripped_ascii_name()
14737            .is_some_and(|stripped| stripped.eq_ignore_ascii_case(name))
14738}
14739
14740fn rubi_inert_reciprocal_q(f: &Atom, g: &Atom) -> bool {
14741    let (AtomView::Var(f), AtomView::Var(g)) = (f.as_view(), g.as_view()) else {
14742        return false;
14743    };
14744    let f = f.get_symbol();
14745    let g = g.get_symbol();
14746    let symbols = rubi_symbols();
14747    (f == symbols.inert_sin && g == symbols.inert_csc)
14748        || (f == symbols.inert_cos && g == symbols.inert_sec)
14749        || (f == symbols.inert_tan && g == symbols.inert_cot)
14750}
14751
14752fn rubi_inert_trig_free_q(expr: &Atom) -> bool {
14753    fn recur(expr: AtomView<'_>) -> bool {
14754        match expr {
14755            AtomView::Fun(function) => {
14756                let symbol = function.get_symbol();
14757                if rubi_inert_trig_symbol_q(symbol) {
14758                    return false;
14759                }
14760
14761                function.into_iter().all(recur)
14762            }
14763            AtomView::Add(add) => add.into_iter().all(recur),
14764            AtomView::Mul(mul) => mul.into_iter().all(recur),
14765            AtomView::Pow(power) => recur(power.get_base()) && recur(power.get_exp()),
14766            AtomView::Num(_) | AtomView::Var(_) => true,
14767        }
14768    }
14769
14770    recur(expr.as_view())
14771}
14772
14773fn rubi_trig_simplify_q(expr: &Atom) -> bool {
14774    rubi_activate_trig(expr) != rubi_trig_simplify(expr)
14775}
14776
14777fn rubi_trig_simplify(expr: &Atom) -> Atom {
14778    rubi_activate_trig(&rubi_trig_simplify_recur(expr))
14779}
14780
14781fn rubi_trig_simplify_recur(expr: &Atom) -> Atom {
14782    if atom_q(expr.as_view()) {
14783        return expr.to_owned();
14784    }
14785
14786    let mapped = match expr.as_view() {
14787        AtomView::Add(add) => add
14788            .into_iter()
14789            .map(|term| rubi_trig_simplify_recur(&term.to_owned()))
14790            .fold(Atom::num(0), |sum, term| sum + term),
14791        AtomView::Mul(mul) => mul
14792            .into_iter()
14793            .map(|factor| rubi_trig_simplify_recur(&factor.to_owned()))
14794            .fold(Atom::num(1), |product, factor| product * factor),
14795        AtomView::Pow(power) => {
14796            let direct = rubi_trig_simplify_aux(expr);
14797            if direct != *expr {
14798                return rubi_trig_simplify_recur(&direct);
14799            }
14800            rubi_trig_simplify_recur(&power.get_base().to_owned())
14801                .pow(rubi_trig_simplify_recur(&power.get_exp().to_owned()))
14802        }
14803        AtomView::Fun(function) => {
14804            let args: Vec<_> = function
14805                .into_iter()
14806                .map(|argument| rubi_trig_simplify_recur(&argument.to_owned()))
14807                .collect();
14808            function.get_symbol().call_args(args)
14809        }
14810        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
14811    };
14812
14813    rubi_trig_simplify_aux(&mapped)
14814}
14815
14816fn rubi_trig_simplify_aux(expr: &Atom) -> Atom {
14817    rubi_trig_simplify_square_sum(expr)
14818        .or_else(|| rubi_trig_simplify_integer_sec_tan_pair(expr))
14819        .or_else(|| rubi_trig_simplify_integer_tan_sin_pair(expr))
14820        .or_else(|| rubi_trig_simplify_integer_outer_three_term_pair(expr))
14821        .or_else(|| rubi_trig_simplify_integer_reciprocal_direct_pair(expr))
14822        .or_else(|| rubi_trig_simplify_tangent_double_angle_product(expr))
14823        .unwrap_or_else(|| expr.to_owned())
14824}
14825
14826fn rubi_trig_simplify_tangent_double_angle_product(expr: &Atom) -> Option<Atom> {
14827    // Rubi IntegrationUtilityFunctions.m:
14828    //   TrigSimplifyAux[u_.*(c_.*tan[v_]^n_.*tan[w_]^n_.)^p_.] :=
14829    //     u*((-c+c*sec[w])^n)^p /; IntegerQ[n] && EqQ[w,2*v]
14830    let (coefficient, exponent, _argument, doubled_argument, outer_exponent) =
14831        rubi_tangent_double_angle_product_parts(expr)?;
14832    let simplified_base = (-&coefficient + &coefficient * i_sec(doubled_argument)).pow(exponent);
14833    Some(simplified_base.pow(outer_exponent))
14834}
14835
14836fn rubi_tangent_double_angle_product_parts(expr: &Atom) -> Option<(Atom, Atom, Atom, Atom, Atom)> {
14837    let (base, outer_exponent) = match expr.as_view() {
14838        AtomView::Pow(power) => (power.get_base().to_owned(), power.get_exp().to_owned()),
14839        _ => (expr.to_owned(), Atom::num(1)),
14840    };
14841    let factors = rubi_product_factors(&base);
14842
14843    for first_index in 0..factors.len() {
14844        let Some((first_symbol, first_argument, first_exponent)) =
14845            rubi_trig_power_factor(&factors[first_index])
14846        else {
14847            continue;
14848        };
14849        if rubi_trig_symbol_family(first_symbol) != Some(RubiTrigFamily::Tan)
14850            || !rubi_inert_trig_symbol_q(first_symbol)
14851            || !integerq!(first_exponent)
14852        {
14853            continue;
14854        }
14855
14856        for second_index in (first_index + 1)..factors.len() {
14857            let Some((second_symbol, second_argument, second_exponent)) =
14858                rubi_trig_power_factor(&factors[second_index])
14859            else {
14860                continue;
14861            };
14862            if rubi_trig_symbol_family(second_symbol) != Some(RubiTrigFamily::Tan)
14863                || !rubi_inert_trig_symbol_q(second_symbol)
14864                || !eqq!(second_exponent, first_exponent)
14865            {
14866                continue;
14867            }
14868
14869            let doubled_argument = if eqq!(second_argument, 2 * &first_argument) {
14870                (first_argument, second_argument)
14871            } else if eqq!(first_argument, 2 * &second_argument) {
14872                (second_argument, first_argument)
14873            } else {
14874                continue;
14875            };
14876            let coefficient = factors
14877                .iter()
14878                .enumerate()
14879                .filter_map(|(index, factor)| {
14880                    (index != first_index && index != second_index).then_some(factor.to_owned())
14881                })
14882                .fold(Atom::num(1), |product, factor| product * factor);
14883            return Some((
14884                coefficient,
14885                first_exponent,
14886                doubled_argument.0,
14887                doubled_argument.1,
14888                outer_exponent,
14889            ));
14890        }
14891    }
14892
14893    None
14894}
14895
14896fn rubi_double_angle_tangent_product_match_q(expr: &Atom, x: Symbol) -> bool {
14897    rubi_product_factors(expr).into_iter().any(|factor| {
14898        rubi_tangent_double_angle_product_parts(&factor).is_some_and(
14899            |(coefficient, _exponent, argument, _doubled_argument, outer_exponent)| {
14900                freeq!([coefficient, outer_exponent], x) && rubi_linear_q(argument.as_view(), x)
14901            },
14902        )
14903    })
14904}
14905
14906fn rubi_trig_simplify_square_sum(expr: &Atom) -> Option<Atom> {
14907    let AtomView::Add(add) = expr.as_view() else {
14908        return None;
14909    };
14910    let terms: Vec<Atom> = add.into_iter().map(|term| term.to_owned()).collect();
14911    for i in 0..terms.len() {
14912        let Some((a, function, u)) = rubi_trig_square_term(&terms[i]) else {
14913            continue;
14914        };
14915        for j in 0..terms.len() {
14916            if i == j {
14917                continue;
14918            }
14919            let Some((b, other_function, other_u)) = rubi_trig_square_term(&terms[j]) else {
14920                continue;
14921            };
14922            if u != other_u {
14923                continue;
14924            }
14925            let rest = product_atoms(&[]);
14926            let v = terms
14927                .iter()
14928                .enumerate()
14929                .filter_map(|(index, term)| (index != i && index != j).then_some(term.to_owned()))
14930                .fold(Atom::num(0), |sum, term| sum + term);
14931
14932            let symbols = rubi_symbols();
14933            if function == symbols.inert_cos && other_function == symbols.inert_sin && a == b {
14934                let _ = rest;
14935                return Some(a + v);
14936            }
14937            if function == symbols.inert_sin && other_function == symbols.inert_cos && a == b {
14938                let _ = rest;
14939                return Some(a + v);
14940            }
14941            if function == symbols.inert_sec && other_function == symbols.inert_tan && a == -&b {
14942                let _ = rest;
14943                return Some(a + v);
14944            }
14945            if function == symbols.inert_tan && other_function == symbols.inert_sec && b == -&a {
14946                let _ = rest;
14947                return Some(b + v);
14948            }
14949            if function == symbols.inert_csc && other_function == symbols.inert_cot && a == -&b {
14950                let _ = rest;
14951                return Some(a + v);
14952            }
14953            if function == symbols.inert_cot && other_function == symbols.inert_csc && b == -&a {
14954                let _ = rest;
14955                return Some(b + v);
14956            }
14957        }
14958    }
14959
14960    None
14961}
14962
14963fn rubi_trig_square_term(term: &Atom) -> Option<(Atom, Symbol, Atom)> {
14964    if let Some((coefficient, rest)) =
14965        rubi_split_product(|factor| rubi_trig_square_factor(factor).is_some(), term)
14966    {
14967        let (function, argument) = rubi_trig_square_factor(&coefficient)?;
14968        return Some((rest, function, argument));
14969    }
14970
14971    rubi_trig_square_factor(term).map(|(function, argument)| (Atom::num(1), function, argument))
14972}
14973
14974fn rubi_trig_square_factor(factor: &Atom) -> Option<(Symbol, Atom)> {
14975    let AtomView::Pow(power) = factor.as_view() else {
14976        return None;
14977    };
14978    if !eqq!(power.get_exp(), 2) {
14979        return None;
14980    }
14981    let AtomView::Fun(function) = power.get_base() else {
14982        return None;
14983    };
14984    if function.get_nargs() != 1 {
14985        return None;
14986    }
14987    let symbol = function.get_symbol();
14988    if rubi_inert_trig_symbol_q(symbol) {
14989        Some((symbol, function.get(0).to_owned()))
14990    } else {
14991        None
14992    }
14993}
14994
14995fn rubi_trig_simplify_integer_sec_tan_pair(expr: &Atom) -> Option<Atom> {
14996    let (power_expr, u) = rubi_split_product(|factor| rubi_trig_sum_power(factor).is_some(), expr)?;
14997    let (sum, p) = rubi_trig_sum_power(&power_expr)?;
14998    let AtomView::Add(add) = sum.as_view() else {
14999        return None;
15000    };
15001    let terms: Vec<_> = add.into_iter().map(|term| term.to_owned()).collect();
15002    if terms.len() != 2 {
15003        return None;
15004    }
15005
15006    let (a, first_function, v, n) = rubi_scaled_trig_power_term(&terms[0])?;
15007    let (b, second_function, v2, n2) = rubi_scaled_trig_power_term(&terms[1])?;
15008    if v != v2 || !eqq!(&n - &n2, 0) || !integersq!([n, p]) {
15009        return None;
15010    }
15011
15012    let first_family = rubi_trig_symbol_family(first_function)?;
15013    let second_family = rubi_trig_symbol_family(second_function)?;
15014    if first_family == RubiTrigFamily::Sec && second_family == RubiTrigFamily::Tan {
15015        return Some(
15016            u * rubi_trig_power_or_reciprocal(v.sec(), v.cos(), &(&n * &p))
15017                * (a + b * v.sin().pow(&n)).pow(&p),
15018        );
15019    }
15020    if first_family == RubiTrigFamily::Tan && second_family == RubiTrigFamily::Sec {
15021        return Some(
15022            u * rubi_trig_power_or_reciprocal(v.sec(), v.cos(), &(&n * &p))
15023                * (b + a * v.sin().pow(&n)).pow(&p),
15024        );
15025    }
15026    if first_family == RubiTrigFamily::Csc && second_family == RubiTrigFamily::Cot {
15027        return Some(
15028            u * rubi_trig_power_or_reciprocal(v.csc(), v.sin(), &(&n * &p))
15029                * (a + b * v.cos().pow(&n)).pow(&p),
15030        );
15031    }
15032    if first_family == RubiTrigFamily::Cot && second_family == RubiTrigFamily::Csc {
15033        return Some(
15034            u * rubi_trig_power_or_reciprocal(v.csc(), v.sin(), &(&n * &p))
15035                * (b + a * v.cos().pow(&n)).pow(&p),
15036        );
15037    }
15038
15039    None
15040}
15041
15042fn rubi_trig_simplify_integer_tan_sin_pair(expr: &Atom) -> Option<Atom> {
15043    let (power_expr, u) = rubi_split_product(|factor| rubi_trig_sum_power(factor).is_some(), expr)?;
15044    let (sum, p) = rubi_trig_sum_power(&power_expr)?;
15045    let AtomView::Add(add) = sum.as_view() else {
15046        return None;
15047    };
15048    let terms: Vec<_> = add.into_iter().map(|term| term.to_owned()).collect();
15049    if terms.len() != 2 {
15050        return None;
15051    }
15052
15053    let (a, first_function, v, n) = rubi_scaled_trig_power_term(&terms[0])?;
15054    let (b, second_function, v2, n2) = rubi_scaled_trig_power_term(&terms[1])?;
15055    if v != v2 || !eqq!(&n - &n2, 0) || !integersq!([n, p]) {
15056        return None;
15057    }
15058
15059    let first_family = rubi_trig_symbol_family(first_function)?;
15060    let second_family = rubi_trig_symbol_family(second_function)?;
15061    if first_family == RubiTrigFamily::Tan && second_family == RubiTrigFamily::Sin {
15062        return Some(
15063            u * rubi_trig_power_or_reciprocal(v.tan(), v.cot(), &(&n * &p))
15064                * (a + b * v.cos().pow(&n)).pow(&p),
15065        );
15066    }
15067    if first_family == RubiTrigFamily::Sin && second_family == RubiTrigFamily::Tan {
15068        return Some(
15069            u * rubi_trig_power_or_reciprocal(v.tan(), v.cot(), &(&n * &p))
15070                * (b + a * v.cos().pow(&n)).pow(&p),
15071        );
15072    }
15073    if first_family == RubiTrigFamily::Cot && second_family == RubiTrigFamily::Cos {
15074        return Some(
15075            u * rubi_trig_power_or_reciprocal(v.cot(), v.tan(), &(&n * &p))
15076                * (a + b * v.sin().pow(&n)).pow(&p),
15077        );
15078    }
15079    if first_family == RubiTrigFamily::Cos && second_family == RubiTrigFamily::Cot {
15080        return Some(
15081            u * rubi_trig_power_or_reciprocal(v.cot(), v.tan(), &(&n * &p))
15082                * (b + a * v.sin().pow(&n)).pow(&p),
15083        );
15084    }
15085
15086    None
15087}
15088
15089fn rubi_trig_simplify_integer_outer_three_term_pair(expr: &Atom) -> Option<Atom> {
15090    let factors = rubi_product_factors(expr);
15091    for outer_index in 0..factors.len() {
15092        let Some((outer_function, v, m)) = rubi_trig_power_factor(&factors[outer_index]) else {
15093            continue;
15094        };
15095        if !rubi_inert_trig_symbol_q(outer_function) {
15096            continue;
15097        }
15098
15099        for sum_index in 0..factors.len() {
15100            if outer_index == sum_index {
15101                continue;
15102            }
15103            let Some((sum, p)) = rubi_trig_sum_power(&factors[sum_index]) else {
15104                continue;
15105            };
15106            let terms = rubi_sum_terms(&sum);
15107
15108            for first_index in 0..terms.len() {
15109                let Some((first_coefficient, first_function, first_v, n)) =
15110                    rubi_scaled_trig_power_term(&terms[first_index])
15111                else {
15112                    continue;
15113                };
15114                if !rubi_inert_trig_symbol_q(first_function) {
15115                    continue;
15116                }
15117
15118                for second_index in 0..terms.len() {
15119                    if first_index == second_index {
15120                        continue;
15121                    }
15122                    let Some((second_coefficient, second_function, second_v, second_n)) =
15123                        rubi_scaled_trig_power_term(&terms[second_index])
15124                    else {
15125                        continue;
15126                    };
15127                    if !rubi_inert_trig_symbol_q(second_function)
15128                        || v != first_v
15129                        || v != second_v
15130                        || !eqq!(&n - &second_n, 0)
15131                        || !integersq!([m.to_owned(), n.to_owned(), p.to_owned()])
15132                    {
15133                        continue;
15134                    }
15135
15136                    let first_family = rubi_trig_symbol_family(first_function)?;
15137                    let second_family = rubi_trig_symbol_family(second_function)?;
15138                    let outer_family = rubi_trig_symbol_family(outer_function)?;
15139                    let (b, c, direct, complement, outer_base, outer_exponent) =
15140                        match (outer_family, first_family, second_family) {
15141                            (RubiTrigFamily::Cos, RubiTrigFamily::Tan, RubiTrigFamily::Sec) => (
15142                                first_coefficient,
15143                                second_coefficient,
15144                                v.sin(),
15145                                v.cos(),
15146                                v.cos(),
15147                                &m - &n * &p,
15148                            ),
15149                            (RubiTrigFamily::Cos, RubiTrigFamily::Sec, RubiTrigFamily::Tan) => (
15150                                second_coefficient,
15151                                first_coefficient,
15152                                v.sin(),
15153                                v.cos(),
15154                                v.cos(),
15155                                &m - &n * &p,
15156                            ),
15157                            (RubiTrigFamily::Sec, RubiTrigFamily::Tan, RubiTrigFamily::Sec) => (
15158                                first_coefficient,
15159                                second_coefficient,
15160                                v.sin(),
15161                                v.cos(),
15162                                v.sec(),
15163                                &m + &n * &p,
15164                            ),
15165                            (RubiTrigFamily::Sec, RubiTrigFamily::Sec, RubiTrigFamily::Tan) => (
15166                                second_coefficient,
15167                                first_coefficient,
15168                                v.sin(),
15169                                v.cos(),
15170                                v.sec(),
15171                                &m + &n * &p,
15172                            ),
15173                            (RubiTrigFamily::Sin, RubiTrigFamily::Cot, RubiTrigFamily::Csc) => (
15174                                first_coefficient,
15175                                second_coefficient,
15176                                v.cos(),
15177                                v.sin(),
15178                                v.sin(),
15179                                &m - &n * &p,
15180                            ),
15181                            (RubiTrigFamily::Sin, RubiTrigFamily::Csc, RubiTrigFamily::Cot) => (
15182                                second_coefficient,
15183                                first_coefficient,
15184                                v.cos(),
15185                                v.sin(),
15186                                v.sin(),
15187                                &m - &n * &p,
15188                            ),
15189                            (RubiTrigFamily::Csc, RubiTrigFamily::Cot, RubiTrigFamily::Csc) => (
15190                                first_coefficient,
15191                                second_coefficient,
15192                                v.cos(),
15193                                v.sin(),
15194                                v.to_owned().csc(),
15195                                &m + &n * &p,
15196                            ),
15197                            (RubiTrigFamily::Csc, RubiTrigFamily::Csc, RubiTrigFamily::Cot) => (
15198                                second_coefficient,
15199                                first_coefficient,
15200                                v.cos(),
15201                                v.sin(),
15202                                v.to_owned().csc(),
15203                                &m + &n * &p,
15204                            ),
15205                            _ => continue,
15206                        };
15207
15208                    let a = rubi_sum_except_two(&terms, first_index, second_index);
15209                    let u = factors
15210                        .iter()
15211                        .enumerate()
15212                        .filter_map(|(index, factor)| {
15213                            (index != outer_index && index != sum_index)
15214                                .then_some(factor.to_owned())
15215                        })
15216                        .fold(Atom::num(1), |product, factor| product * factor);
15217                    return Some(
15218                        u * outer_base.pow(outer_exponent)
15219                            * (c + b * direct.pow(&n) + a * complement.pow(&n)).pow(&p),
15220                    );
15221                }
15222            }
15223        }
15224    }
15225
15226    None
15227}
15228
15229fn rubi_trig_simplify_integer_reciprocal_direct_pair(expr: &Atom) -> Option<Atom> {
15230    let (power_expr, u) = rubi_split_product(|factor| rubi_trig_sum_power(factor).is_some(), expr)?;
15231    let (sum, p) = rubi_trig_sum_power(&power_expr)?;
15232    let AtomView::Add(add) = sum.as_view() else {
15233        return None;
15234    };
15235    let terms: Vec<_> = add.into_iter().map(|term| term.to_owned()).collect();
15236    if terms.len() != 2 {
15237        return None;
15238    }
15239
15240    for (reciprocal_index, direct_index) in [(0, 1), (1, 0)] {
15241        let (a, reciprocal_function, v, m) = rubi_scaled_trig_power_term(&terms[reciprocal_index])?;
15242        let (b, direct_function, v2, n) = rubi_scaled_trig_power_term(&terms[direct_index])?;
15243        if v != v2 || !integersq!([m.to_owned(), n.to_owned()]) {
15244            continue;
15245        }
15246
15247        let families = (
15248            rubi_trig_symbol_family(reciprocal_function)?,
15249            rubi_trig_symbol_family(direct_function)?,
15250        );
15251        let (direct, complement) = match families {
15252            (RubiTrigFamily::Csc, RubiTrigFamily::Sin) => (v.sin(), v.cos()),
15253            (RubiTrigFamily::Sec, RubiTrigFamily::Cos) => (v.cos(), v.sin()),
15254            _ => continue,
15255        };
15256
15257        let numerator = if eqq!(&m + &n - 2, 0) && eqq!(&a + &b, 0) {
15258            a * complement.pow(2)
15259        } else {
15260            a + b * direct.pow(&m + &n)
15261        };
15262        return Some(u * (numerator / direct.pow(&m)).pow(&p));
15263    }
15264
15265    None
15266}
15267
15268fn rubi_trig_power_or_reciprocal(base: Atom, reciprocal: Atom, exponent: &Atom) -> Atom {
15269    match integer_i64(exponent) {
15270        Some(power) if power < 0 => reciprocal.pow(-power),
15271        _ => base.pow(exponent),
15272    }
15273}
15274
15275fn rubi_trig_sum_power(expr: &Atom) -> Option<(Atom, Atom)> {
15276    match expr.as_view() {
15277        AtomView::Pow(power) => {
15278            let base = power.get_base().to_owned();
15279            matches!(base.as_view(), AtomView::Add(_)).then_some((base, power.get_exp().to_owned()))
15280        }
15281        AtomView::Add(_) => Some((expr.to_owned(), Atom::num(1))),
15282        _ => None,
15283    }
15284}
15285
15286fn rubi_power_of_inert_trig_sum_q(expr: &Atom, func: Symbol, x: Symbol) -> bool {
15287    rubi_power_of_inert_trig_binomial_sum_q(expr, func, x)
15288        || rubi_power_of_inert_trig_trinomial_sum_q(expr, func, x)
15289}
15290
15291fn rubi_power_of_inert_trig_binomial_sum_q(expr: &Atom, func: Symbol, x: Symbol) -> bool {
15292    let (base, p) = rubi_optional_power(expr);
15293    let Some((a, b, c, _w, n)) = rubi_match_inert_trig_binomial_sum(&base, func) else {
15294        return false;
15295    };
15296
15297    freeq!([a, b, c, n, p], x) && !(eqq!(a, 0) && (integerq!(p) || eqq!(n, 1)))
15298}
15299
15300fn rubi_power_of_inert_trig_trinomial_sum_q(expr: &Atom, func: Symbol, x: Symbol) -> bool {
15301    let (base, n) = rubi_optional_power(expr);
15302    let Some((a, b, c, d, _w, p, q)) = rubi_match_inert_trig_trinomial_sum(&base, func) else {
15303        return false;
15304    };
15305
15306    freeq!([a, b, c, d, n, p, q], x)
15307}
15308
15309fn rubi_optional_power(expr: &Atom) -> (Atom, Atom) {
15310    match expr.as_view() {
15311        AtomView::Pow(power) => (power.get_base().to_owned(), power.get_exp().to_owned()),
15312        _ => (expr.to_owned(), Atom::num(1)),
15313    }
15314}
15315
15316fn rubi_match_inert_trig_binomial_sum(
15317    expr: &Atom,
15318    func: Symbol,
15319) -> Option<(Atom, Atom, Atom, Atom, Atom)> {
15320    let terms = rubi_sum_terms(expr);
15321    for index in 0..terms.len() {
15322        let Some((b, c, w, n)) = rubi_scaled_inert_trig_power_term(&terms[index], func) else {
15323            continue;
15324        };
15325        let a = rubi_sum_except(&terms, index);
15326        return Some((a, b, c, w, n));
15327    }
15328    None
15329}
15330
15331fn rubi_match_inert_trig_trinomial_sum(
15332    expr: &Atom,
15333    func: Symbol,
15334) -> Option<(Atom, Atom, Atom, Atom, Atom, Atom, Atom)> {
15335    let terms = rubi_sum_terms(expr);
15336    for first in 0..terms.len() {
15337        let Some((b, d, w, p)) = rubi_scaled_inert_trig_power_term(&terms[first], func) else {
15338            continue;
15339        };
15340        for second in 0..terms.len() {
15341            if first == second {
15342                continue;
15343            }
15344            let Some((c, d2, w2, q)) = rubi_scaled_inert_trig_power_term(&terms[second], func)
15345            else {
15346                continue;
15347            };
15348            if d == d2 && w == w2 {
15349                let a = rubi_sum_except_two(&terms, first, second);
15350                return Some((a, b, c, d, w, p, q));
15351            }
15352        }
15353    }
15354    None
15355}
15356
15357fn rubi_scaled_inert_trig_power_term(
15358    term: &Atom,
15359    func: Symbol,
15360) -> Option<(Atom, Atom, Atom, Atom)> {
15361    if let Some((matched, rest)) = rubi_split_product(
15362        |factor| rubi_inert_trig_power_base(factor, func).is_some(),
15363        term,
15364    ) {
15365        let (c, w, n) = rubi_inert_trig_power_base(&matched, func)?;
15366        Some((rest, c, w, n))
15367    } else {
15368        rubi_inert_trig_power_base(term, func).map(|(c, w, n)| (Atom::num(1), c, w, n))
15369    }
15370}
15371
15372fn rubi_inert_trig_power_base(expr: &Atom, func: Symbol) -> Option<(Atom, Atom, Atom)> {
15373    match expr.as_view() {
15374        AtomView::Pow(power) => {
15375            let (c, w) = rubi_scaled_inert_trig_call(&power.get_base().to_owned(), func)?;
15376            Some((c, w, power.get_exp().to_owned()))
15377        }
15378        _ => {
15379            let (c, w) = rubi_scaled_inert_trig_call(expr, func)?;
15380            Some((c, w, Atom::num(1)))
15381        }
15382    }
15383}
15384
15385fn rubi_scaled_inert_trig_call(expr: &Atom, func: Symbol) -> Option<(Atom, Atom)> {
15386    if let Some((matched, rest)) = rubi_split_product(
15387        |factor| rubi_inert_trig_call_argument(factor, func).is_some(),
15388        expr,
15389    ) {
15390        Some((rest, rubi_inert_trig_call_argument(&matched, func)?))
15391    } else {
15392        rubi_inert_trig_call_argument(expr, func).map(|argument| (Atom::num(1), argument))
15393    }
15394}
15395
15396fn rubi_inert_trig_call_argument(expr: &Atom, func: Symbol) -> Option<Atom> {
15397    let AtomView::Fun(function) = expr.as_view() else {
15398        return None;
15399    };
15400    if function.get_symbol() == func && function.get_nargs() == 1 {
15401        Some(function.get(0).to_owned())
15402    } else {
15403        None
15404    }
15405}
15406
15407fn rubi_sum_terms(expr: &Atom) -> Vec<Atom> {
15408    match expr.as_view() {
15409        AtomView::Add(add) => add.into_iter().map(|term| term.to_owned()).collect(),
15410        _ => vec![expr.to_owned()],
15411    }
15412}
15413
15414fn rubi_sum_except(terms: &[Atom], skip: usize) -> Atom {
15415    terms
15416        .iter()
15417        .enumerate()
15418        .filter_map(|(index, term)| (index != skip).then_some(term.to_owned()))
15419        .fold(Atom::num(0), |sum, term| sum + term)
15420}
15421
15422fn rubi_sum_except_two(terms: &[Atom], skip1: usize, skip2: usize) -> Atom {
15423    terms
15424        .iter()
15425        .enumerate()
15426        .filter_map(|(index, term)| (index != skip1 && index != skip2).then_some(term.to_owned()))
15427        .fold(Atom::num(0), |sum, term| sum + term)
15428}
15429
15430fn rubi_scaled_trig_power_term(term: &Atom) -> Option<(Atom, Symbol, Atom, Atom)> {
15431    if let Some((matched, rest)) =
15432        rubi_split_product(|factor| rubi_trig_power_factor(factor).is_some(), term)
15433    {
15434        let (function, argument, exponent) = rubi_trig_power_factor(&matched)?;
15435        Some((rest, function, argument, exponent))
15436    } else {
15437        rubi_trig_power_factor(term)
15438            .map(|(function, argument, exponent)| (Atom::num(1), function, argument, exponent))
15439    }
15440}
15441
15442fn rubi_trig_power_factor(factor: &Atom) -> Option<(Symbol, Atom, Atom)> {
15443    match factor.as_view() {
15444        AtomView::Fun(function) if function.get_nargs() == 1 => {
15445            let symbol = function.get_symbol();
15446            if rubi_trig_function_symbol(symbol) {
15447                Some((symbol, function.get(0).to_owned(), Atom::num(1)))
15448            } else {
15449                None
15450            }
15451        }
15452        AtomView::Pow(power) => {
15453            let base = power.get_base().to_owned();
15454            let AtomView::Fun(function) = base.as_view() else {
15455                return None;
15456            };
15457            let symbol = function.get_symbol();
15458            if function.get_nargs() == 1 && rubi_trig_function_symbol(symbol) {
15459                Some((
15460                    symbol,
15461                    function.get(0).to_owned(),
15462                    power.get_exp().to_owned(),
15463                ))
15464            } else {
15465                None
15466            }
15467        }
15468        _ => None,
15469    }
15470}
15471
15472fn rubi_try_pure_tan_subst(u: &Atom, x: Symbol) -> bool {
15473    !rubi_inverse_tan_family_linear_wrapper_q(u, x)
15474}
15475
15476fn rubi_inverse_tan_family_linear_wrapper_q(u: &Atom, x: Symbol) -> bool {
15477    let AtomView::Fun(function) = u.as_view() else {
15478        return false;
15479    };
15480    if function.get_nargs() != 1 {
15481        return false;
15482    }
15483
15484    let function_symbol = function.get_symbol();
15485    if function_symbol != symbol!("atan")
15486        && function_symbol != symbol!("acot")
15487        && function_symbol != symbol!("atanh")
15488        && function_symbol != symbol!("acoth")
15489    {
15490        return false;
15491    }
15492
15493    function
15494        .into_iter()
15495        .next()
15496        .is_some_and(|argument| rubi_optional_scaled_tan_family_linear_q(&argument.to_owned(), x))
15497}
15498
15499fn rubi_optional_scaled_tan_family_linear_q(u: &Atom, x: Symbol) -> bool {
15500    if rubi_affine_tan_family_linear_q(u, x) {
15501        return true;
15502    }
15503
15504    let AtomView::Mul(mul) = u.as_view() else {
15505        return false;
15506    };
15507    let nonfree_factors: Vec<Atom> = mul
15508        .into_iter()
15509        .filter_map(|factor| {
15510            let factor = factor.to_owned();
15511            (!is_free_of(&factor, x)).then_some(factor)
15512        })
15513        .collect();
15514    !nonfree_factors.is_empty()
15515        && rubi_affine_tan_family_linear_q(&product_atoms(&nonfree_factors), x)
15516}
15517
15518fn rubi_affine_tan_family_linear_q(u: &Atom, x: Symbol) -> bool {
15519    if rubi_tan_family_linear_term_q(u, x) {
15520        return true;
15521    }
15522
15523    let AtomView::Add(add) = u.as_view() else {
15524        return false;
15525    };
15526    let mut tan_term_seen = false;
15527    for term in add {
15528        let term = term.to_owned();
15529        if is_free_of(&term, x) {
15530            continue;
15531        }
15532        if tan_term_seen || !rubi_tan_family_linear_term_q(&term, x) {
15533            return false;
15534        }
15535        tan_term_seen = true;
15536    }
15537
15538    tan_term_seen
15539}
15540
15541fn rubi_tan_family_linear_term_q(u: &Atom, x: Symbol) -> bool {
15542    if rubi_tan_family_linear_call_q(u, x) {
15543        return true;
15544    }
15545
15546    rubi_split_product(|factor| rubi_tan_family_linear_call_q(factor, x), u)
15547        .is_some_and(|(_, rest)| is_free_of(&rest, x))
15548}
15549
15550fn rubi_tan_family_linear_call_q(u: &Atom, x: Symbol) -> bool {
15551    let AtomView::Fun(function) = u.as_view() else {
15552        return false;
15553    };
15554    if function.get_nargs() != 1 {
15555        return false;
15556    }
15557
15558    let function_symbol = function.get_symbol();
15559    let symbols = rubi_symbols();
15560    if function_symbol != symbolica::transcendental::tan()
15561        && function_symbol != symbolica::transcendental::cot()
15562        && function_symbol != symbols.inert_tan
15563        && function_symbol != symbols.inert_cot
15564        && function_symbol != symbol!("tanh")
15565        && function_symbol != symbol!("coth")
15566    {
15567        return false;
15568    }
15569
15570    function
15571        .into_iter()
15572        .next()
15573        .is_some_and(|argument| rubi_linear_q(argument, x))
15574}
15575
15576fn rubi_function_of_trig(u: &Atom, x: Symbol) -> Option<Atom> {
15577    rubi_function_of_trig_recur(&rubi_activate_trig(u), None, x)?
15578}
15579
15580fn rubi_function_of_trig_of_linear_q(u: &Atom, x: Symbol) -> bool {
15581    rubi_linear_trig_power_product_q(u, x)
15582        || (rubi_function_of_trig_recur(u, None, x).flatten().is_some()
15583            && rubi_algebraic_trig_function_q(u, x))
15584}
15585
15586fn rubi_linear_trig_power_product_q(expr: &Atom, x: Symbol) -> bool {
15587    let factors: Vec<Atom> = match expr.as_view() {
15588        AtomView::Mul(mul) => mul.into_iter().map(|factor| factor.to_owned()).collect(),
15589        _ => vec![expr.to_owned()],
15590    }
15591    .into_iter()
15592    .map(|factor| rubi_mathematica_trig_quotient(&factor).unwrap_or(factor))
15593    .collect();
15594
15595    for (index, factor) in factors.iter().enumerate() {
15596        let Some((a, b, _trig, e, f, n)) = rubi_trig_binomial_power_parts(factor, x) else {
15597            continue;
15598        };
15599        let mut remaining = Atom::num(1);
15600        for (factor_index, other_factor) in factors.iter().enumerate() {
15601            if factor_index != index {
15602                remaining *= other_factor.to_owned();
15603            }
15604        }
15605        if remaining.is_one() {
15606            continue;
15607        }
15608        if rubi_optional_linear_power_factor(&remaining, x).is_some()
15609            && is_free_of((&a, &b, &e, &f, &n), x)
15610        {
15611            return true;
15612        }
15613    }
15614
15615    false
15616}
15617
15618fn rubi_algebraic_trig_function_q(u: &Atom, x: Symbol) -> bool {
15619    if atom_q(u.as_view()) {
15620        return true;
15621    }
15622
15623    if rubi_trig_or_hyperbolic_linear_argument(u, x).is_some() {
15624        return true;
15625    }
15626
15627    match u.as_view() {
15628        AtomView::Pow(power) => {
15629            is_free_of(&power.get_exp().to_owned(), x)
15630                && rubi_algebraic_trig_function_q(&power.get_base().to_owned(), x)
15631        }
15632        AtomView::Mul(_) | AtomView::Add(_) => rubi_children(u.as_view())
15633            .into_iter()
15634            .all(|child| rubi_algebraic_trig_function_q(&child, x)),
15635        _ => false,
15636    }
15637}
15638
15639fn rubi_function_of_trig_recur(u: &Atom, v: Option<Atom>, x: Symbol) -> Option<Option<Atom>> {
15640    if atom_q(u.as_view()) {
15641        return (u != &Atom::var(x)).then_some(v);
15642    }
15643
15644    if let Some(argument) = rubi_trig_or_hyperbolic_linear_argument(u, x) {
15645        return match v {
15646            None => Some(Some(argument)),
15647            Some(existing) => {
15648                rubi_commensurate_linear_trig_argument(&existing, &argument, x).map(Some)
15649            }
15650        };
15651    }
15652
15653    if matches!(u.as_view(), AtomView::Fun(function) if rubi_calculus_function_symbol(function.get_symbol()) && !rubi_inert_or_builtin_trig_symbol_q(function.get_symbol()) && !rubi_hyperbolic_function_symbol(function.get_symbol()))
15654    {
15655        return None;
15656    }
15657
15658    let mut w = v;
15659    for child in rubi_children(u.as_view()) {
15660        w = rubi_function_of_trig_recur(&child, w, x)?;
15661    }
15662    Some(w)
15663}
15664
15665fn rubi_trig_or_hyperbolic_linear_argument(u: &Atom, x: Symbol) -> Option<Atom> {
15666    let AtomView::Fun(function) = u.as_view() else {
15667        return None;
15668    };
15669    if function.get_nargs() != 1 {
15670        return None;
15671    }
15672
15673    let function_symbol = function.get_symbol();
15674    let argument = function.into_iter().next()?.to_owned();
15675    if !rubi_linear_q(argument.as_view(), x) {
15676        return None;
15677    }
15678
15679    if rubi_builtin_trig_symbol_q(function_symbol) {
15680        Some(argument)
15681    } else if rubi_hyperbolic_function_symbol(function_symbol) {
15682        Some(Atom::i() * argument)
15683    } else {
15684        None
15685    }
15686}
15687
15688fn rubi_commensurate_linear_trig_argument(v: &Atom, u: &Atom, x: Symbol) -> Option<Atom> {
15689    let a = rubi_coefficient(v, x, 0)?;
15690    let b = rubi_coefficient(v, x, 1)?;
15691    let c = rubi_coefficient(u, x, 0)?;
15692    let d = rubi_coefficient(u, x, 1)?;
15693    if neq!((&a * &d - &b * &c).expand(), 0) {
15694        return None;
15695    }
15696
15697    let quotient = (&b / &d).expand().cancel();
15698    let (numerator, _) = rational_number(&quotient)?;
15699    Some(a / Atom::num(numerator) + b * Atom::var(x) / Atom::num(numerator))
15700}
15701
15702fn rubi_trig_function_symbol(symbol: Symbol) -> bool {
15703    rubi_inert_or_builtin_trig_symbol_q(symbol)
15704}
15705
15706fn rubi_hyperbolic_function_symbol(symbol: Symbol) -> bool {
15707    matches!(
15708        symbol.get_stripped_ascii_name(),
15709        Some("sinh" | "cosh" | "tanh" | "coth" | "sech" | "csch")
15710    )
15711}
15712
15713fn rubi_hyperbolic_head_q(function_head: &Atom) -> bool {
15714    matches!(
15715        function_head.as_view(),
15716        AtomView::Var(variable) if rubi_hyperbolic_function_symbol(variable.get_symbol())
15717    )
15718}
15719
15720fn rubi_derivative(
15721    order: impl RubiAtomArgument,
15722    function_head: impl RubiAtomArgument,
15723    argument: impl RubiAtomArgument,
15724) -> Atom {
15725    let order = order.into_rubi_atom();
15726    let function_head = function_head.into_rubi_atom();
15727    let argument = argument.into_rubi_atom();
15728    if order.is_zero() {
15729        let AtomView::Var(function_head) = function_head.as_view() else {
15730            panic!("Rubi derivative function head must be a symbol");
15731        };
15732        return function_head.get_symbol().call(argument);
15733    }
15734    Symbol::DERIVATIVE.call((order, function_head, argument))
15735}
15736
15737fn rubi_subst_function_power_primitive(
15738    a: &Atom,
15739    b: &Atom,
15740    function_head: Atom,
15741    c: &Atom,
15742    n: &Atom,
15743    substitution: Atom,
15744) -> Atom {
15745    let function_head = rubi_function_head_symbol(&function_head).unwrap();
15746    let substitution_guard =
15747        fresh_substitution_symbol().expect("Rubi substitution depth should remain bounded");
15748    let sub = substitution_guard.symbol();
15749    let sub_atom = Atom::var(sub);
15750    let integrand = (a + b * function_head.call(c * &sub_atom)).pow(n) / &sub_atom;
15751    let primitive = rubi_rhs_int(&integrand, sub);
15752    rubi_subst(&primitive, sub, substitution)
15753}
15754
15755fn rubi_subst_integral(
15756    substitution_guard: &FreshSubstitutionSymbol,
15757    integrand: Atom,
15758    substitution: Atom,
15759) -> Option<Atom> {
15760    let sub = substitution_guard.symbol();
15761    let primitive = integrate_internal(integrand.as_view(), sub)?;
15762    Some(rubi_subst(&primitive, sub, substitution))
15763}
15764
15765fn rubi_subst_for_simplify_integrand_integral(base: &Atom, expr: &Atom) -> Atom {
15766    let substitution_guard =
15767        fresh_substitution_symbol().expect("Rubi substitution depth should remain bounded");
15768    let sub = substitution_guard.symbol();
15769    let transformed = rubi_subst_for(expr, base, sub);
15770    let integrand = rubi_simplify_integrand(&transformed, sub);
15771    let primitive = rubi_rhs_int(&integrand, sub);
15772    rubi_subst(&primitive, sub, base.to_owned())
15773}
15774
15775fn rubi_slope(expr: &Atom, x: Symbol) -> Atom {
15776    rubi_simp(&expr.derivative(x), x)
15777}
15778
15779fn rubi_piecewise_linear_q(expr: &Atom, x: Symbol) -> bool {
15780    let slope = rubi_slope(expr, x);
15781    !slope.is_zero() && freeq!(slope, x)
15782}
15783
15784fn rubi_piecewise_linear_pair_q(u: &Atom, v: &Atom, x: Symbol) -> bool {
15785    rubi_piecewise_linear_q(u, x) && rubi_piecewise_linear_q(v, x)
15786}
15787
15788fn rubi_piecewise_linear_pair_data(u: &Atom, v: &Atom, x: Symbol) -> (Atom, Atom, Atom) {
15789    let a = rubi_slope(u, x);
15790    let b = rubi_slope(v, x);
15791    let det = &b * u - &a * v;
15792    (a, b, det)
15793}
15794
15795fn rubi_subst_power(expr: &Atom, x: Symbol, n: i64) -> Atom {
15796    match expr.as_view() {
15797        AtomView::Var(variable) if variable.get_symbol() == x => Atom::var(x).pow(n),
15798        AtomView::Pow(power) if power.get_base() == Atom::var(x) => {
15799            let exponent = power.get_exp().to_owned();
15800            if freeq!(exponent, x) {
15801                Atom::var(x).pow(Atom::num(n) * exponent)
15802            } else {
15803                let base = rubi_subst_power(&power.get_base().to_owned(), x, n);
15804                let exponent = rubi_subst_power(&power.get_exp().to_owned(), x, n);
15805                base.pow(exponent)
15806            }
15807        }
15808        AtomView::Pow(power) => {
15809            let base = rubi_subst_power(&power.get_base().to_owned(), x, n);
15810            let exponent = rubi_subst_power(&power.get_exp().to_owned(), x, n);
15811            base.pow(exponent)
15812        }
15813        AtomView::Mul(mul) => mul
15814            .into_iter()
15815            .map(|factor| rubi_subst_power(&factor.to_owned(), x, n))
15816            .fold(Atom::num(1), |product, factor| product * factor),
15817        AtomView::Add(add) => add
15818            .into_iter()
15819            .map(|term| rubi_subst_power(&term.to_owned(), x, n))
15820            .fold(Atom::num(0), |sum, term| sum + term),
15821        AtomView::Fun(function) => function.get_symbol().call_args(
15822            function
15823                .into_iter()
15824                .map(|argument| rubi_subst_power(&argument.to_owned(), x, n)),
15825        ),
15826        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
15827    }
15828}
15829
15830fn rubi_known_sine_integrand_q(u: &Atom, x: Symbol) -> bool {
15831    let symbols = rubi_symbols();
15832    rubi_known_trig_integrand_q(&[symbols.inert_sin, symbols.inert_cos], u, x)
15833}
15834
15835fn rubi_known_tangent_integrand_q(u: &Atom, x: Symbol) -> bool {
15836    rubi_known_trig_integrand_q(&[rubi_symbols().inert_tan], u, x)
15837}
15838
15839fn rubi_known_cotangent_integrand_q(u: &Atom, x: Symbol) -> bool {
15840    rubi_known_trig_integrand_q(&[rubi_symbols().inert_cot], u, x)
15841}
15842
15843fn rubi_known_secant_integrand_q(u: &Atom, x: Symbol) -> bool {
15844    let symbols = rubi_symbols();
15845    rubi_known_trig_integrand_q(&[symbols.inert_sec, symbols.inert_csc], u, x)
15846}
15847
15848fn rubi_known_trig_integrand_q(functions: &[Symbol], u: &Atom, x: Symbol) -> bool {
15849    if u.is_one() {
15850        return true;
15851    }
15852
15853    if rubi_trig_power_shape(u, functions, x, &[1]).is_some()
15854        || rubi_trig_polynomial_shape(u, functions, x, &[2]).is_some()
15855        || rubi_trig_polynomial_shape(u, functions, x, &[1, 2]).is_some()
15856    {
15857        return true;
15858    }
15859
15860    let AtomView::Mul(mul) = u.as_view() else {
15861        return false;
15862    };
15863    let factors: Vec<Atom> = mul.into_iter().map(|factor| factor.to_owned()).collect();
15864    if factors.len() != 2 {
15865        return false;
15866    }
15867
15868    fn product_shape_q(
15869        left: &Atom,
15870        right: &Atom,
15871        functions: &[Symbol],
15872        x: Symbol,
15873        powers: &[i64],
15874    ) -> bool {
15875        let Some((func, angle)) = rubi_trig_power_shape(left, functions, x, &[1]) else {
15876            return false;
15877        };
15878        rubi_trig_polynomial_shape(right, &[func], x, powers)
15879            .is_some_and(|(_, right_angle)| right_angle == angle)
15880    }
15881
15882    product_shape_q(&factors[0], &factors[1], functions, x, &[1])
15883        || product_shape_q(&factors[1], &factors[0], functions, x, &[1])
15884        || product_shape_q(&factors[0], &factors[1], functions, x, &[2])
15885        || product_shape_q(&factors[1], &factors[0], functions, x, &[2])
15886        || product_shape_q(&factors[0], &factors[1], functions, x, &[1, 2])
15887        || product_shape_q(&factors[1], &factors[0], functions, x, &[1, 2])
15888}
15889
15890fn rubi_trig_power_shape(
15891    expr: &Atom,
15892    functions: &[Symbol],
15893    x: Symbol,
15894    powers: &[i64],
15895) -> Option<(Symbol, Atom)> {
15896    match expr.as_view() {
15897        AtomView::Pow(power) => {
15898            let (base, exponent) = power.get_base_exp();
15899            if !is_free_of(exponent, x) {
15900                return None;
15901            }
15902            rubi_trig_polynomial_shape(&base.to_owned(), functions, x, powers)
15903        }
15904        _ => rubi_trig_polynomial_shape(expr, functions, x, powers),
15905    }
15906}
15907
15908fn rubi_trig_polynomial_shape(
15909    expr: &Atom,
15910    functions: &[Symbol],
15911    x: Symbol,
15912    powers: &[i64],
15913) -> Option<(Symbol, Atom)> {
15914    let terms: Vec<Atom> = match expr.as_view() {
15915        AtomView::Add(add) => add.into_iter().map(|term| term.to_owned()).collect(),
15916        _ => vec![expr.to_owned()],
15917    };
15918
15919    let mut seen: Option<(Symbol, Atom)> = None;
15920    for term in terms {
15921        if is_free_of(&term, x) {
15922            continue;
15923        }
15924        let (func, angle, power) = rubi_trig_term_shape(&term, functions, x)?;
15925        if !powers.contains(&power) {
15926            return None;
15927        }
15928        if let Some((seen_func, seen_angle)) = &seen {
15929            if *seen_func != func || *seen_angle != angle {
15930                return None;
15931            }
15932        } else {
15933            seen = Some((func, angle));
15934        }
15935    }
15936
15937    seen
15938}
15939
15940fn rubi_trig_term_shape(
15941    term: &Atom,
15942    functions: &[Symbol],
15943    x: Symbol,
15944) -> Option<(Symbol, Atom, i64)> {
15945    let factors: Vec<Atom> = match term.as_view() {
15946        AtomView::Mul(mul) => mul.into_iter().map(|factor| factor.to_owned()).collect(),
15947        _ => vec![term.to_owned()],
15948    };
15949
15950    let mut trig_part: Option<(Symbol, Atom, i64)> = None;
15951    for factor in factors {
15952        if let Some(shape) = rubi_trig_factor_shape(&factor, functions, x) {
15953            if trig_part.is_some() {
15954                return None;
15955            }
15956            trig_part = Some(shape);
15957        } else if !is_free_of(&factor, x) {
15958            return None;
15959        }
15960    }
15961
15962    trig_part
15963}
15964
15965fn rubi_trig_factor_shape(
15966    factor: &Atom,
15967    functions: &[Symbol],
15968    x: Symbol,
15969) -> Option<(Symbol, Atom, i64)> {
15970    match factor.as_view() {
15971        AtomView::Fun(function)
15972            if function.get_nargs() == 1 && functions.contains(&function.get_symbol()) =>
15973        {
15974            let angle = function.into_iter().next()?.to_owned();
15975            if !rubi_linear_q(angle.as_view(), x) {
15976                return None;
15977            }
15978            Some((function.get_symbol(), angle, 1))
15979        }
15980        AtomView::Pow(power) => {
15981            let (base, exponent) = power.get_base_exp();
15982            let power = integer_i64_view(exponent)?;
15983            let (func, angle, base_power) = rubi_trig_factor_shape(&base.to_owned(), functions, x)?;
15984            Some((func, angle, base_power * power))
15985        }
15986        _ => None,
15987    }
15988}
15989
15990fn rubi_algebraic_function_q(expr: &Atom, x: Symbol, flag: bool) -> bool {
15991    rubi_algebraic_function_q_view(expr.as_view(), x, flag)
15992}
15993
15994fn rubi_algebraic_function_q_view(expr: AtomView<'_>, x: Symbol, flag: bool) -> bool {
15995    if atom_q(expr) || is_free_of(expr, x) {
15996        return true;
15997    }
15998
15999    match expr {
16000        AtomView::Pow(power) => {
16001            let (base, exponent) = power.get_base_exp();
16002            let exponent = exponent.to_owned();
16003            (rational_q(&exponent) || flag && is_free_of(&exponent, x))
16004                && rubi_algebraic_function_q_view(base, x, flag)
16005        }
16006        AtomView::Mul(mul) => mul
16007            .into_iter()
16008            .all(|factor| rubi_algebraic_function_q_view(factor, x, flag)),
16009        AtomView::Add(add) => add
16010            .into_iter()
16011            .all(|term| rubi_algebraic_function_q_view(term, x, flag)),
16012        _ => false,
16013    }
16014}
16015
16016fn rubi_expand_integrand_product(u: &Atom, v: &Atom, x: Symbol) -> Atom {
16017    rubi_expand_integrand_product_changed(u, v, x).unwrap_or_else(|| u * v)
16018}
16019
16020fn rubi_expand_integrand_product_changed(u: &Atom, v: &Atom, x: Symbol) -> Option<Atom> {
16021    if let Some(expanded) = rubi_expand_integrand_log_reciprocal_product(u, v, x) {
16022        return (expanded != u * v).then_some(expanded);
16023    }
16024
16025    let original = u * v;
16026    if let Some(expanded) = rubi_smart_apart_squared_square_root_sum_denominator(&original, x) {
16027        return Some(expanded);
16028    }
16029
16030    let w = rubi_expand_integrand(v, x);
16031    let (free_terms, nonfree_terms) = rubi_free_nonfree_terms(&w, x);
16032    let mut expanded = if free_terms.is_zero() {
16033        Atom::num(0)
16034    } else {
16035        u * free_terms
16036    };
16037
16038    if nonfree_terms.len() == 1 {
16039        expanded += rubi_merge_monomials(&(u * &nonfree_terms[0]), x);
16040    } else {
16041        for term in nonfree_terms {
16042            expanded += rubi_merge_monomials(&(u * term), x);
16043        }
16044    }
16045
16046    if expanded == original {
16047        None
16048    } else {
16049        Some(expanded)
16050    }
16051}
16052
16053fn rubi_expand_integrand_log_reciprocal_product(u: &Atom, v: &Atom, x: Symbol) -> Option<Atom> {
16054    let (log_base, p) = rubi_factor_base_exponent(u);
16055    let (a, b, argument) = rubi_affine_log_parts(&log_base, x)?;
16056    let (c, n) = rubi_monomial_in_variable_parts(&argument, x)?;
16057    if !is_free_of((&a, &b, &c, &n), x) || !igtq!(p, 0) {
16058        return None;
16059    }
16060
16061    let factors = rubi_product_factors(v);
16062    if factors.len() != 2 {
16063        return None;
16064    }
16065    let mut m = None;
16066    let mut linear_power = None;
16067    for factor in factors {
16068        let (base, exponent) = rubi_factor_base_exponent(&factor);
16069        if base == Atom::var(x) {
16070            m = Some(exponent);
16071            continue;
16072        }
16073        if let Some((d, e)) = linear_coefficients(base.as_view(), x) {
16074            if e.is_zero() {
16075                return None;
16076            }
16077            linear_power = Some((d, e, exponent));
16078            continue;
16079        }
16080        return None;
16081    }
16082
16083    let m = m?;
16084    let (d, e, q) = linear_power?;
16085    if !is_free_of((&d, &e), x) || !iltq!(m, 0) || !iltq!(q, 0) {
16086        return None;
16087    }
16088
16089    let expanded_v = rubi_expand_integrand(v, x);
16090    let collected_v = rubi_collect_recip_terms(&expanded_v, x);
16091    Some(rubi_distribute_over_terms(u, &collected_v, x))
16092}
16093
16094fn rubi_monomial_in_variable_parts(expr: &Atom, x: Symbol) -> Option<(Atom, Atom)> {
16095    let mut coefficient = Atom::num(1);
16096    let mut exponent = None;
16097    for factor in rubi_product_factors(expr) {
16098        let (base, factor_exponent) = rubi_factor_base_exponent(&factor);
16099        if base == Atom::var(x) {
16100            if exponent.is_some() {
16101                return None;
16102            }
16103            exponent = Some(factor_exponent);
16104        } else if is_free_of(&factor, x) {
16105            coefficient *= factor;
16106        } else {
16107            return None;
16108        }
16109    }
16110    Some((coefficient, exponent?))
16111}
16112
16113fn rubi_distribute_over_terms(u: &Atom, v: &Atom, x: Symbol) -> Atom {
16114    let (free_terms, nonfree_terms) = rubi_free_nonfree_terms(v, x);
16115    let mut result = u * free_terms;
16116    for term in nonfree_terms {
16117        result += rubi_merge_monomials(&(u * term), x);
16118    }
16119    result
16120}
16121
16122fn rubi_collect_recip_terms(expr: &Atom, x: Symbol) -> Atom {
16123    let terms = rubi_add_terms(expr);
16124    for (x_index, x_term) in terms.iter().enumerate() {
16125        let Some((a, x_denominator)) = rational_numerator_denominator(x_term) else {
16126            continue;
16127        };
16128        if x_denominator != Atom::var(x) || !freeq!(a, x) {
16129            continue;
16130        }
16131
16132        for (linear_index, linear_term) in terms.iter().enumerate() {
16133            if linear_index == x_index {
16134                continue;
16135            }
16136            let Some((b, denominator)) = rational_numerator_denominator(linear_term) else {
16137                continue;
16138            };
16139            let Some((d, e)) = linear_coefficients(denominator.as_view(), x) else {
16140                continue;
16141            };
16142            if d.is_zero() || !is_free_of((&b, &d, &e), x) || !eqq!(&b + &a * &e, 0) {
16143                continue;
16144            }
16145
16146            let rest = terms
16147                .iter()
16148                .enumerate()
16149                .filter_map(|(index, term)| {
16150                    (index != x_index && index != linear_index).then_some(term.to_owned())
16151                })
16152                .fold(Atom::num(0), |sum, term| sum + term);
16153            return rest + a * d / (Atom::var(x) * denominator);
16154        }
16155    }
16156    expr.to_owned()
16157}
16158
16159fn rubi_expand_integrand_product_sum(u: &Atom, v: &Atom, x: Symbol) -> Option<Atom> {
16160    let expanded = rubi_expand_integrand_product(u, v, x);
16161    rubi_sum_q(&expanded).then_some(expanded)
16162}
16163
16164fn rubi_expand_to_sum(expr: &Atom, x: Symbol) -> Atom {
16165    if let Some(terms) = rubi_polynomial_terms(expr, x) {
16166        return rubi_simp(&polynomial_from_terms(&terms, x), x);
16167    }
16168
16169    if rubi_binomial_q(expr.as_view(), x) {
16170        let parts =
16171            rubi_binomial_parts(expr.as_view(), x).expect("BinomialQ should provide BinomialParts");
16172        return parts.a + parts.b * Atom::var(x).pow(parts.n);
16173    }
16174
16175    if rubi_trinomial_q(expr, x) {
16176        let parts =
16177            rubi_trinomial_parts(expr, x).expect("TrinomialQ should provide TrinomialParts");
16178        let x_atom = Atom::var(x);
16179        return parts.a + parts.b * x_atom.pow(parts.n) + parts.c * x_atom.pow(2 * parts.n);
16180    }
16181
16182    if rubi_generalized_binomial_q(expr, x) {
16183        let parts = rubi_generalized_binomial_parts(expr, x)
16184            .expect("GeneralizedBinomialQ should provide GeneralizedBinomialParts");
16185        let x_atom = Atom::var(x);
16186        return parts.a * x_atom.pow(parts.q) + parts.b * x_atom.pow(parts.n);
16187    }
16188
16189    if rubi_generalized_trinomial_q(expr, x) {
16190        let parts = rubi_generalized_trinomial_parts(expr, x)
16191            .expect("GeneralizedTrinomialQ should provide GeneralizedTrinomialParts");
16192        let x_atom = Atom::var(x);
16193        return parts.a * x_atom.pow(parts.q)
16194            + parts.b * x_atom.pow(parts.n)
16195            + parts.c * x_atom.pow(2 * parts.n - parts.q);
16196    }
16197
16198    expr.expand()
16199}
16200
16201fn rubi_expand_trig(expr: &Atom, x: Symbol) -> Atom {
16202    rubi_activate_trig(&rubi_expand_integrand(expr, x))
16203}
16204
16205fn rubi_expand_trig_product(u: impl RubiAtomArgument, v: &Atom, x: Symbol) -> Atom {
16206    let z = rubi_activate_trig(&u.into_rubi_atom());
16207    let w = rubi_expand_trig(v, x);
16208    match w.as_view() {
16209        AtomView::Add(add) => {
16210            let mut sum = Atom::num(0);
16211            for term in add {
16212                sum += &z * term.to_owned();
16213            }
16214            sum
16215        }
16216        _ => z * w,
16217    }
16218}
16219
16220fn rubi_expand_trig_reduce(u: impl RubiAtomArgument, v: &Atom, x: Symbol) -> Atom {
16221    let u = u.into_rubi_atom();
16222    let w = rubi_expand_trig_reduce_one(v, x);
16223    match w.as_view() {
16224        AtomView::Add(add) => add
16225            .into_iter()
16226            .map(|term| &u * term.to_owned())
16227            .fold(Atom::num(0), |sum, term| sum + term),
16228        _ => u * w,
16229    }
16230}
16231
16232fn rubi_expand_trig_to_exp(u: &Atom, v: &Atom, x: Symbol) -> Atom {
16233    let w = rubi_trig_to_exp(v.as_view());
16234    let simplified = match w.as_view() {
16235        AtomView::Add(add) => add
16236            .into_iter()
16237            .map(|term| rubi_simplify_integrand(&(u * term.to_owned()), x))
16238            .fold(Atom::num(0), |sum, term| sum + term),
16239        _ => rubi_simplify_integrand(&(u * w), x),
16240    };
16241
16242    let free = rubi_free_factors(&simplified, x);
16243    let nonfree = rubi_nonfree_factors(&simplified, x);
16244    rubi_expand_integrand(&(&free * &nonfree), x)
16245}
16246
16247fn rubi_trig_to_exp(expr: AtomView<'_>) -> Atom {
16248    match expr {
16249        AtomView::Add(add) => add
16250            .into_iter()
16251            .map(rubi_trig_to_exp)
16252            .fold(Atom::num(0), |sum, term| sum + term),
16253        AtomView::Mul(mul) => mul
16254            .into_iter()
16255            .map(rubi_trig_to_exp)
16256            .fold(Atom::num(1), |product, factor| product * factor),
16257        AtomView::Pow(power) => {
16258            let (base, exponent) = power.get_base_exp();
16259            let expand_square = integer_i64_view(exponent) == Some(2)
16260                && matches!(
16261                    base,
16262                    AtomView::Fun(function)
16263                        if function.get_nargs() == 1
16264                            && rubi_trig_symbol_family(function.get_symbol()).is_some()
16265                );
16266            let converted = rubi_trig_to_exp(base).pow(rubi_trig_to_exp(exponent));
16267            if expand_square {
16268                converted.expand()
16269            } else {
16270                converted
16271            }
16272        }
16273        AtomView::Fun(function) if function.get_nargs() == 1 => {
16274            let symbol = function.get_symbol();
16275            let argument = rubi_trig_to_exp(function.get(0));
16276            let i = Atom::i();
16277            let exp_pos = (&i * &argument).exp();
16278            let exp_neg = (-&i * &argument).exp();
16279            match rubi_trig_symbol_family(symbol) {
16280                Some(RubiTrigFamily::Sin) => (exp_pos - exp_neg) / (Atom::num(2) * i),
16281                Some(RubiTrigFamily::Cos) => (exp_pos + exp_neg) / 2,
16282                Some(RubiTrigFamily::Tan) => {
16283                    let numerator = exp_pos.to_owned() - exp_neg.to_owned();
16284                    let denominator = exp_pos + exp_neg;
16285                    numerator / (i * denominator)
16286                }
16287                Some(RubiTrigFamily::Cot) => {
16288                    let numerator = exp_pos.to_owned() + exp_neg.to_owned();
16289                    let denominator = exp_pos - exp_neg;
16290                    i * numerator / denominator
16291                }
16292                Some(RubiTrigFamily::Sec) => Atom::num(2) / (exp_pos + exp_neg),
16293                Some(RubiTrigFamily::Csc) => Atom::num(2) * i / (exp_pos - exp_neg),
16294                None => symbol.call_args(vec![argument]),
16295            }
16296        }
16297        AtomView::Fun(function) => {
16298            let args: Vec<_> = function.into_iter().map(rubi_trig_to_exp).collect();
16299            function.get_symbol().call_args(args)
16300        }
16301        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
16302    }
16303}
16304
16305fn rubi_expand_trig_expand(
16306    u: &Atom,
16307    f: &Atom,
16308    v: &Atom,
16309    m: &Atom,
16310    n: &Atom,
16311    _x: Symbol,
16312) -> Option<Atom> {
16313    let m = positive_integer_i64(m)?;
16314    let n = positive_integer_i64(n)?;
16315    let (sin_nv, cos_nv) = rubi_multiple_angle_sin_cos(v, n);
16316    let function_head = rubi_function_head_symbol(f)?;
16317    let expanded = if function_head == Symbol::SIN {
16318        sin_nv.pow(Atom::num(m)).expand()
16319    } else if function_head == Symbol::COS {
16320        cos_nv.pow(Atom::num(m)).expand()
16321    } else {
16322        return None;
16323    };
16324
16325    Some(match expanded.as_view() {
16326        AtomView::Add(add) => {
16327            let mut sum = Atom::num(0);
16328            for term in add {
16329                let product = u * term.to_owned();
16330                sum += rubi_mathematica_trig_quotient(&product).unwrap_or(product);
16331            }
16332            sum
16333        }
16334        _ => {
16335            let product = u * expanded;
16336            rubi_mathematica_trig_quotient(&product).unwrap_or(product)
16337        }
16338    })
16339}
16340
16341fn rubi_multiple_angle_sin_cos(v: &Atom, n: i64) -> (Atom, Atom) {
16342    if n == 0 {
16343        return (Atom::num(0), Atom::num(1));
16344    }
16345
16346    let sin_v = v.sin();
16347    let cos_v = v.cos();
16348    let mut sin_nv = sin_v.to_owned();
16349    let mut cos_nv = cos_v.to_owned();
16350
16351    for _ in 1..n {
16352        let next_sin = (&sin_nv * &cos_v + &cos_nv * &sin_v).expand();
16353        let next_cos = (&cos_nv * &cos_v - &sin_nv * &sin_v).expand();
16354        sin_nv = next_sin;
16355        cos_nv = next_cos;
16356    }
16357
16358    (sin_nv, cos_nv)
16359}
16360
16361fn positive_integer_i64(expr: &Atom) -> Option<i64> {
16362    let (numerator, denominator) = rational_number(expr)?;
16363    (denominator == 1 && numerator > 0).then_some(numerator)
16364}
16365
16366fn rubi_expand_trig_reduce_one(expr: &Atom, x: Symbol) -> Atom {
16367    rubi_expand_trig_reduce_one_recur(expr, x, 0)
16368}
16369
16370fn rubi_expand_trig_reduce_one_recur(expr: &Atom, x: Symbol, depth: usize) -> Atom {
16371    if depth > 16 {
16372        return expr.to_owned();
16373    }
16374
16375    let expanded = expr.expand();
16376    match expanded.as_view() {
16377        AtomView::Add(add) => {
16378            let mut sum = Atom::num(0);
16379            for term in add {
16380                sum += rubi_normalize_trig_reduce(
16381                    &rubi_trig_reduce_term(&term.to_owned(), x, depth)
16382                        .unwrap_or_else(|| term.to_owned()),
16383                    x,
16384                );
16385            }
16386            sum
16387        }
16388        _ => rubi_normalize_trig_reduce(
16389            &rubi_trig_reduce_term(&expanded, x, depth).unwrap_or(expanded),
16390            x,
16391        ),
16392    }
16393}
16394
16395fn rubi_trig_reduce_term(expr: &Atom, x: Symbol, depth: usize) -> Option<Atom> {
16396    if let Some(reduced) = rubi_trig_reduce(expr).filter(|reduced| reduced != expr) {
16397        return Some(reduced);
16398    }
16399
16400    let AtomView::Mul(mul) = expr.as_view() else {
16401        return None;
16402    };
16403
16404    let mut coefficient = Atom::num(1);
16405    let mut trig_factors = Vec::new();
16406    let mut hyperbolic_factors = Vec::new();
16407    let mut transformed_product = Atom::num(1);
16408    let mut transformed_factor = false;
16409    for factor in mul {
16410        let factor = factor.to_owned();
16411        if let Some(reduced) = rubi_trig_reduce(&factor).filter(|reduced| reduced != &factor) {
16412            transformed_product *= reduced;
16413            transformed_factor = true;
16414        } else if let Some(factor) = rubi_linear_trig_factor(&factor) {
16415            trig_factors.push(factor);
16416        } else if let Some(factor) = rubi_linear_hyperbolic_factor(&factor) {
16417            hyperbolic_factors.push(factor);
16418        } else {
16419            coefficient *= &factor;
16420            transformed_product *= factor;
16421        }
16422    }
16423
16424    if transformed_factor {
16425        for factor in trig_factors {
16426            transformed_product *= factor.to_atom();
16427        }
16428        for factor in hyperbolic_factors {
16429            transformed_product *= factor.to_atom();
16430        }
16431        let transformed = transformed_product.expand();
16432        return Some(rubi_expand_trig_reduce_one_recur(
16433            &transformed,
16434            x,
16435            depth + 1,
16436        ));
16437    }
16438
16439    if trig_factors.len() >= 2 {
16440        let pair = rubi_trig_reduce_pair(&trig_factors[0], &trig_factors[1]);
16441        let mut transformed = coefficient * pair;
16442        for factor in &trig_factors[2..] {
16443            transformed *= factor.to_atom();
16444        }
16445        let transformed = transformed.expand();
16446        return Some(rubi_expand_trig_reduce_one_recur(
16447            &transformed,
16448            x,
16449            depth + 1,
16450        ));
16451    }
16452
16453    if hyperbolic_factors.len() >= 2 {
16454        let pair = rubi_hyperbolic_reduce_pair(&hyperbolic_factors[0], &hyperbolic_factors[1]);
16455        let mut transformed = coefficient * pair;
16456        for factor in &trig_factors {
16457            transformed *= factor.to_atom();
16458        }
16459        for factor in &hyperbolic_factors[2..] {
16460            transformed *= factor.to_atom();
16461        }
16462        let transformed = transformed.expand();
16463        return Some(rubi_expand_trig_reduce_one_recur(
16464            &transformed,
16465            x,
16466            depth + 1,
16467        ));
16468    }
16469
16470    None
16471}
16472
16473#[derive(Clone, Copy, PartialEq, Eq)]
16474/// Trigonometric heads supported by linear-argument factor analysis.
16475enum RubiLinearTrigKind {
16476    Sin,
16477    Cos,
16478}
16479
16480/// A trigonometric factor with an affine argument and explicit exponent.
16481struct RubiLinearTrigFactor {
16482    kind: RubiLinearTrigKind,
16483    angle: Atom,
16484}
16485
16486impl RubiLinearTrigFactor {
16487    fn to_atom(&self) -> Atom {
16488        match self.kind {
16489            RubiLinearTrigKind::Sin => self.angle.sin(),
16490            RubiLinearTrigKind::Cos => self.angle.cos(),
16491        }
16492    }
16493}
16494
16495#[derive(Clone, Copy, PartialEq, Eq)]
16496/// Hyperbolic heads supported by linear-argument factor analysis.
16497enum RubiLinearHyperbolicKind {
16498    Sinh,
16499    Cosh,
16500}
16501
16502/// A hyperbolic factor with an affine argument and explicit exponent.
16503struct RubiLinearHyperbolicFactor {
16504    kind: RubiLinearHyperbolicKind,
16505    angle: Atom,
16506}
16507
16508impl RubiLinearHyperbolicFactor {
16509    fn to_atom(&self) -> Atom {
16510        match self.kind {
16511            RubiLinearHyperbolicKind::Sinh => self.angle.sinh(),
16512            RubiLinearHyperbolicKind::Cosh => self.angle.cosh(),
16513        }
16514    }
16515}
16516
16517fn rubi_linear_hyperbolic_factor(expr: &Atom) -> Option<RubiLinearHyperbolicFactor> {
16518    let AtomView::Fun(function) = expr.as_view() else {
16519        return None;
16520    };
16521    if function.get_nargs() != 1 {
16522        return None;
16523    }
16524    let argument = function.get(0).to_owned();
16525    match function.get_symbol().get_stripped_ascii_name() {
16526        Some("sinh") => Some(RubiLinearHyperbolicFactor {
16527            kind: RubiLinearHyperbolicKind::Sinh,
16528            angle: argument,
16529        }),
16530        Some("cosh") => Some(RubiLinearHyperbolicFactor {
16531            kind: RubiLinearHyperbolicKind::Cosh,
16532            angle: argument,
16533        }),
16534        _ => None,
16535    }
16536}
16537
16538fn rubi_hyperbolic_reduce_pair(
16539    left: &RubiLinearHyperbolicFactor,
16540    right: &RubiLinearHyperbolicFactor,
16541) -> Atom {
16542    let sum = (&left.angle + &right.angle).expand();
16543    let difference = (&left.angle - &right.angle).expand();
16544    let reverse_difference = (&right.angle - &left.angle).expand();
16545    match (left.kind, right.kind) {
16546        (RubiLinearHyperbolicKind::Sinh, RubiLinearHyperbolicKind::Sinh) => {
16547            (sum.cosh() - difference.cosh()) / 2
16548        }
16549        (RubiLinearHyperbolicKind::Cosh, RubiLinearHyperbolicKind::Cosh) => {
16550            (sum.cosh() + difference.cosh()) / 2
16551        }
16552        (RubiLinearHyperbolicKind::Sinh, RubiLinearHyperbolicKind::Cosh) => {
16553            (sum.sinh() + difference.sinh()) / 2
16554        }
16555        (RubiLinearHyperbolicKind::Cosh, RubiLinearHyperbolicKind::Sinh) => {
16556            (sum.sinh() + reverse_difference.sinh()) / 2
16557        }
16558    }
16559}
16560
16561fn rubi_linear_trig_factor(expr: &Atom) -> Option<RubiLinearTrigFactor> {
16562    if let Some(angle) = rubi_sin_argument(expr.as_view()) {
16563        return Some(RubiLinearTrigFactor {
16564            kind: RubiLinearTrigKind::Sin,
16565            angle,
16566        });
16567    }
16568    if let Some(angle) = rubi_cos_argument(expr.as_view()) {
16569        return Some(RubiLinearTrigFactor {
16570            kind: RubiLinearTrigKind::Cos,
16571            angle,
16572        });
16573    }
16574    None
16575}
16576
16577fn rubi_trig_reduce_pair(left: &RubiLinearTrigFactor, right: &RubiLinearTrigFactor) -> Atom {
16578    let sum = (&left.angle + &right.angle).expand();
16579    let difference = (&left.angle - &right.angle).expand();
16580    let reverse_difference = (&right.angle - &left.angle).expand();
16581    match (left.kind, right.kind) {
16582        (RubiLinearTrigKind::Sin, RubiLinearTrigKind::Sin) => (difference.cos() - sum.cos()) / 2,
16583        (RubiLinearTrigKind::Cos, RubiLinearTrigKind::Cos) => (difference.cos() + sum.cos()) / 2,
16584        (RubiLinearTrigKind::Sin, RubiLinearTrigKind::Cos) => (sum.sin() + difference.sin()) / 2,
16585        (RubiLinearTrigKind::Cos, RubiLinearTrigKind::Sin) => {
16586            (sum.sin() + reverse_difference.sin()) / 2
16587        }
16588    }
16589}
16590
16591fn rubi_normalize_trig_reduce(expr: &Atom, x: Symbol) -> Atom {
16592    match expr.as_view() {
16593        AtomView::Add(add) => {
16594            let mut sum = Atom::num(0);
16595            for term in add {
16596                sum += rubi_normalize_trig_reduce(&term.to_owned(), x);
16597            }
16598            sum
16599        }
16600        AtomView::Mul(mul) => {
16601            let mut product = Atom::num(1);
16602            for factor in mul {
16603                product *= rubi_normalize_trig_reduce(&factor.to_owned(), x);
16604            }
16605            product
16606        }
16607        AtomView::Pow(power) => {
16608            let base = rubi_normalize_trig_reduce(&power.get_base().to_owned(), x);
16609            base.pow(rubi_normalize_trig_reduce(&power.get_exp().to_owned(), x))
16610        }
16611        AtomView::Fun(function)
16612            if (rubi_sin_symbol_q(function.get_symbol())
16613                || rubi_cos_symbol_q(function.get_symbol()))
16614                && function.get_nargs() == 1 =>
16615        {
16616            let argument = function.get(0).to_owned();
16617            let argument = rubi_expand_to_sum(&argument, x);
16618            if function.get_symbol() == Symbol::SIN {
16619                argument.sin()
16620            } else if function.get_symbol() == Symbol::COS {
16621                argument.cos()
16622            } else if function.get_symbol() == rubi_symbols().inert_sin {
16623                i_sin(argument)
16624            } else {
16625                i_cos(argument)
16626            }
16627        }
16628        _ => expr.to_owned(),
16629    }
16630}
16631
16632fn rubi_trig_reduce(expr: &Atom) -> Option<Atom> {
16633    if let Some((angle, n)) = rubi_sin_power_parts(expr) {
16634        return rubi_trig_reduce_sin_power(&angle, n);
16635    }
16636
16637    if let Some((angle, n)) = rubi_cos_power_parts(expr) {
16638        return rubi_trig_reduce_cos_power(&angle, n);
16639    }
16640
16641    if let Some((angle, n)) = rubi_sinh_power_parts(expr) {
16642        return rubi_hyperbolic_reduce_sinh_power(&angle, n);
16643    }
16644
16645    if let Some((angle, n)) = rubi_cosh_power_parts(expr) {
16646        return rubi_hyperbolic_reduce_cosh_power(&angle, n);
16647    }
16648
16649    if let Some((angle, n)) = rubi_cos_times_sin_power_parts(expr) {
16650        return rubi_trig_reduce_cos_times_sin_power(&angle, n);
16651    }
16652
16653    None
16654}
16655
16656fn rubi_sin_power_parts(expr: &Atom) -> Option<(Atom, i64)> {
16657    match expr.as_view() {
16658        AtomView::Pow(power) => {
16659            let base = power.get_base();
16660            let exponent = integer_i64_view(power.get_exp())?;
16661            rubi_sin_argument(base).map(|angle| (angle, exponent))
16662        }
16663        view => rubi_sin_argument(view).map(|angle| (angle, 1)),
16664    }
16665}
16666
16667fn rubi_cos_power_parts(expr: &Atom) -> Option<(Atom, i64)> {
16668    match expr.as_view() {
16669        AtomView::Pow(power) => {
16670            let base = power.get_base();
16671            let exponent = integer_i64_view(power.get_exp())?;
16672            rubi_cos_argument(base).map(|angle| (angle, exponent))
16673        }
16674        view => rubi_cos_argument(view).map(|angle| (angle, 1)),
16675    }
16676}
16677
16678fn rubi_sinh_power_parts(expr: &Atom) -> Option<(Atom, i64)> {
16679    match expr.as_view() {
16680        AtomView::Pow(power) => {
16681            let base = power.get_base();
16682            let exponent = integer_i64_view(power.get_exp())?;
16683            rubi_hyperbolic_argument(base, "sinh").map(|angle| (angle, exponent))
16684        }
16685        view => rubi_hyperbolic_argument(view, "sinh").map(|angle| (angle, 1)),
16686    }
16687}
16688
16689fn rubi_cosh_power_parts(expr: &Atom) -> Option<(Atom, i64)> {
16690    match expr.as_view() {
16691        AtomView::Pow(power) => {
16692            let base = power.get_base();
16693            let exponent = integer_i64_view(power.get_exp())?;
16694            rubi_hyperbolic_argument(base, "cosh").map(|angle| (angle, exponent))
16695        }
16696        view => rubi_hyperbolic_argument(view, "cosh").map(|angle| (angle, 1)),
16697    }
16698}
16699
16700fn rubi_hyperbolic_reduce_sinh_power(angle: &Atom, n: i64) -> Option<Atom> {
16701    if n < 0 {
16702        return None;
16703    }
16704    if n == 0 {
16705        return Some(Atom::num(1));
16706    }
16707    if n == 1 {
16708        return Some(angle.sinh());
16709    }
16710
16711    let mut sum = Atom::num(0);
16712    if n % 2 == 0 {
16713        let denominator = power_of_two_i64(n)?;
16714        let middle_sign = if (n / 2) % 2 == 0 { 1 } else { -1 };
16715        sum += Atom::num(middle_sign * binomial_i64(n, n / 2)?) / Atom::num(denominator);
16716        for j in 0..(n / 2) {
16717            let k = n - 2 * j;
16718            let sign = if j % 2 == 0 { 1 } else { -1 };
16719            let numerator = sign * 2 * binomial_i64(n, j)?;
16720            sum += Atom::num(numerator) * (Atom::num(k) * angle).cosh() / Atom::num(denominator);
16721        }
16722    } else {
16723        let denominator = power_of_two_i64(n - 1)?;
16724        for j in 0..=((n - 1) / 2) {
16725            let k = n - 2 * j;
16726            let sign = if j % 2 == 0 { 1 } else { -1 };
16727            let numerator = sign * binomial_i64(n, j)?;
16728            sum += Atom::num(numerator) * (Atom::num(k) * angle).sinh() / Atom::num(denominator);
16729        }
16730    }
16731
16732    Some(sum)
16733}
16734
16735fn rubi_hyperbolic_reduce_cosh_power(angle: &Atom, n: i64) -> Option<Atom> {
16736    if n < 0 {
16737        return None;
16738    }
16739    if n == 0 {
16740        return Some(Atom::num(1));
16741    }
16742    if n == 1 {
16743        return Some(angle.cosh());
16744    }
16745
16746    let mut sum = Atom::num(0);
16747    if n % 2 == 0 {
16748        let denominator = power_of_two_i64(n)?;
16749        sum += Atom::num(binomial_i64(n, n / 2)?) / Atom::num(denominator);
16750        for j in 0..(n / 2) {
16751            let k = n - 2 * j;
16752            let numerator = 2 * binomial_i64(n, j)?;
16753            sum += Atom::num(numerator) * (Atom::num(k) * angle).cosh() / Atom::num(denominator);
16754        }
16755    } else {
16756        let denominator = power_of_two_i64(n - 1)?;
16757        for j in 0..=((n - 1) / 2) {
16758            let k = n - 2 * j;
16759            let numerator = binomial_i64(n, j)?;
16760            sum += Atom::num(numerator) * (Atom::num(k) * angle).cosh() / Atom::num(denominator);
16761        }
16762    }
16763
16764    Some(sum)
16765}
16766
16767fn rubi_cos_times_sin_power_parts(expr: &Atom) -> Option<(Atom, i64)> {
16768    let AtomView::Mul(mul) = expr.as_view() else {
16769        return None;
16770    };
16771
16772    let mut angle = None;
16773    let mut sin_power = None;
16774    for factor in mul {
16775        let factor = factor.to_owned();
16776        if let Some(cos_angle) = rubi_cos_argument(factor.as_view()) {
16777            if angle.as_ref().is_some_and(|a| a != &cos_angle) {
16778                return None;
16779            }
16780            angle = Some(cos_angle);
16781            continue;
16782        }
16783
16784        if let Some((sin_angle, power)) = rubi_sin_power_parts(&factor) {
16785            if angle.as_ref().is_some_and(|a| a != &sin_angle) {
16786                return None;
16787            }
16788            angle = Some(sin_angle);
16789            sin_power = Some(power);
16790            continue;
16791        }
16792
16793        return None;
16794    }
16795
16796    Some((angle?, sin_power? + 1))
16797}
16798
16799fn rubi_hyperbolic_argument(expr: AtomView<'_>, name: &str) -> Option<Atom> {
16800    match expr {
16801        AtomView::Fun(function)
16802            if function.get_symbol().get_stripped_ascii_name() == Some(name)
16803                && function.get_nargs() == 1 =>
16804        {
16805            Some(function.get(0).to_owned())
16806        }
16807        _ => None,
16808    }
16809}
16810
16811fn rubi_sin_argument(expr: AtomView<'_>) -> Option<Atom> {
16812    match expr {
16813        AtomView::Fun(function)
16814            if rubi_sin_symbol_q(function.get_symbol()) && function.get_nargs() == 1 =>
16815        {
16816            Some(function.get(0).to_owned())
16817        }
16818        _ => None,
16819    }
16820}
16821
16822fn rubi_cos_argument(expr: AtomView<'_>) -> Option<Atom> {
16823    match expr {
16824        AtomView::Fun(function)
16825            if rubi_cos_symbol_q(function.get_symbol()) && function.get_nargs() == 1 =>
16826        {
16827            Some(function.get(0).to_owned())
16828        }
16829        _ => None,
16830    }
16831}
16832
16833fn rubi_sin_symbol_q(symbol: Symbol) -> bool {
16834    symbol == Symbol::SIN || symbol == rubi_symbols().inert_sin
16835}
16836
16837fn rubi_cos_symbol_q(symbol: Symbol) -> bool {
16838    symbol == Symbol::COS || symbol == rubi_symbols().inert_cos
16839}
16840
16841fn rubi_trig_reduce_sin_power(angle: &Atom, n: i64) -> Option<Atom> {
16842    if n < 0 {
16843        return None;
16844    }
16845    if n == 0 {
16846        return Some(Atom::num(1));
16847    }
16848    if n == 1 {
16849        return Some(angle.sin());
16850    }
16851
16852    let mut sum = Atom::num(0);
16853    if n % 2 == 0 {
16854        let denominator = power_of_two_i64(n)?;
16855        sum += Atom::num(binomial_i64(n, n / 2)?) / Atom::num(denominator);
16856        for j in 0..(n / 2) {
16857            let k = n - 2 * j;
16858            let sign = if (n / 2 - j) % 2 == 0 { 1 } else { -1 };
16859            let numerator = sign * 2 * binomial_i64(n, j)?;
16860            sum += Atom::num(numerator) * (Atom::num(k) * angle).cos() / Atom::num(denominator);
16861        }
16862    } else {
16863        let denominator = power_of_two_i64(n - 1)?;
16864        for j in 0..=((n - 1) / 2) {
16865            let k = n - 2 * j;
16866            let sign = if ((n - 1) / 2 - j) % 2 == 0 { 1 } else { -1 };
16867            let numerator = sign * binomial_i64(n, j)?;
16868            sum += Atom::num(numerator) * (Atom::num(k) * angle).sin() / Atom::num(denominator);
16869        }
16870    }
16871
16872    Some(sum)
16873}
16874
16875fn rubi_trig_reduce_cos_power(angle: &Atom, n: i64) -> Option<Atom> {
16876    if n < 0 {
16877        return None;
16878    }
16879    if n == 0 {
16880        return Some(Atom::num(1));
16881    }
16882    if n == 1 {
16883        return Some(angle.cos());
16884    }
16885
16886    let mut sum = Atom::num(0);
16887    if n % 2 == 0 {
16888        let denominator = power_of_two_i64(n)?;
16889        sum += Atom::num(binomial_i64(n, n / 2)?) / Atom::num(denominator);
16890        for j in 0..(n / 2) {
16891            let k = n - 2 * j;
16892            let numerator = 2 * binomial_i64(n, j)?;
16893            sum += Atom::num(numerator) * (Atom::num(k) * angle).cos() / Atom::num(denominator);
16894        }
16895    } else {
16896        let denominator = power_of_two_i64(n - 1)?;
16897        for j in 0..=((n - 1) / 2) {
16898            let k = n - 2 * j;
16899            let numerator = binomial_i64(n, j)?;
16900            sum += Atom::num(numerator) * (Atom::num(k) * angle).cos() / Atom::num(denominator);
16901        }
16902    }
16903
16904    Some(sum)
16905}
16906
16907fn rubi_trig_reduce_cos_times_sin_power(angle: &Atom, n: i64) -> Option<Atom> {
16908    if n < 1 {
16909        return None;
16910    }
16911
16912    let mut sum = Atom::num(0);
16913    if n % 2 == 0 {
16914        let denominator = power_of_two_i64(n)?.checked_mul(n)?;
16915        for j in 0..(n / 2) {
16916            let k = n - 2 * j;
16917            let sign = if (n / 2 - j) % 2 == 0 { 1 } else { -1 };
16918            let numerator = -sign * 2 * k * binomial_i64(n, j)?;
16919            sum += Atom::num(numerator) * (Atom::num(k) * angle).sin() / Atom::num(denominator);
16920        }
16921    } else {
16922        let denominator = power_of_two_i64(n - 1)?.checked_mul(n)?;
16923        for j in 0..=((n - 1) / 2) {
16924            let k = n - 2 * j;
16925            let sign = if ((n - 1) / 2 - j) % 2 == 0 { 1 } else { -1 };
16926            let numerator = sign * k * binomial_i64(n, j)?;
16927            sum += Atom::num(numerator) * (Atom::num(k) * angle).cos() / Atom::num(denominator);
16928        }
16929    }
16930
16931    Some(sum)
16932}
16933
16934fn power_of_two_i64(exponent: i64) -> Option<i64> {
16935    if !(0..63).contains(&exponent) {
16936        return None;
16937    }
16938    1_i64.checked_shl(exponent as u32)
16939}
16940
16941/// Coefficients and degree of a polynomial binomial.
16942struct RubiBinomialParts {
16943    a: Atom,
16944    b: Atom,
16945    n: Atom,
16946}
16947
16948fn rubi_binomial_q<T: AtomCore>(expr: T, x: Symbol) -> bool {
16949    rubi_binomial_parts_equivalent(expr.as_atom_view(), x).is_some()
16950}
16951
16952fn rubi_binomial_q_list(exprs: &[&Atom], x: Symbol) -> bool {
16953    exprs.iter().all(|expr| rubi_binomial_q(expr.as_view(), x))
16954}
16955
16956fn rubi_expand_trig_reduce_angles_q(v: &Atom, w: &Atom, x: Symbol) -> bool {
16957    (rubi_polynomial_q(v, x) && rubi_polynomial_q(w, x))
16958        || (rubi_binomial_q_list(&[v, w], x) && is_free_of(&rubi_cancel(&(v / w)), x))
16959}
16960
16961fn rubi_binomial_match_q(expr: &Atom, x: Symbol) -> bool {
16962    rubi_binomial_match_parts(expr, x).is_some()
16963}
16964
16965fn rubi_binomial_match_q_list(exprs: &[&Atom], x: Symbol) -> bool {
16966    exprs.iter().all(|expr| rubi_binomial_match_q(expr, x))
16967}
16968
16969fn rubi_binomial_degree(expr: &Atom, x: Symbol) -> Option<Atom> {
16970    rubi_binomial_parts_equivalent(expr.as_view(), x).map(|parts| parts.n)
16971}
16972
16973fn rubi_binomial_parts(expr: AtomView<'_>, x: Symbol) -> Option<RubiBinomialParts> {
16974    if let Some(terms) = collect_polynomial_terms(&expr.to_owned(), x) {
16975        return rubi_binomial_parts_from_terms(&terms);
16976    }
16977
16978    match expr {
16979        AtomView::Pow(power)
16980            if matches!(power.get_base(), AtomView::Var(variable) if variable.get_symbol() == x)
16981                && is_free_of(power.get_exp(), x) =>
16982        {
16983            Some(RubiBinomialParts {
16984                a: Atom::num(0),
16985                b: Atom::num(1),
16986                n: power.get_exp().to_owned(),
16987            })
16988        }
16989        AtomView::Mul(mul) => {
16990            let factors: Vec<Atom> = mul.into_iter().map(|factor| factor.to_owned()).collect();
16991            let first = factors.first()?.to_owned();
16992            let rest = product_atoms(&factors[1..]);
16993            if is_free_of(&first, x) {
16994                let parts = rubi_binomial_parts(rest.as_view(), x)?;
16995                return Some(RubiBinomialParts {
16996                    a: &first * parts.a,
16997                    b: first * parts.b,
16998                    n: parts.n,
16999                });
17000            }
17001            if is_free_of(&rest, x) {
17002                let parts = rubi_binomial_parts(first.as_view(), x)?;
17003                return Some(RubiBinomialParts {
17004                    a: &rest * parts.a,
17005                    b: rest * parts.b,
17006                    n: parts.n,
17007                });
17008            }
17009
17010            let left = rubi_binomial_parts(first.as_view(), x)?;
17011            let right = rubi_binomial_parts(rest.as_view(), x)?;
17012            rubi_multiply_binomial_parts(left, right)
17013        }
17014        AtomView::Add(add) => {
17015            let terms: Vec<Atom> = add.into_iter().map(|term| term.to_owned()).collect();
17016            let first = terms.first()?.to_owned();
17017            let rest = terms[1..]
17018                .iter()
17019                .cloned()
17020                .fold(Atom::num(0), |sum, term| sum + term);
17021            if is_free_of(&first, x) {
17022                let parts = rubi_binomial_parts(rest.as_view(), x)?;
17023                return Some(RubiBinomialParts {
17024                    a: first + parts.a,
17025                    b: parts.b,
17026                    n: parts.n,
17027                });
17028            }
17029            if is_free_of(&rest, x) {
17030                let parts = rubi_binomial_parts(first.as_view(), x)?;
17031                return Some(RubiBinomialParts {
17032                    a: rest + parts.a,
17033                    b: parts.b,
17034                    n: parts.n,
17035                });
17036            }
17037
17038            let left = rubi_binomial_parts(first.as_view(), x)?;
17039            let right = rubi_binomial_parts(rest.as_view(), x)?;
17040            if !eqq!(left.n, right.n) {
17041                return None;
17042            }
17043            Some(RubiBinomialParts {
17044                a: left.a + right.a,
17045                b: left.b + right.b,
17046                n: left.n,
17047            })
17048        }
17049        AtomView::Num(_) | AtomView::Var(_) | AtomView::Fun(_) | AtomView::Pow(_) => None,
17050    }
17051}
17052
17053fn rubi_binomial_parts_equivalent(expr: AtomView<'_>, x: Symbol) -> Option<RubiBinomialParts> {
17054    rubi_binomial_parts(expr, x)
17055}
17056
17057fn rubi_binomial_parts_from_terms(terms: &BTreeMap<i64, Atom>) -> Option<RubiBinomialParts> {
17058    match terms.len() {
17059        1 => {
17060            let (&n, b) = terms.iter().next()?;
17061            if n == 0 || b.is_zero() {
17062                return None;
17063            }
17064            Some(RubiBinomialParts {
17065                a: Atom::num(0),
17066                b: b.to_owned(),
17067                n: Atom::num(n),
17068            })
17069        }
17070        2 => {
17071            let a = terms.get(&0)?.to_owned();
17072            let (&n, b) = terms.iter().find(|(degree, _)| **degree != 0)?;
17073            if n == 0 || b.is_zero() {
17074                return None;
17075            }
17076            Some(RubiBinomialParts {
17077                a,
17078                b: b.to_owned(),
17079                n: Atom::num(n),
17080            })
17081        }
17082        _ => None,
17083    }
17084}
17085
17086fn rubi_multiply_binomial_parts(
17087    left: RubiBinomialParts,
17088    right: RubiBinomialParts,
17089) -> Option<RubiBinomialParts> {
17090    let exponent_sum = &left.n + &right.n;
17091    if left.a.is_zero() {
17092        if right.a.is_zero() {
17093            return Some(RubiBinomialParts {
17094                a: Atom::num(0),
17095                b: left.b * right.b,
17096                n: exponent_sum,
17097            });
17098        }
17099        if eqq!(exponent_sum, 0) {
17100            return Some(RubiBinomialParts {
17101                a: &left.b * &right.b,
17102                b: left.b * right.a,
17103                n: left.n,
17104            });
17105        }
17106        return None;
17107    }
17108    if right.a.is_zero() {
17109        if eqq!(exponent_sum, 0) {
17110            return Some(RubiBinomialParts {
17111                a: &left.b * &right.b,
17112                b: left.a * right.b,
17113                n: right.n,
17114            });
17115        }
17116        return None;
17117    }
17118    if eqq!(left.n, right.n) && eqq!(&left.a * &right.b + &left.b * &right.a, 0) {
17119        return Some(RubiBinomialParts {
17120            a: left.a * right.a,
17121            b: left.b * right.b,
17122            n: Atom::num(2) * left.n,
17123        });
17124    }
17125    None
17126}
17127
17128fn rubi_binomial_match_parts(expr: &Atom, x: Symbol) -> Option<RubiBinomialParts> {
17129    if let Some((b, n)) = rubi_monomial_coefficient_exponent(expr, x) {
17130        return Some(RubiBinomialParts {
17131            a: Atom::num(0),
17132            b,
17133            n,
17134        });
17135    }
17136
17137    let AtomView::Add(add) = expr.as_view() else {
17138        return None;
17139    };
17140    let terms: Vec<Atom> = add.into_iter().map(|term| term.to_owned()).collect();
17141    let mut dependent = terms.iter().filter(|term| !is_free_of(*term, x));
17142    let monomial = dependent.next()?;
17143    if dependent.next().is_some() {
17144        return None;
17145    }
17146    let (b, n) = rubi_monomial_coefficient_exponent(monomial, x)?;
17147    let a = terms
17148        .into_iter()
17149        .filter(|term| is_free_of(term, x))
17150        .fold(Atom::num(0), |sum, term| sum + term);
17151    Some(RubiBinomialParts { a, b, n })
17152}
17153
17154/// Coefficients and degree of a polynomial trinomial.
17155struct RubiTrinomialParts {
17156    a: Atom,
17157    b: Atom,
17158    c: Atom,
17159    n: i64,
17160}
17161
17162fn rubi_trinomial_q(expr: &Atom, x: Symbol) -> bool {
17163    rubi_trinomial_parts_equivalent(expr, x).is_some()
17164        && !rubi_quadratic_q(expr, x)
17165        && !rubi_binomial_square_q(expr, x)
17166}
17167
17168// IntegrationUtilityFunctions.m: Not[MatchQ[u,w_^2 /; BinomialQ[w,x]]].
17169fn rubi_binomial_square_q(expr: &Atom, x: Symbol) -> bool {
17170    let AtomView::Pow(power) = expr.as_view() else {
17171        return false;
17172    };
17173    integer_i64_view(power.get_exp()) == Some(2) && rubi_binomial_q(power.get_base(), x)
17174}
17175
17176fn rubi_trinomial_match_q(expr: &Atom, x: Symbol) -> bool {
17177    rubi_trinomial_parts(expr, x).is_some()
17178}
17179
17180fn rubi_trinomial_parts(expr: &Atom, x: Symbol) -> Option<RubiTrinomialParts> {
17181    let terms = collect_polynomial_terms_without_expanding(expr, x)?;
17182    rubi_trinomial_parts_from_terms(&terms)
17183}
17184
17185fn rubi_trinomial_parts_equivalent(expr: &Atom, x: Symbol) -> Option<RubiTrinomialParts> {
17186    let terms = collect_polynomial_terms(expr, x)?;
17187    rubi_trinomial_parts_from_terms(&terms)
17188}
17189
17190fn rubi_trinomial_parts_from_terms(terms: &BTreeMap<i64, Atom>) -> Option<RubiTrinomialParts> {
17191    if terms.len() != 3 {
17192        return None;
17193    }
17194
17195    let (&first_degree, _) = terms.iter().next()?;
17196    if first_degree != 0 {
17197        return None;
17198    }
17199
17200    let degrees: Vec<i64> = terms.keys().copied().collect();
17201    let n = degrees[1];
17202    if n == 0 || degrees[2] != 2 * n {
17203        return None;
17204    }
17205
17206    let a = terms.get(&0)?.to_owned();
17207    let b = terms.get(&n)?.to_owned();
17208    let c = terms.get(&(2 * n))?.to_owned();
17209    if b.is_zero() || c.is_zero() {
17210        return None;
17211    }
17212
17213    Some(RubiTrinomialParts { a, b, c, n })
17214}
17215
17216/// Coefficients and exponents of a generalized binomial.
17217struct RubiGeneralizedBinomialParts {
17218    a: Atom,
17219    b: Atom,
17220    n: i64,
17221    q: i64,
17222}
17223
17224fn rubi_generalized_binomial_q(expr: &Atom, x: Symbol) -> bool {
17225    rubi_generalized_binomial_parts_equivalent(expr, x).is_some()
17226}
17227
17228fn rubi_generalized_binomial_match_q(expr: &Atom, x: Symbol) -> bool {
17229    rubi_generalized_binomial_parts(expr, x).is_some()
17230}
17231
17232fn rubi_generalized_binomial_parts(expr: &Atom, x: Symbol) -> Option<RubiGeneralizedBinomialParts> {
17233    let terms = collect_polynomial_terms_without_expanding(expr, x)?;
17234    rubi_generalized_binomial_parts_from_terms(&terms)
17235}
17236
17237fn rubi_generalized_binomial_parts_equivalent(
17238    expr: &Atom,
17239    x: Symbol,
17240) -> Option<RubiGeneralizedBinomialParts> {
17241    let terms = collect_polynomial_terms(expr, x)?;
17242    rubi_generalized_binomial_parts_from_terms(&terms)
17243}
17244
17245fn rubi_generalized_binomial_parts_from_terms(
17246    terms: &BTreeMap<i64, Atom>,
17247) -> Option<RubiGeneralizedBinomialParts> {
17248    if terms.len() != 2 || terms.contains_key(&0) {
17249        return None;
17250    }
17251
17252    let mut iter = terms.iter();
17253    let (&q, a) = iter.next()?;
17254    let (&n, b) = iter.next()?;
17255    if q == 0 || n == 0 || n <= q || a.is_zero() || b.is_zero() {
17256        return None;
17257    }
17258
17259    Some(RubiGeneralizedBinomialParts {
17260        a: a.to_owned(),
17261        b: b.to_owned(),
17262        n,
17263        q,
17264    })
17265}
17266
17267/// Coefficients and exponents of a generalized trinomial.
17268struct RubiGeneralizedTrinomialParts {
17269    a: Atom,
17270    b: Atom,
17271    c: Atom,
17272    n: i64,
17273    q: i64,
17274}
17275
17276fn rubi_generalized_trinomial_q(expr: &Atom, x: Symbol) -> bool {
17277    rubi_generalized_trinomial_parts_equivalent(expr, x).is_some()
17278}
17279
17280fn rubi_generalized_trinomial_match_q(expr: &Atom, x: Symbol) -> bool {
17281    rubi_generalized_trinomial_parts(expr, x).is_some()
17282}
17283
17284fn rubi_generalized_trinomial_degree(expr: &Atom, x: Symbol) -> Option<Atom> {
17285    rubi_generalized_trinomial_parts_equivalent(expr, x).map(|parts| Atom::num(parts.n - parts.q))
17286}
17287
17288fn rubi_generalized_trinomial_parts(
17289    expr: &Atom,
17290    x: Symbol,
17291) -> Option<RubiGeneralizedTrinomialParts> {
17292    let terms = collect_polynomial_terms_without_expanding(expr, x)?;
17293    rubi_generalized_trinomial_parts_from_terms(&terms)
17294}
17295
17296fn rubi_generalized_trinomial_parts_equivalent(
17297    expr: &Atom,
17298    x: Symbol,
17299) -> Option<RubiGeneralizedTrinomialParts> {
17300    let terms = collect_polynomial_terms(expr, x)?;
17301    rubi_generalized_trinomial_parts_from_terms(&terms)
17302}
17303
17304fn rubi_generalized_trinomial_parts_from_terms(
17305    terms: &BTreeMap<i64, Atom>,
17306) -> Option<RubiGeneralizedTrinomialParts> {
17307    if terms.len() != 3 || terms.contains_key(&0) {
17308        return None;
17309    }
17310
17311    let degrees: Vec<i64> = terms.keys().copied().collect();
17312    let q = degrees[0];
17313    let n = degrees[1];
17314    let r = degrees[2];
17315    if q == 0 || n == 0 || r != 2 * n - q {
17316        return None;
17317    }
17318
17319    let a = terms.get(&q)?.to_owned();
17320    let b = terms.get(&n)?.to_owned();
17321    let c = terms.get(&r)?.to_owned();
17322    if a.is_zero() || b.is_zero() || c.is_zero() {
17323        return None;
17324    }
17325
17326    Some(RubiGeneralizedTrinomialParts { a, b, c, n, q })
17327}
17328
17329fn rubi_together(expr: &Atom) -> Atom {
17330    let together = expr.together();
17331    if !rubi_sum_q(expr) && rubi_leaf_count(expr.as_view()) < rubi_leaf_count(together.as_view()) {
17332        expr.to_owned()
17333    } else {
17334        together
17335    }
17336}
17337
17338fn rubi_together_simplify(expr: &Atom) -> Atom {
17339    // Mathematica's Simplify reaches elementary identities inside the terms
17340    // of a sum even when Together would first combine them into one rational
17341    // expression. Preserve that behavior for the local adapters used below;
17342    // otherwise identities such as Csc[z]^3/(1-Csc[z]^2) are hidden inside a
17343    // much larger numerator before the trigonometric simplifier sees them.
17344    let locally_simplified = if rubi_sum_q(expr) {
17345        map_sum_terms(expr, |term| rubi_simplify(term))
17346    } else {
17347        expr.to_owned()
17348    };
17349    let together = rubi_together(&locally_simplified);
17350    let simplified = rubi_simplify(&together);
17351    let fixed = rubi_fix_simplify(&rubi_together(&simplified));
17352    let fixed = rubi_factor_rational_denominator_if_simpler(&fixed);
17353    let combination_limit = rubi_product_factors(&fixed).len();
17354    let mut combined = fixed;
17355    for _ in 0..combination_limit {
17356        let Some(candidate) = rubi_combine_exact_rational_power_base_factor(&combined) else {
17357            break;
17358        };
17359        if candidate == combined {
17360            break;
17361        }
17362        combined = candidate;
17363    }
17364    combined
17365}
17366
17367fn rubi_factor_rational_denominator_if_simpler(expr: &Atom) -> Atom {
17368    let Some((numerator, denominator)) = rational_numerator_denominator(expr) else {
17369        return expr.to_owned();
17370    };
17371    if denominator.is_one() {
17372        return expr.to_owned();
17373    }
17374    let Some(factored_denominator) = rubi_try_factor(denominator.as_view()) else {
17375        return expr.to_owned();
17376    };
17377    if factored_denominator == denominator
17378        || rubi_leaf_count(factored_denominator.as_view()) >= rubi_leaf_count(denominator.as_view())
17379        || !rubi_equivalent_q(&factored_denominator, &denominator)
17380    {
17381        return expr.to_owned();
17382    }
17383
17384    numerator / factored_denominator
17385}
17386
17387fn rubi_fix_simplify(expr: &Atom) -> Atom {
17388    let Some(factored) = rubi_fix_simplify_common_rational_power_sum(expr) else {
17389        return expr.to_owned();
17390    };
17391
17392    let factors = rubi_product_factors(&factored);
17393    factors.into_iter().fold(Atom::num(1), |product, factor| {
17394        if rubi_sum_q(&factor) {
17395            product * rubi_fix_simplify(&factor)
17396        } else {
17397            product * factor
17398        }
17399    })
17400}
17401
17402fn rubi_fix_simplify_common_rational_power_sum(expr: &Atom) -> Option<Atom> {
17403    let terms = rubi_add_terms(expr);
17404    let [left, right] = terms.as_slice() else {
17405        return None;
17406    };
17407    let left_factors = rubi_product_factors(left);
17408    let right_factors = rubi_product_factors(right);
17409
17410    for (left_index, left_factor) in left_factors.iter().enumerate() {
17411        let (base, left_exponent_atom) = rubi_factor_base_exponent(left_factor);
17412        if rational_q(&base) {
17413            continue;
17414        }
17415        let Some(left_exponent) = rational_number(&left_exponent_atom).map(Rational::from) else {
17416            continue;
17417        };
17418        if left_exponent <= 0 {
17419            continue;
17420        }
17421
17422        let Some((right_index, right_exponent)) =
17423            rubi_matching_rational_power_factor(&right_factors, &base)
17424        else {
17425            continue;
17426        };
17427        if right_exponent <= 0 {
17428            continue;
17429        }
17430
17431        let common_exponent = (&left_exponent).min(&right_exponent);
17432        let left_residual = &left_exponent - common_exponent;
17433        let right_residual = &right_exponent - common_exponent;
17434
17435        let mut left_rest = left_factors.to_owned();
17436        let _ = left_rest.remove(left_index);
17437        if left_residual > 0 {
17438            left_rest.push(base.pow(rational_atom(left_residual)));
17439        }
17440        let mut right_rest = right_factors.to_owned();
17441        let _ = right_rest.remove(right_index);
17442        if right_residual > 0 {
17443            right_rest.push(base.pow(rational_atom(right_residual)));
17444        }
17445
17446        return Some(
17447            base.pow(rational_atom(common_exponent.to_owned()))
17448                * (product_atoms(&left_rest) + product_atoms(&right_rest)),
17449        );
17450    }
17451
17452    None
17453}
17454
17455fn rubi_cancel(expr: &Atom) -> Atom {
17456    let cancelled = expr.expand().cancel();
17457    rubi_cancel_integer_polynomial_content(&cancelled).unwrap_or(cancelled)
17458}
17459
17460fn rubi_cancel_integer_polynomial_content(expr: &Atom) -> Option<Atom> {
17461    let variables = expr.get_all_symbols(false);
17462    let x = variables
17463        .into_iter()
17464        .find(|symbol| !is_free_of(expr, *symbol))?;
17465    let (numerator, denominator) = rational_numerator_denominator(expr)?;
17466    if denominator.is_one() {
17467        return None;
17468    }
17469
17470    let numerator_content = polynomial_integer_content(&numerator, x)?;
17471    let denominator_content = polynomial_integer_content(&denominator, x)?;
17472    let content = integer_gcd(numerator_content, denominator_content);
17473    if content <= 1 {
17474        return None;
17475    }
17476
17477    Some((numerator / Atom::num(content)).expand() / (denominator / Atom::num(content)).expand())
17478}
17479
17480fn polynomial_integer_content(expr: &Atom, x: Symbol) -> Option<i64> {
17481    let terms = collect_polynomial_terms(expr, x)?;
17482    let mut content = 0;
17483    for coefficient in terms.values() {
17484        content = integer_gcd(content, coefficient_integer_factor(coefficient)?);
17485    }
17486    Some(content)
17487}
17488
17489fn coefficient_integer_factor(expr: &Atom) -> Option<i64> {
17490    if let Some((numerator, denominator)) = rational_number(expr) {
17491        return (denominator == 1).then_some(numerator.abs());
17492    }
17493
17494    let AtomView::Mul(mul) = expr.as_view() else {
17495        return Some(1);
17496    };
17497    for factor in mul {
17498        if let Some((numerator, denominator)) = rational_number_view(factor) {
17499            return (denominator == 1).then_some(numerator.abs());
17500        }
17501    }
17502    Some(1)
17503}
17504
17505fn rubi_d(expr: &Atom, x: Symbol) -> Atom {
17506    rubi_differentiate(expr, x)
17507}
17508
17509fn rubi_product_of_linear_powers_q(expr: AtomView<'_>, x: Symbol) -> bool {
17510    fn linear_power_q(factor: AtomView<'_>, x: Symbol) -> bool {
17511        let (base, exponent) = match factor {
17512            AtomView::Pow(power) => {
17513                let (base, exponent) = power.get_base_exp();
17514                (base, Some(exponent))
17515            }
17516            _ => (factor, None),
17517        };
17518
17519        rubi_linear_q(base, x) && exponent.is_none_or(|exponent| is_free_of(exponent, x))
17520    }
17521
17522    if is_free_of(expr, x) {
17523        return true;
17524    }
17525
17526    match expr {
17527        AtomView::Mul(mul) => mul
17528            .into_iter()
17529            .filter(|factor| !is_free_of(*factor, x))
17530            .all(|factor| linear_power_q(factor, x)),
17531        _ => linear_power_q(expr, x),
17532    }
17533}
17534
17535fn rubi_easy_dq(expr: AtomView<'_>, x: Symbol) -> bool {
17536    // EasyDQ[u_.*x_^m_.,x] := EasyDQ[u,x] /; FreeQ[m,x]
17537    if let AtomView::Mul(mul) = expr {
17538        let factors = mul.into_iter().collect::<Vec<_>>();
17539        if let Some(index) = factors.iter().position(|factor| match factor {
17540            AtomView::Var(variable) => variable.get_symbol() == x,
17541            AtomView::Pow(power) => {
17542                let (base, exponent) = power.get_base_exp();
17543                matches!(base, AtomView::Var(variable) if variable.get_symbol() == x)
17544                    && is_free_of(exponent, x)
17545            }
17546            _ => false,
17547        }) {
17548            let remainder: Atom = factors
17549                .into_iter()
17550                .enumerate()
17551                .filter(|(factor_index, _)| *factor_index != index)
17552                .map(|(_, factor)| factor.to_owned())
17553                .product();
17554            return rubi_easy_dq(remainder.as_view(), x);
17555        }
17556    }
17557
17558    if atom_q(expr) || is_free_of(expr, x) {
17559        return true;
17560    }
17561
17562    if rubi_binomial_q(expr, x) || rubi_product_of_linear_powers_q(expr, x) {
17563        return true;
17564    }
17565
17566    if rubi_rational_function_exponents(expr, x).is_some_and(|exponents| exponents == (1, 1)) {
17567        return true;
17568    }
17569
17570    match expr {
17571        AtomView::Pow(power) => {
17572            let (base, exponent) = power.get_base_exp();
17573            if is_free_of(base, x) {
17574                rubi_easy_dq(exponent, x)
17575            } else if is_free_of(exponent, x) {
17576                rubi_easy_dq(base, x)
17577            } else {
17578                false
17579            }
17580        }
17581        AtomView::Mul(mul) => {
17582            let nonfree: Vec<_> = mul
17583                .into_iter()
17584                .filter(|factor| !is_free_of(*factor, x))
17585                .collect();
17586            nonfree.len() == 1 && rubi_easy_dq(nonfree[0], x)
17587        }
17588        AtomView::Add(add) => add.into_iter().all(|term| rubi_easy_dq(term, x)),
17589        AtomView::Fun(function) => {
17590            if function.get_nargs() != 1 {
17591                return false;
17592            }
17593            rubi_easy_dq(function.get(0), x)
17594        }
17595        AtomView::Num(_) | AtomView::Var(_) => true,
17596    }
17597}
17598
17599fn rubi_derivative_divides(y: &Atom, u: &Atom, x: Symbol) -> Option<Atom> {
17600    if rubi_optional_free_coefficient_times_x_q(y, x) {
17601        return None;
17602    }
17603
17604    let polynomial_case = poly_q(y, x);
17605    let derivative_allowed = if polynomial_case {
17606        poly_q(u, x)
17607            && polynomial_degree(u, x)
17608                .zip(polynomial_degree(y, x))
17609                .is_some_and(|(u_degree, y_degree)| u_degree == y_degree - 1)
17610    } else {
17611        rubi_easy_dq(y.as_view(), x)
17612    };
17613
17614    if !derivative_allowed {
17615        return None;
17616    }
17617
17618    let derivative = rubi_d(y, x);
17619    if eqq!(derivative, 0) {
17620        return None;
17621    }
17622    if polynomial_case {
17623        return rubi_polynomial_proportional_factor(u, &derivative, x);
17624    }
17625
17626    let raw_quotient = u / &derivative;
17627    if freeq!(raw_quotient, x) {
17628        return Some(raw_quotient);
17629    }
17630
17631    let together_quotient = raw_quotient.together();
17632    if freeq!(together_quotient, x) {
17633        return Some(together_quotient);
17634    }
17635    let algebraic_quotient = rubi_algebraic_function_q(&together_quotient, x, false);
17636    if algebraic_quotient
17637        && rubi_contains_imaginary_unit(&together_quotient)
17638        && let Some(factored_quotient) = rubi_try_factor(together_quotient.as_view())
17639    {
17640        let normalized_factored_quotient = factored_quotient.together();
17641        if freeq!(normalized_factored_quotient, x) {
17642            return Some(normalized_factored_quotient);
17643        }
17644        if let Some((numerator, denominator)) = rational_numerator_denominator(&factored_quotient) {
17645            let normalized_quotient = (numerator / denominator.together()).together();
17646            if freeq!(normalized_quotient, x) {
17647                return Some(normalized_quotient);
17648            }
17649        }
17650    }
17651    // Mathematica preserves a quotient power in u, so Simplify can cancel it
17652    // against the identical power produced by D. Symbolica may canonicalize u
17653    // first (for example, (A/C)^n/(A*C) to A^(n-1)*C^(-n-1)) while retaining
17654    // (A/C)^(n-1) in D. Formally distribute only product-base powers to put
17655    // both sides in the same canonical form, then use the result solely as an
17656    // x-free proof for DerivativeDivides.
17657    let formal_power_quotient =
17658        rubi_formally_distribute_product_powers(together_quotient.as_view());
17659    if freeq!(formal_power_quotient, x) {
17660        return Some(formal_power_quotient);
17661    }
17662    if algebraic_quotient
17663        && rubi_fractional_power_bases_are_variable_q(together_quotient.as_view(), x)
17664    {
17665        return None;
17666    }
17667
17668    let quotient = rubi_simplify(&raw_quotient);
17669    let mut candidates = vec![
17670        quotient.to_owned(),
17671        quotient.expand().cancel(),
17672        quotient.together(),
17673    ];
17674    if let Some(evaluated) = rubi_mathematica_evaluate_integrand(&quotient) {
17675        candidates.insert(0, evaluated);
17676    }
17677    if ["sinh", "cosh", "tanh", "coth", "sech", "csch"]
17678        .iter()
17679        .any(|name| rubi_contains_function_name(&quotient, name))
17680    {
17681        candidates.insert(
17682            0,
17683            rubi_hyperbolic_trig_to_exp(quotient.as_view()).together(),
17684        );
17685    }
17686    for candidate in candidates {
17687        if freeq!(candidate, x) {
17688            return Some(candidate);
17689        }
17690        if let Some(simplified) =
17691            rubi_simplify_integrand_mathematica_simplify_candidate(&candidate, x)
17692        {
17693            if freeq!(simplified, x) {
17694                return Some(simplified);
17695            }
17696        }
17697    }
17698
17699    if rubi_derivative_quotient_one_q(u, &derivative) {
17700        return Some(Atom::num(1));
17701    }
17702
17703    None
17704}
17705
17706fn rubi_optional_free_coefficient_times_x_q(expr: &Atom, x: Symbol) -> bool {
17707    match expr.as_view() {
17708        AtomView::Var(variable) => variable.get_symbol() == x,
17709        AtomView::Mul(mul) => {
17710            let mut saw_x = false;
17711            for factor in mul {
17712                if matches!(factor, AtomView::Var(variable) if variable.get_symbol() == x) {
17713                    if saw_x {
17714                        return false;
17715                    }
17716                    saw_x = true;
17717                } else if !is_free_of(factor, x) {
17718                    return false;
17719                }
17720            }
17721            saw_x
17722        }
17723        _ => false,
17724    }
17725}
17726
17727fn rubi_contains_imaginary_unit(expr: &Atom) -> bool {
17728    fn recur(expr: AtomView<'_>, imaginary_unit: AtomView<'_>) -> bool {
17729        if expr == imaginary_unit {
17730            return true;
17731        }
17732        match expr {
17733            AtomView::Fun(function) => function
17734                .into_iter()
17735                .any(|argument| recur(argument, imaginary_unit)),
17736            AtomView::Add(add) => add.into_iter().any(|term| recur(term, imaginary_unit)),
17737            AtomView::Mul(mul) => mul.into_iter().any(|factor| recur(factor, imaginary_unit)),
17738            AtomView::Pow(power) => {
17739                recur(power.get_base(), imaginary_unit) || recur(power.get_exp(), imaginary_unit)
17740            }
17741            AtomView::Num(_) | AtomView::Var(_) => false,
17742        }
17743    }
17744
17745    let imaginary_unit = Atom::i();
17746    recur(expr.as_view(), imaginary_unit.as_view())
17747}
17748
17749fn rubi_formally_distribute_product_powers(expr: AtomView<'_>) -> Atom {
17750    match expr {
17751        AtomView::Pow(power) => {
17752            let base = rubi_formally_distribute_product_powers(power.get_base());
17753            let exponent = rubi_formally_distribute_product_powers(power.get_exp());
17754            if let AtomView::Mul(product) = base.as_view() {
17755                product
17756                    .into_iter()
17757                    .map(|factor| {
17758                        let power = factor.to_owned().pow(&exponent);
17759                        rubi_formally_distribute_product_powers(power.as_view())
17760                    })
17761                    .product()
17762            } else if let AtomView::Pow(inner_power) = base.as_view()
17763                && integer_i64_view(inner_power.get_exp()).is_some()
17764            {
17765                inner_power
17766                    .get_base()
17767                    .to_owned()
17768                    .pow(inner_power.get_exp().to_owned() * exponent)
17769            } else {
17770                base.pow(exponent)
17771            }
17772        }
17773        AtomView::Add(add) => add
17774            .into_iter()
17775            .map(rubi_formally_distribute_product_powers)
17776            .sum(),
17777        AtomView::Mul(mul) => mul
17778            .into_iter()
17779            .map(rubi_formally_distribute_product_powers)
17780            .product(),
17781        AtomView::Fun(function) => function.get_symbol().call_args(
17782            function
17783                .into_iter()
17784                .map(rubi_formally_distribute_product_powers)
17785                .collect::<Vec<_>>(),
17786        ),
17787        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
17788    }
17789}
17790
17791fn rubi_derivative_quotient_one_q(u: &Atom, derivative: &Atom) -> bool {
17792    for residual in [
17793        u - derivative,
17794        rubi_simplify(&(u - derivative)),
17795        (u - derivative).expand().cancel(),
17796        (u - derivative).together(),
17797    ] {
17798        if residual.is_zero() || rubi_sqrt_product_sum_zero_q(&residual) {
17799            return true;
17800        }
17801    }
17802
17803    false
17804}
17805
17806fn rubi_sqrt_product_sum_zero_q(expr: &Atom) -> bool {
17807    let mut saw_sqrt = false;
17808    let mut terms = Vec::new();
17809    let mut minimum_exponents: BTreeMap<String, (Atom, i64)> = BTreeMap::new();
17810
17811    for term in rubi_add_terms(expr) {
17812        let Some((coefficient, exponents, term_saw_sqrt)) = rubi_sqrt_product_term(&term) else {
17813            return false;
17814        };
17815        saw_sqrt |= term_saw_sqrt;
17816        for (key, (base, exponent)) in &exponents {
17817            minimum_exponents
17818                .entry(key.to_owned())
17819                .and_modify(|(_, minimum)| *minimum = (*minimum).min(*exponent).min(0))
17820                .or_insert_with(|| (base.to_owned(), (*exponent).min(0)));
17821        }
17822        terms.push((coefficient, exponents));
17823    }
17824
17825    if !saw_sqrt {
17826        return false;
17827    }
17828
17829    let mut coefficients_by_basis: BTreeMap<Vec<String>, Atom> = BTreeMap::new();
17830    for (mut coefficient, exponents) in terms {
17831        let mut basis = Vec::new();
17832        for (key, (base, minimum)) in &minimum_exponents {
17833            let exponent = exponents
17834                .get(key)
17835                .map(|(_, exponent)| *exponent)
17836                .unwrap_or(0);
17837            let shifted = exponent - minimum;
17838            if shifted < 0 {
17839                return false;
17840            }
17841            let polynomial_power = shifted / 2;
17842            if polynomial_power > 0 {
17843                coefficient *= base.pow(polynomial_power);
17844            }
17845            if shifted % 2 != 0 {
17846                basis.push(key.to_owned());
17847            }
17848        }
17849
17850        coefficients_by_basis
17851            .entry(basis)
17852            .and_modify(|sum| *sum += &coefficient)
17853            .or_insert(coefficient);
17854    }
17855
17856    coefficients_by_basis.into_values().all(|coefficient| {
17857        [
17858            coefficient.to_owned(),
17859            rubi_simplify(&coefficient),
17860            coefficient.expand().cancel(),
17861            coefficient.together(),
17862            rubi_simplify(&coefficient).together(),
17863        ]
17864        .into_iter()
17865        .any(|candidate| candidate.is_zero() || rubi_simplify(&candidate).is_zero())
17866    })
17867}
17868
17869fn rubi_sqrt_product_term(term: &Atom) -> Option<(Atom, BTreeMap<String, (Atom, i64)>, bool)> {
17870    let mut coefficient = Atom::num(1);
17871    let mut exponents: BTreeMap<String, (Atom, i64)> = BTreeMap::new();
17872    let mut saw_sqrt = false;
17873
17874    for factor in rubi_product_factors(term) {
17875        if let Some((base, exponent)) = rubi_sqrt_half_power(&factor) {
17876            saw_sqrt = true;
17877            let key = base.to_string();
17878            exponents
17879                .entry(key)
17880                .and_modify(|(_, existing)| *existing += exponent)
17881                .or_insert((base, exponent));
17882        } else {
17883            coefficient *= factor;
17884        }
17885    }
17886
17887    Some((coefficient, exponents, saw_sqrt))
17888}
17889
17890fn rubi_sqrt_half_power(expr: &Atom) -> Option<(Atom, i64)> {
17891    let AtomView::Pow(power) = expr.as_view() else {
17892        return None;
17893    };
17894
17895    let (base, exponent) = power.get_base_exp();
17896    let exponent = exponent.to_owned();
17897    if let Some((numerator, denominator)) = rational_number(&exponent) {
17898        if denominator == 2 && numerator % 2 != 0 {
17899            return Some((base.to_owned(), numerator));
17900        }
17901    }
17902
17903    if let Some(integer) = integer_i64(&exponent) {
17904        if let Some((sqrt_base, half_exponent)) = rubi_sqrt_half_power(&base.to_owned()) {
17905            return Some((sqrt_base, half_exponent * integer));
17906        }
17907    }
17908
17909    None
17910}
17911
17912#[allow(dead_code)]
17913fn rubi_expand_to_sum_product(u: &Atom, v: &Atom, x: Symbol) -> Atom {
17914    let w = rubi_expand_to_sum(v, x);
17915    let (free_terms, nonfree_terms) = rubi_free_nonfree_terms(&w, x);
17916    let mut expanded = if free_terms.is_zero() {
17917        Atom::num(0)
17918    } else {
17919        u * free_terms
17920    };
17921
17922    if nonfree_terms.len() == 1 {
17923        expanded += rubi_merge_monomials(&(u * &nonfree_terms[0]), x);
17924    } else {
17925        for term in nonfree_terms {
17926            expanded += rubi_merge_monomials(&(u * term), x);
17927        }
17928    }
17929
17930    expanded.expand()
17931}
17932
17933fn rubi_expand_linear_product(
17934    v: impl RubiAtomArgument,
17935    u: impl RubiAtomArgument,
17936    a: &Atom,
17937    b: &Atom,
17938    x: Symbol,
17939) -> Option<Atom> {
17940    let v = v.into_rubi_atom();
17941    let u = u.into_rubi_atom();
17942    if !is_free_of((a, b), x) || b.is_zero() || !poly_q(&u, x) {
17943        return None;
17944    }
17945
17946    let x_atom = Atom::var(x);
17947    let shifted = substitute_symbol(&u, x, (&x_atom - a) / b);
17948    let terms = collect_polynomial_terms(&shifted, x)?;
17949    let linear = a + b * &x_atom;
17950    let mut sum = Atom::num(0);
17951    for (degree, coefficient) in terms {
17952        if coefficient.expand().is_zero() {
17953            continue;
17954        }
17955
17956        sum += &v * rubi_simp(&coefficient, x) * linear.pow(degree);
17957    }
17958
17959    Some(sum)
17960}
17961
17962fn rubi_free_nonfree_terms(expr: &Atom, x: Symbol) -> (Atom, Vec<Atom>) {
17963    let mut free_terms = Atom::num(0);
17964    let mut nonfree_terms = Vec::new();
17965
17966    match expr.as_view() {
17967        AtomView::Add(add) => {
17968            for term in add {
17969                let term = term.to_owned();
17970                if is_free_of(&term, x) {
17971                    free_terms += term;
17972                } else {
17973                    nonfree_terms.push(term);
17974                }
17975            }
17976        }
17977        _ if is_free_of(expr, x) => {
17978            free_terms = expr.to_owned();
17979        }
17980        _ => nonfree_terms.push(expr.to_owned()),
17981    }
17982
17983    (free_terms, nonfree_terms)
17984}
17985
17986fn rubi_merge_monomials(expr: &Atom, x: Symbol) -> Atom {
17987    if let Some(merged) = rubi_merge_monomials_linear_powers(expr, x) {
17988        return merged;
17989    }
17990
17991    if rubi_linear_q(expr.as_view(), x) {
17992        rubi_cancel(expr)
17993    } else {
17994        expr.to_owned()
17995    }
17996}
17997
17998fn rubi_merge_monomials_linear_powers(expr: &Atom, x: Symbol) -> Option<Atom> {
17999    let factors = match expr.as_view() {
18000        AtomView::Mul(mul) => mul
18001            .into_iter()
18002            .map(|factor| factor.to_owned())
18003            .collect::<Vec<_>>(),
18004        _ => return None,
18005    };
18006
18007    for left_index in 0..factors.len() {
18008        let (left_base, left_exponent) = rubi_factor_base_exponent(&factors[left_index]);
18009        if !integerq!(left_exponent) {
18010            continue;
18011        }
18012        let Some((left_constant, left_slope)) = linear_coefficients(left_base.as_view(), x) else {
18013            continue;
18014        };
18015        if left_slope.is_zero() {
18016            continue;
18017        }
18018
18019        for right_index in 0..factors.len() {
18020            if left_index == right_index {
18021                continue;
18022            }
18023            let (right_base, right_exponent) = rubi_factor_base_exponent(&factors[right_index]);
18024            let Some((right_constant, right_slope)) = linear_coefficients(right_base.as_view(), x)
18025            else {
18026                continue;
18027            };
18028            if right_slope.is_zero() {
18029                continue;
18030            }
18031            if !eqq!(
18032                &left_slope * &right_constant - &left_constant * &right_slope,
18033                0
18034            ) {
18035                continue;
18036            }
18037
18038            let denominator = right_slope.pow(&left_exponent);
18039            if denominator.is_zero() {
18040                continue;
18041            }
18042
18043            let mut rest = Vec::with_capacity(factors.len().saturating_sub(2) + 2);
18044            for (index, factor) in factors.iter().enumerate() {
18045                if index != left_index && index != right_index {
18046                    rest.push(factor.to_owned());
18047                }
18048            }
18049            rest.push(left_slope.pow(&left_exponent) / denominator);
18050            rest.push(right_base.pow(left_exponent + right_exponent));
18051            return Some(product_atoms(&rest));
18052        }
18053    }
18054
18055    None
18056}
18057
18058fn rubi_factor_base_exponent(factor: &Atom) -> (Atom, Atom) {
18059    match factor.as_view() {
18060        AtomView::Pow(power) => {
18061            let (base, exponent) = power.get_base_exp();
18062            (base.to_owned(), exponent.to_owned())
18063        }
18064        _ => (factor.to_owned(), Atom::num(1)),
18065    }
18066}
18067
18068fn rational_numerator_denominator(expr: &Atom) -> Option<(Atom, Atom)> {
18069    let (numerator, denominator) = rational_numerator_denominator_unexpanded(expr)?;
18070    Some((numerator.expand(), denominator.expand()))
18071}
18072
18073fn rational_numerator_denominator_unexpanded(expr: &Atom) -> Option<(Atom, Atom)> {
18074    let mut numerator = Atom::num(1);
18075    let mut denominator = Atom::num(1);
18076    collect_rational_factors(expr.as_view(), &mut numerator, &mut denominator)?;
18077    Some((numerator, denominator))
18078}
18079
18080fn collect_rational_factors(
18081    expr: AtomView<'_>,
18082    numerator: &mut Atom,
18083    denominator: &mut Atom,
18084) -> Option<()> {
18085    match expr {
18086        AtomView::Mul(mul) => {
18087            for factor in mul {
18088                collect_rational_factors(factor, numerator, denominator)?;
18089            }
18090        }
18091        AtomView::Pow(power) => {
18092            let (base, exponent) = power.get_base_exp();
18093            let exponent = exponent.to_owned();
18094            if let Some(integer) = integer_i64(&exponent) {
18095                if integer < 0 {
18096                    *denominator *= base.to_owned().pow(-integer);
18097                } else {
18098                    *numerator *= base.to_owned().pow(integer);
18099                }
18100            } else {
18101                *numerator *= expr.to_owned();
18102            }
18103        }
18104        AtomView::Num(_) => {
18105            let number = expr.to_owned();
18106            if let Some((number_numerator, number_denominator)) = rational_number(&number) {
18107                *numerator *= Atom::num(number_numerator);
18108                *denominator *= Atom::num(number_denominator);
18109            } else {
18110                *numerator *= number;
18111            }
18112        }
18113        _ => *numerator *= expr.to_owned(),
18114    }
18115
18116    Some(())
18117}
18118
18119fn add_polynomial_term(terms: &mut BTreeMap<i64, Atom>, degree: i64, coefficient: Atom) {
18120    let updated = terms
18121        .remove(&degree)
18122        .map(|existing| existing + &coefficient)
18123        .unwrap_or(coefficient);
18124    // Mathematica's polynomial routines perform coefficient arithmetic over
18125    // the rational function field. Together is required here so subtracting a
18126    // leading term actually removes it when the coefficient is symbolic.
18127    let updated = updated.together();
18128    if !polynomial_coefficient_zero_q(&updated) {
18129        terms.insert(degree, updated);
18130    }
18131}
18132
18133fn polynomial_coefficient_zero_q(coefficient: &Atom) -> bool {
18134    coefficient.is_zero()
18135        || (coefficient.to_string().len() <= 512 && rubi_algebraic_zero_q(coefficient))
18136}
18137
18138fn polynomial_from_terms(terms: &BTreeMap<i64, Atom>, x: Symbol) -> Atom {
18139    let variable = Atom::var(x);
18140    let mut polynomial = Atom::num(0);
18141    for (degree, coefficient) in terms {
18142        if coefficient.is_zero() {
18143            continue;
18144        }
18145        if *degree == 0 {
18146            polynomial += coefficient;
18147        } else {
18148            polynomial += coefficient * variable.pow(degree);
18149        }
18150    }
18151
18152    polynomial
18153}
18154
18155fn collect_polynomial_terms(expr: &Atom, x: Symbol) -> Option<BTreeMap<i64, Atom>> {
18156    let expanded = rubi_mathematica_expand(expr, Some(x));
18157    collect_polynomial_terms_without_expanding(&expanded, x)
18158}
18159
18160fn rubi_polynomial_terms(expr: &Atom, x: Symbol) -> Option<BTreeMap<i64, Atom>> {
18161    collect_polynomial_terms(expr, x).or_else(|| {
18162        let together = expr.together();
18163        collect_polynomial_terms(&together, x)
18164    })
18165}
18166
18167fn collect_polynomial_terms_without_expanding(
18168    expr: &Atom,
18169    x: Symbol,
18170) -> Option<BTreeMap<i64, Atom>> {
18171    collect_polynomial_terms_without_expanding_view(expr.as_view(), x)
18172}
18173
18174fn collect_polynomial_terms_without_expanding_view(
18175    expr: AtomView<'_>,
18176    x: Symbol,
18177) -> Option<BTreeMap<i64, Atom>> {
18178    let mut terms = BTreeMap::new();
18179    match expr {
18180        AtomView::Add(add) => {
18181            for term in add {
18182                let (degree, coefficient) = polynomial_term(term, x)?;
18183                terms
18184                    .entry(degree)
18185                    .and_modify(|existing: &mut Atom| *existing = &*existing + &coefficient)
18186                    .or_insert(coefficient);
18187            }
18188        }
18189        term => {
18190            let (degree, coefficient) = polynomial_term(term, x)?;
18191            terms.insert(degree, coefficient);
18192        }
18193    }
18194
18195    Some(terms)
18196}
18197
18198fn polynomial_term(term: AtomView<'_>, x: Symbol) -> Option<(i64, Atom)> {
18199    if is_free_of(term, x) {
18200        return Some((0, term.to_owned()));
18201    }
18202
18203    match term {
18204        AtomView::Var(variable) if variable.get_symbol() == x => Some((1, Atom::num(1))),
18205        AtomView::Pow(power) => {
18206            let (base, exponent) = power.get_base_exp();
18207            match base {
18208                AtomView::Var(variable) if variable.get_symbol() == x => {
18209                    let degree = integer_i64_view(exponent)?;
18210                    if degree >= 0 {
18211                        Some((degree, Atom::num(1)))
18212                    } else {
18213                        None
18214                    }
18215                }
18216                _ => None,
18217            }
18218        }
18219        AtomView::Mul(mul) => {
18220            let mut degree = 0_i64;
18221            let mut coefficient = Atom::num(1);
18222            for factor in mul {
18223                if is_free_of(factor, x) {
18224                    coefficient *= factor.to_owned();
18225                    continue;
18226                }
18227
18228                match factor {
18229                    AtomView::Var(variable) if variable.get_symbol() == x => {
18230                        degree = degree.checked_add(1)?;
18231                    }
18232                    AtomView::Pow(power) => {
18233                        let (base, exponent) = power.get_base_exp();
18234                        match base {
18235                            AtomView::Var(variable) if variable.get_symbol() == x => {
18236                                let factor_degree = integer_i64_view(exponent)?;
18237                                if factor_degree < 0 {
18238                                    return None;
18239                                }
18240                                degree = degree.checked_add(factor_degree)?;
18241                            }
18242                            _ => return None,
18243                        }
18244                    }
18245                    _ => return None,
18246                }
18247            }
18248
18249            Some((degree, coefficient))
18250        }
18251        _ => None,
18252    }
18253}
18254
18255fn laurent_monomial_term(term: AtomView<'_>, x: Symbol) -> Option<(i64, Atom)> {
18256    if is_free_of(term, x) {
18257        return Some((0, term.to_owned()));
18258    }
18259
18260    match term {
18261        AtomView::Var(variable) if variable.get_symbol() == x => Some((1, Atom::num(1))),
18262        AtomView::Pow(power) => {
18263            let (base, exponent) = power.get_base_exp();
18264            match base {
18265                AtomView::Var(variable) if variable.get_symbol() == x => {
18266                    Some((integer_i64_view(exponent)?, Atom::num(1)))
18267                }
18268                _ => None,
18269            }
18270        }
18271        AtomView::Mul(mul) => {
18272            let mut degree = 0_i64;
18273            let mut coefficient = Atom::num(1);
18274            for factor in mul {
18275                if is_free_of(factor, x) {
18276                    coefficient *= factor.to_owned();
18277                    continue;
18278                }
18279
18280                match factor {
18281                    AtomView::Var(variable) if variable.get_symbol() == x => {
18282                        degree = degree.checked_add(1)?;
18283                    }
18284                    AtomView::Pow(power) => {
18285                        let (base, exponent) = power.get_base_exp();
18286                        match base {
18287                            AtomView::Var(variable) if variable.get_symbol() == x => {
18288                                degree = degree.checked_add(integer_i64_view(exponent)?)?;
18289                            }
18290                            _ => return None,
18291                        }
18292                    }
18293                    _ => return None,
18294                }
18295            }
18296
18297            Some((degree, coefficient))
18298        }
18299        _ => None,
18300    }
18301}
18302
18303fn collect_laurent_terms(expr: &Atom, x: Symbol) -> Option<BTreeMap<i64, Atom>> {
18304    let expanded = expr.expand();
18305    let mut terms = BTreeMap::new();
18306    match expanded.as_view() {
18307        AtomView::Add(add) => {
18308            for term in add {
18309                let (degree, coefficient) = laurent_monomial_term(term, x)?;
18310                add_polynomial_term(&mut terms, degree, coefficient);
18311            }
18312        }
18313        term => {
18314            let (degree, coefficient) = laurent_monomial_term(term, x)?;
18315            add_polynomial_term(&mut terms, degree, coefficient);
18316        }
18317    }
18318
18319    Some(terms)
18320}
18321
18322#[cfg(test)]
18323fn integrate_laurent_polynomial(expr: &Atom, x: Symbol) -> Option<Atom> {
18324    let expanded = expr.expand();
18325    let mut primitive = Atom::num(0);
18326    let variable = Atom::var(x);
18327
18328    match expanded.as_view() {
18329        AtomView::Add(add) => {
18330            for term in add {
18331                let (degree, coefficient) = laurent_monomial_term(term, x)?;
18332                primitive += integrate_laurent_monomial(degree, coefficient, variable.to_owned());
18333            }
18334        }
18335        term => {
18336            let (degree, coefficient) = laurent_monomial_term(term, x)?;
18337            primitive += integrate_laurent_monomial(degree, coefficient, variable);
18338        }
18339    }
18340
18341    #[cfg(feature = "trace")]
18342    trace_direct_polynomial_integration("integrate_laurent_polynomial", expr);
18343    Some(primitive)
18344}
18345
18346#[cfg(test)]
18347fn integrate_laurent_monomial(degree: i64, coefficient: Atom, variable: Atom) -> Atom {
18348    if degree == -1 {
18349        coefficient * variable.log()
18350    } else {
18351        coefficient * variable.pow(degree + 1) / Atom::num(degree + 1)
18352    }
18353}
18354
18355fn visible_integer_power_of_variable_factor<T: AtomCore>(expr: T, x: Symbol) -> bool {
18356    let expr = expr.as_atom_view();
18357    fn is_visible_factor(factor: AtomView<'_>, x: Symbol) -> bool {
18358        match factor {
18359            AtomView::Var(variable) if variable.get_symbol() == x => true,
18360            AtomView::Pow(power) => {
18361                let (base, exponent) = power.get_base_exp();
18362                matches!(base, AtomView::Var(variable) if variable.get_symbol() == x)
18363                    && integer_i64_view(exponent).is_some()
18364            }
18365            _ => false,
18366        }
18367    }
18368
18369    if is_visible_factor(expr, x) {
18370        return true;
18371    }
18372
18373    match expr {
18374        AtomView::Mul(mul) => mul.into_iter().any(|factor| is_visible_factor(factor, x)),
18375        _ => false,
18376    }
18377}
18378
18379fn atom_q(expr: AtomView<'_>) -> bool {
18380    matches!(expr, AtomView::Num(_) | AtomView::Var(_))
18381}
18382
18383fn rubi_sum_q(expr: &Atom) -> bool {
18384    matches!(expr.as_view(), AtomView::Add(_))
18385}
18386
18387fn rubi_product_q(expr: &Atom) -> bool {
18388    matches!(expr.as_view(), AtomView::Mul(_))
18389}
18390
18391fn rubi_power_q(expr: &Atom) -> bool {
18392    matches!(expr.as_view(), AtomView::Pow(_))
18393}
18394
18395fn rubi_odd_q(expr: &Atom) -> bool {
18396    integer_i64(expr).is_some_and(|value| value % 2 != 0)
18397}
18398
18399fn rubi_contains_noninteger_power(expr: AtomView<'_>) -> bool {
18400    match expr {
18401        AtomView::Pow(power) => {
18402            integer_i64_view(power.get_exp()).is_none()
18403                || rubi_contains_noninteger_power(power.get_base())
18404        }
18405        AtomView::Add(add) => add.into_iter().any(rubi_contains_noninteger_power),
18406        AtomView::Mul(mul) => mul.into_iter().any(rubi_contains_noninteger_power),
18407        AtomView::Fun(function) => function.into_iter().any(rubi_contains_noninteger_power),
18408        AtomView::Num(_) | AtomView::Var(_) => false,
18409    }
18410}
18411
18412fn rubi_monomial_exponents(term: AtomView<'_>) -> Option<BTreeMap<String, i64>> {
18413    fn add_factor(factor: AtomView<'_>, exponents: &mut BTreeMap<String, i64>) -> Option<()> {
18414        match factor {
18415            AtomView::Num(_) => Some(()),
18416            AtomView::Var(variable) => {
18417                *exponents
18418                    .entry(Atom::var(variable.get_symbol()).to_string())
18419                    .or_default() += 1;
18420                Some(())
18421            }
18422            AtomView::Pow(power) => {
18423                let AtomView::Var(variable) = power.get_base() else {
18424                    return None;
18425                };
18426                let exponent = integer_i64_view(power.get_exp())?;
18427                if exponent < 0 {
18428                    return None;
18429                }
18430                *exponents
18431                    .entry(Atom::var(variable.get_symbol()).to_string())
18432                    .or_default() += exponent;
18433                Some(())
18434            }
18435            AtomView::Mul(product) => {
18436                for factor in product {
18437                    add_factor(factor, exponents)?;
18438                }
18439                Some(())
18440            }
18441            AtomView::Add(_) | AtomView::Fun(_) => None,
18442        }
18443    }
18444
18445    let mut exponents = BTreeMap::new();
18446    add_factor(term, &mut exponents)?;
18447    Some(exponents)
18448}
18449
18450fn rubi_mathematica_monomial_cmp(left: AtomView<'_>, right: AtomView<'_>) -> Ordering {
18451    match (
18452        rubi_monomial_exponents(left),
18453        rubi_monomial_exponents(right),
18454    ) {
18455        (Some(left), Some(right)) => {
18456            let mut symbols = left.keys().chain(right.keys()).collect::<Vec<_>>();
18457            symbols.sort_unstable();
18458            symbols.dedup();
18459            for symbol in symbols.into_iter().rev() {
18460                let ordering = left
18461                    .get(symbol)
18462                    .copied()
18463                    .unwrap_or(0)
18464                    .cmp(&right.get(symbol).copied().unwrap_or(0));
18465                if ordering != Ordering::Equal {
18466                    return ordering;
18467                }
18468            }
18469            Ordering::Equal
18470        }
18471        (Some(_), None) => Ordering::Less,
18472        (None, Some(_)) => Ordering::Greater,
18473        (None, None) => right.cmp(&left),
18474    }
18475}
18476
18477fn rubi_mathematica_first_sum_term(expr: &Atom) -> Option<Atom> {
18478    let AtomView::Add(add) = expr.as_view() else {
18479        return None;
18480    };
18481    let terms = add.into_iter().collect::<Vec<_>>();
18482
18483    terms
18484        .iter()
18485        .copied()
18486        .find(|term| matches!(*term, AtomView::Num(_)))
18487        .or_else(|| {
18488            terms
18489                .iter()
18490                .copied()
18491                .filter(|term| !rubi_contains_noninteger_power(*term))
18492                .min_by(|left, right| rubi_mathematica_monomial_cmp(*left, *right))
18493        })
18494        .or_else(|| terms.first().copied())
18495        .map(|term| term.to_owned())
18496}
18497
18498fn rubi_mathematica_first_sum_term_in(expr: &Atom, x: Symbol) -> Option<Atom> {
18499    let AtomView::Add(add) = expr.as_view() else {
18500        return None;
18501    };
18502    let terms = add
18503        .into_iter()
18504        .map(|term| term.to_owned())
18505        .collect::<Vec<_>>();
18506
18507    if terms.iter().all(|term| {
18508        let dependent = rubi_nonfree_factors(term, x);
18509        let AtomView::Pow(power) = dependent.as_view() else {
18510            return false;
18511        };
18512        rubi_linear_q(power.get_base(), x)
18513            && rational_number_view(power.get_exp()).is_some_and(|(_, denominator)| denominator > 1)
18514    }) {
18515        // Mathematica orders these terms by their x-dependent kernels before
18516        // applying RemoveContentAux. Symbolica's free algebraic coefficient
18517        // participates in its Add order and reverses this particular choice.
18518        return terms.into_iter().max_by(|left, right| {
18519            rubi_nonfree_factors(left, x).cmp(&rubi_nonfree_factors(right, x))
18520        });
18521    }
18522
18523    rubi_mathematica_first_sum_term(expr)
18524}
18525
18526fn rubi_pos_q(expr: &Atom) -> bool {
18527    fn pos_aux(expr: &Atom) -> bool {
18528        if let Some((numerator, denominator)) = rational_number(expr) {
18529            return numerator * denominator > 0;
18530        }
18531
18532        match expr.as_view() {
18533            AtomView::Pow(power) => {
18534                let (base, exponent) = power.get_base_exp();
18535                let exponent = exponent.to_owned();
18536                if let Some(exponent) = integer_i64(&exponent) {
18537                    exponent % 2 == 0 || pos_aux(&base.to_owned())
18538                } else {
18539                    true
18540                }
18541            }
18542            AtomView::Mul(mul) => {
18543                let factors: Vec<Atom> = mul.into_iter().map(|factor| factor.to_owned()).collect();
18544                match factors.split_first() {
18545                    Some((first, rest)) => {
18546                        let rest = product_atoms(rest);
18547                        if pos_aux(first) {
18548                            pos_aux(&rest)
18549                        } else {
18550                            !pos_aux(&rest)
18551                        }
18552                    }
18553                    None => true,
18554                }
18555            }
18556            AtomView::Add(_) => rubi_mathematica_first_sum_term(expr)
18557                .as_ref()
18558                .is_none_or(pos_aux),
18559            _ => true,
18560        }
18561    }
18562
18563    pos_aux(&rubi_together_simplify(expr))
18564}
18565
18566fn rubi_neg_q(expr: &Atom) -> bool {
18567    !rubi_pos_q(expr) && !rubi_simplify(expr).is_zero()
18568}
18569
18570fn rubi_sum_base_q(expr: &Atom) -> bool {
18571    if rubi_sum_q(expr) {
18572        return true;
18573    }
18574
18575    if rubi_power_q(expr) {
18576        if let AtomView::Pow(power) = expr.as_view() {
18577            let (base, exponent) = power.get_base_exp();
18578            return rubi_odd_q(&exponent.to_owned()) && rubi_sum_base_q(&base.to_owned());
18579        }
18580    }
18581
18582    false
18583}
18584
18585#[allow(dead_code)]
18586fn rubi_atom_base_q(expr: &Atom) -> bool {
18587    if atom_q(expr.as_view()) {
18588        return true;
18589    }
18590
18591    if let AtomView::Pow(power) = expr.as_view() {
18592        let (base, exponent) = power.get_base_exp();
18593        return rubi_odd_q(&exponent.to_owned()) && rubi_atom_base_q(&base.to_owned());
18594    }
18595
18596    false
18597}
18598
18599fn rubi_negative_form_q(expr: &Atom) -> bool {
18600    if is_number_less_than(expr, 0) || rubi_split_numeric_factor(expr).0 < 0 {
18601        return true;
18602    }
18603
18604    matches!(
18605        expr.as_view(),
18606        AtomView::Mul(product)
18607            if product
18608                .get_coefficient()
18609                .is_some_and(|coefficient| is_number_less_than(&coefficient.to_owned(), 0))
18610    )
18611}
18612
18613#[allow(dead_code)]
18614fn rubi_neg_sum_base_q(expr: &Atom) -> bool {
18615    match expr.as_view() {
18616        AtomView::Add(add) => add
18617            .into_iter()
18618            .next()
18619            .is_some_and(|first| rubi_negative_form_q(&first.to_owned())),
18620        AtomView::Pow(power) => {
18621            let (base, exponent) = power.get_base_exp();
18622            rubi_odd_q(&exponent.to_owned()) && rubi_neg_sum_base_q(&base.to_owned())
18623        }
18624        _ => false,
18625    }
18626}
18627
18628#[allow(dead_code)]
18629fn rubi_all_neg_term_q(expr: &Atom) -> bool {
18630    match expr.as_view() {
18631        AtomView::Pow(power) => {
18632            let (base, exponent) = power.get_base_exp();
18633            rubi_odd_q(&exponent.to_owned()) && rubi_all_neg_term_q(&base.to_owned())
18634        }
18635        AtomView::Add(add) => add
18636            .into_iter()
18637            .all(|term| rubi_negative_form_q(&term.to_owned())),
18638        _ => rubi_negative_form_q(expr),
18639    }
18640}
18641
18642#[allow(dead_code)]
18643fn rubi_some_neg_term_q(expr: &Atom) -> bool {
18644    match expr.as_view() {
18645        AtomView::Pow(power) => {
18646            let (base, exponent) = power.get_base_exp();
18647            rubi_odd_q(&exponent.to_owned()) && rubi_some_neg_term_q(&base.to_owned())
18648        }
18649        AtomView::Add(add) => add
18650            .into_iter()
18651            .any(|term| rubi_negative_form_q(&term.to_owned())),
18652        _ => rubi_negative_form_q(expr),
18653    }
18654}
18655
18656fn rubi_split_product<F>(predicate: F, expr: &Atom) -> Option<(Atom, Atom)>
18657where
18658    F: Fn(&Atom) -> bool + Copy,
18659{
18660    if rubi_product_q(expr) {
18661        if let AtomView::Mul(mul) = expr.as_view() {
18662            let factors: Vec<Atom> = mul.into_iter().map(|factor| factor.to_owned()).collect();
18663            if let Some((first, rest)) = factors.split_first() {
18664                if predicate(first) {
18665                    return Some((first.to_owned(), product_atoms(rest)));
18666                }
18667
18668                let rest_product = product_atoms(rest);
18669                if let Some((matched, unmatched_rest)) =
18670                    rubi_split_product(predicate, &rest_product)
18671                {
18672                    return Some((matched, first.to_owned() * unmatched_rest));
18673                }
18674            }
18675        }
18676
18677        None
18678    } else if predicate(expr) {
18679        Some((expr.to_owned(), Atom::num(1)))
18680    } else {
18681        None
18682    }
18683}
18684
18685fn product_atoms(factors: &[Atom]) -> Atom {
18686    factors
18687        .iter()
18688        .fold(Atom::num(1), |product, factor| product * factor)
18689}
18690
18691fn rubi_atomq_split_product_sum_base(expr: &Atom) -> bool {
18692    rubi_split_product(rubi_sum_base_q, expr).is_none()
18693}
18694
18695fn rubi_simpler_q(u: &Atom, v: &Atom) -> bool {
18696    if u == v {
18697        return false;
18698    }
18699
18700    if let Some(u_int) = integer_i64(u) {
18701        if let Some(v_int) = integer_i64(v) {
18702            if u_int == -v_int {
18703                return v_int < 0;
18704            }
18705            return u_int.unsigned_abs() < v_int.unsigned_abs();
18706        }
18707        return true;
18708    }
18709    if integer_i64(v).is_some() {
18710        return false;
18711    }
18712
18713    if let Some((u_num, u_den)) = rubi_fraction_parts(u) {
18714        if let Some((v_num, v_den)) = rubi_fraction_parts(v) {
18715            if u_den == v_den {
18716                return rubi_simpler_q(&Atom::num(u_num), &Atom::num(v_num));
18717            }
18718            return u_den < v_den;
18719        }
18720        return true;
18721    }
18722    if rubi_fraction_parts(v).is_some() {
18723        return false;
18724    }
18725
18726    if matches!(u.as_view(), AtomView::Num(_)) {
18727        if matches!(v.as_view(), AtomView::Num(_)) {
18728            return rubi_ordered_q(u, v);
18729        }
18730        return true;
18731    }
18732    if matches!(v.as_view(), AtomView::Num(_)) {
18733        return false;
18734    }
18735
18736    if atom_q(u.as_view()) {
18737        if atom_q(v.as_view()) {
18738            return rubi_ordered_q(u, v);
18739        }
18740        return true;
18741    }
18742    if atom_q(v.as_view()) {
18743        return false;
18744    }
18745
18746    if rubi_same_head(u.as_view(), v.as_view()) {
18747        let u_len = rubi_length(u.as_view());
18748        let v_len = rubi_length(v.as_view());
18749        if u_len == v_len {
18750            let u_leaf_count = rubi_leaf_count(u.as_view());
18751            let v_leaf_count = rubi_leaf_count(v.as_view());
18752            if u_leaf_count == v_leaf_count {
18753                for (u_child, v_child) in rubi_children(u.as_view())
18754                    .into_iter()
18755                    .zip(rubi_children(v.as_view()))
18756                {
18757                    if u_child == v_child {
18758                        continue;
18759                    }
18760                    return rubi_simpler_q(&u_child, &v_child);
18761                }
18762                false
18763            } else {
18764                u_leaf_count < v_leaf_count
18765            }
18766        } else {
18767            u_len < v_len
18768        }
18769    } else {
18770        let u_leaf_count = rubi_leaf_count(u.as_view());
18771        let v_leaf_count = rubi_leaf_count(v.as_view());
18772        if u_leaf_count == v_leaf_count {
18773            !rubi_ordered_q(v, u)
18774        } else {
18775            u_leaf_count < v_leaf_count
18776        }
18777    }
18778}
18779
18780fn rubi_simpler_sqrt_q(u: &Atom, v: &Atom) -> bool {
18781    if ltq!(v, 0) && !ltq!(u, 0) {
18782        return true;
18783    }
18784    if ltq!(u, 0) && !ltq!(v, 0) {
18785        return false;
18786    }
18787
18788    let sqrtu = rubi_rt(u, 2);
18789    let sqrtv = rubi_rt(v, 2);
18790    if integer_q(&sqrtu) {
18791        if integer_q(&sqrtv) {
18792            return ltq!(sqrtu, sqrtv);
18793        }
18794        return true;
18795    }
18796    if integer_q(&sqrtv) {
18797        return false;
18798    }
18799    if rational_number(&sqrtu).is_some() {
18800        if rational_number(&sqrtv).is_some() {
18801            return ltq!(sqrtu, sqrtv);
18802        }
18803        return true;
18804    }
18805    if rational_number(&sqrtv).is_some() {
18806        return false;
18807    }
18808    if posq!(u) {
18809        if posq!(v) {
18810            return rubi_leaf_count(sqrtu.as_view()) < rubi_leaf_count(sqrtv.as_view());
18811        }
18812        return true;
18813    }
18814    if posq!(v) {
18815        return false;
18816    }
18817
18818    let u_leaf_count = rubi_leaf_count(sqrtu.as_view());
18819    let v_leaf_count = rubi_leaf_count(sqrtv.as_view());
18820    if u_leaf_count < v_leaf_count {
18821        true
18822    } else if v_leaf_count < u_leaf_count {
18823        false
18824    } else {
18825        !rubi_ordered_q(v, u)
18826    }
18827}
18828
18829fn rubi_fraction_parts(expr: &Atom) -> Option<(i64, i64)> {
18830    rational_number(expr).and_then(|(numerator, denominator)| {
18831        (denominator > 1 && numerator % denominator != 0).then_some((numerator, denominator))
18832    })
18833}
18834
18835fn rubi_ordered_q(u: &Atom, v: &Atom) -> bool {
18836    u.cmp(v) != Ordering::Greater
18837}
18838
18839fn rubi_same_head(u: AtomView<'_>, v: AtomView<'_>) -> bool {
18840    match (u, v) {
18841        (AtomView::Num(_), AtomView::Num(_))
18842        | (AtomView::Var(_), AtomView::Var(_))
18843        | (AtomView::Add(_), AtomView::Add(_))
18844        | (AtomView::Mul(_), AtomView::Mul(_))
18845        | (AtomView::Pow(_), AtomView::Pow(_)) => true,
18846        (AtomView::Fun(u_fun), AtomView::Fun(v_fun)) => u_fun.get_symbol() == v_fun.get_symbol(),
18847        _ => false,
18848    }
18849}
18850
18851fn rubi_length<T: AtomCore>(expr: T) -> usize {
18852    let expr = expr.as_atom_view();
18853    match expr {
18854        AtomView::Add(add) => add.get_nargs(),
18855        AtomView::Mul(mul) => mul.get_nargs(),
18856        AtomView::Pow(_) => 2,
18857        AtomView::Fun(fun) => fun.get_nargs(),
18858        AtomView::Num(_) | AtomView::Var(_) => 0,
18859    }
18860}
18861
18862fn rubi_leaf_count<T: AtomCore>(expr: T) -> usize {
18863    let expr = expr.as_atom_view();
18864    match expr {
18865        AtomView::Num(number) => match number.get_coeff_view() {
18866            CoefficientView::Natural(_, denominator, 0, 1) if denominator > 1 => 3,
18867            _ => 1,
18868        },
18869        AtomView::Var(_) => 1,
18870        AtomView::Add(add) => 1 + add.into_iter().map(rubi_leaf_count).sum::<usize>(),
18871        AtomView::Mul(mul) => 1 + mul.into_iter().map(rubi_leaf_count).sum::<usize>(),
18872        AtomView::Pow(power) => {
18873            let (base, exponent) = power.get_base_exp();
18874            1 + rubi_leaf_count(base) + rubi_leaf_count(exponent)
18875        }
18876        AtomView::Fun(fun) => 1 + fun.into_iter().map(rubi_leaf_count).sum::<usize>(),
18877    }
18878}
18879
18880// Walk read-only descendants without copying each subtree into an owned Atom.
18881fn rubi_child_views<'a>(expr: AtomView<'a>) -> impl Iterator<Item = AtomView<'a>> {
18882    match expr {
18883        AtomView::Add(add) => add.to_slice().iter(),
18884        AtomView::Mul(mul) => mul.to_slice().iter(),
18885        AtomView::Pow(power) => power.to_slice().iter(),
18886        AtomView::Fun(function) => function.to_slice().iter(),
18887        AtomView::Num(_) | AtomView::Var(_) => symbolica::atom::ListSlice::empty().iter(),
18888    }
18889}
18890
18891fn rubi_children(expr: AtomView<'_>) -> Vec<Atom> {
18892    match expr {
18893        AtomView::Add(add) => add.into_iter().map(|child| child.to_owned()).collect(),
18894        AtomView::Mul(mul) => mul.into_iter().map(|child| child.to_owned()).collect(),
18895        AtomView::Pow(power) => {
18896            let (base, exponent) = power.get_base_exp();
18897            vec![base.to_owned(), exponent.to_owned()]
18898        }
18899        AtomView::Fun(fun) => fun.into_iter().map(|child| child.to_owned()).collect(),
18900        AtomView::Num(_) | AtomView::Var(_) => Vec::new(),
18901    }
18902}
18903
18904fn rubi_simp(expr: &Atom, x: Symbol) -> Atom {
18905    // Mathematica evaluates active trigonometric calls before Simp processes
18906    // their surrounding expression. In particular, both
18907    // Csc[Pi/2+I*u] and Sec[I*u] become Sech[u].
18908    let expr = rubi_reduce_builtin_trig_pi_shifts(expr);
18909    if let Some(simplified) = rubi_simplify_equal_power_conjugate_product(&expr) {
18910        return simplified;
18911    }
18912    let expr = rubi_mathematica_simplify_trig_squares(&expr);
18913    let simplified = rubi_simp_help(&expr, x);
18914    rubi_normalize_sum_factors(simplified.as_view())
18915}
18916
18917fn rubi_simplify_equal_power_conjugate_product(expr: &Atom) -> Option<Atom> {
18918    let factors = rubi_product_factors(expr);
18919    if factors.len() != 2 {
18920        return None;
18921    }
18922
18923    let (first_base, first_exponent) = rubi_factor_base_exponent(&factors[0]);
18924    let (second_base, second_exponent) = rubi_factor_base_exponent(&factors[1]);
18925    if !eqq!(first_exponent, second_exponent) {
18926        return None;
18927    }
18928
18929    let first_terms = rubi_add_terms(&first_base);
18930    let second_terms = rubi_add_terms(&second_base);
18931    if first_terms.len() != 2 || second_terms.len() != 2 {
18932        return None;
18933    }
18934
18935    for first_common_index in 0..2 {
18936        for second_common_index in 0..2 {
18937            let first_common = &first_terms[first_common_index];
18938            let second_common = &second_terms[second_common_index];
18939            let first_other = &first_terms[1 - first_common_index];
18940            let second_other = &second_terms[1 - second_common_index];
18941            if eqq!(first_common, second_common)
18942                && eqq!(first_other, -second_other)
18943                && gtq!(first_common, 0)
18944            {
18945                let difference = (first_common.pow(2) - first_other.pow(2)).expand();
18946                return Some(difference.pow(first_exponent));
18947            }
18948        }
18949    }
18950
18951    None
18952}
18953
18954fn rubi_mathematica_simplify_trig_squares(expr: &Atom) -> Atom {
18955    let argument = symbol!("rubi_hyperbolic_square_argument_");
18956    let argument_atom = Atom::var(argument);
18957    let identities: [(Pattern, fn(Atom) -> Atom, i64); 20] = [
18958        (
18959            (Atom::num(1) - argument_atom.sin().pow(2)).to_pattern(),
18960            |argument| argument.cos(),
18961            1,
18962        ),
18963        (
18964            (argument_atom.sin().pow(2) - Atom::num(1)).to_pattern(),
18965            |argument| argument.cos(),
18966            -1,
18967        ),
18968        (
18969            (Atom::num(1) - argument_atom.cos().pow(2)).to_pattern(),
18970            |argument| argument.sin(),
18971            1,
18972        ),
18973        (
18974            (argument_atom.cos().pow(2) - Atom::num(1)).to_pattern(),
18975            |argument| argument.sin(),
18976            -1,
18977        ),
18978        (
18979            (Atom::num(1) + argument_atom.sinh().pow(2)).to_pattern(),
18980            |argument| argument.cosh(),
18981            1,
18982        ),
18983        (
18984            (-Atom::num(1) - argument_atom.sinh().pow(2)).to_pattern(),
18985            |argument| argument.cosh(),
18986            -1,
18987        ),
18988        (
18989            (argument_atom.cosh().pow(2) - Atom::num(1)).to_pattern(),
18990            |argument| argument.sinh(),
18991            1,
18992        ),
18993        (
18994            (Atom::num(1) - argument_atom.cosh().pow(2)).to_pattern(),
18995            |argument| argument.sinh(),
18996            -1,
18997        ),
18998        (
18999            (Atom::num(1) - argument_atom.tanh().pow(2)).to_pattern(),
19000            |argument| argument.sech(),
19001            1,
19002        ),
19003        (
19004            (argument_atom.tanh().pow(2) - Atom::num(1)).to_pattern(),
19005            |argument| argument.sech(),
19006            -1,
19007        ),
19008        (
19009            (Atom::num(1) + argument_atom.tan().pow(2)).to_pattern(),
19010            |argument| argument.sec(),
19011            1,
19012        ),
19013        (
19014            (-Atom::num(1) - argument_atom.tan().pow(2)).to_pattern(),
19015            |argument| argument.sec(),
19016            -1,
19017        ),
19018        (
19019            (Atom::num(1) + argument_atom.cot().pow(2)).to_pattern(),
19020            |argument| argument.csc(),
19021            1,
19022        ),
19023        (
19024            (-Atom::num(1) - argument_atom.cot().pow(2)).to_pattern(),
19025            |argument| argument.csc(),
19026            -1,
19027        ),
19028        (
19029            (argument_atom.sec().pow(2) - Atom::num(1)).to_pattern(),
19030            |argument| argument.tan(),
19031            1,
19032        ),
19033        (
19034            (Atom::num(1) - argument_atom.sec().pow(2)).to_pattern(),
19035            |argument| argument.tan(),
19036            -1,
19037        ),
19038        (
19039            (argument_atom.csc().pow(2) - Atom::num(1)).to_pattern(),
19040            |argument| argument.cot(),
19041            1,
19042        ),
19043        (
19044            (Atom::num(1) - argument_atom.csc().pow(2)).to_pattern(),
19045            |argument| argument.cot(),
19046            -1,
19047        ),
19048        (
19049            (argument_atom.coth().pow(2) - Atom::num(1)).to_pattern(),
19050            |argument| argument.csch(),
19051            1,
19052        ),
19053        (
19054            (Atom::num(1) - argument_atom.coth().pow(2)).to_pattern(),
19055            |argument| argument.csch(),
19056            -1,
19057        ),
19058    ];
19059    let rewritten =
19060        identities
19061            .into_iter()
19062            .fold(expr.to_owned(), |current, (pattern, result, sign)| {
19063                current.replace(&pattern).repeat().with_map(move |matches| {
19064                    Atom::num(sign)
19065                        * result(
19066                            matches
19067                                .get(argument)
19068                                .expect("trig square pattern binds its argument")
19069                                .to_atom(),
19070                        )
19071                        .pow(2)
19072                })
19073            });
19074    if rewritten == *expr {
19075        expr.to_owned()
19076    } else {
19077        rewritten.expand().cancel()
19078    }
19079}
19080
19081fn rubi_simplify(expr: &Atom) -> Atom {
19082    let expr = rubi_mathematica_simplify_trig_squares(expr);
19083    let expr = rubi_mathematica_trig_quotient(&expr).unwrap_or(expr);
19084    if let Some(simplified) = rubi_simplify_hyperbolic_half_angle_quotient(&expr) {
19085        return simplified;
19086    }
19087    if let Some(simplified) = rubi_simplify_perfect_square_root_product(&expr) {
19088        return simplified;
19089    }
19090
19091    let expanded = expr.expand();
19092    let mut simplified = if contains_inexact_number(expanded.as_view()) {
19093        expanded
19094    } else {
19095        expanded.cancel()
19096    };
19097
19098    if !contains_inexact_number(expr.as_view()) {
19099        let together = expr.together();
19100        if rubi_leaf_count(together.as_view()) < rubi_leaf_count(simplified.as_view()) {
19101            simplified = together;
19102        }
19103    }
19104
19105    // The exponential candidate is a rational-trigonometric identity prover.
19106    // Applying it to algebraic powers does not model Mathematica Simplify and
19107    // turns radical coefficients into an unnecessarily large algebraic GCD.
19108    if rubi_contains_noninteger_power(expr.as_view()) {
19109        return simplified;
19110    }
19111
19112    let trig_candidate = rubi_trig_to_exp(expr.as_view()).together();
19113    if trig_candidate.get_all_symbols(false).is_empty()
19114        && rubi_leaf_count(trig_candidate.as_view()) < rubi_leaf_count(simplified.as_view())
19115    {
19116        trig_candidate
19117    } else {
19118        simplified
19119    }
19120}
19121
19122fn rubi_simplify_perfect_square_root_product(expr: &Atom) -> Option<Atom> {
19123    let mut radicand = Atom::num(1);
19124    let mut radicands = Vec::new();
19125    let mut remaining = Atom::num(1);
19126    let mut root_count = 0;
19127
19128    for factor in rubi_product_factors(expr) {
19129        let Some((base, half_exponent)) = rubi_sqrt_half_power(&factor) else {
19130            remaining *= factor;
19131            continue;
19132        };
19133
19134        radicand *= base.pow(half_exponent);
19135        radicands.push(base);
19136        root_count += 1;
19137    }
19138
19139    if root_count < 2 {
19140        return None;
19141    }
19142
19143    let radicand = radicand.together().factor();
19144    let mut root = rubi_rt_aux(&radicand, 2);
19145    if rubi_contains_noninteger_power(root.as_view()) || !eqq!(root.pow(2), radicand) {
19146        return None;
19147    }
19148
19149    let root_add_factors = rubi_product_factors(&root)
19150        .into_iter()
19151        .filter_map(|factor| {
19152            let (base, exponent) = rubi_factor_base_exponent(&factor);
19153            (matches!(base.as_view(), AtomView::Add(_))
19154                && integer_i64(&exponent).is_some_and(|exponent| exponent % 2 != 0))
19155            .then_some(base)
19156        })
19157        .collect::<Vec<_>>();
19158    if root_add_factors.iter().any(|factor| {
19159        !radicands
19160            .iter()
19161            .any(|radicand| rubi_contains_subexpression(radicand.as_view(), factor.as_view()))
19162            && radicands.iter().any(|radicand| {
19163                rubi_contains_subexpression(radicand.as_view(), (-factor).expand().as_view())
19164            })
19165    }) {
19166        root = -root;
19167    }
19168
19169    let simplified = remaining * root;
19170    (simplified != *expr && rubi_leaf_count(simplified.as_view()) < rubi_leaf_count(expr.as_view()))
19171        .then_some(simplified)
19172}
19173
19174fn rubi_combine_exact_rational_power_base_factor(expr: &Atom) -> Option<Atom> {
19175    let factors = rubi_product_factors(expr);
19176    if factors.len() < 2 {
19177        return None;
19178    }
19179
19180    for (power_index, power_factor) in factors.iter().enumerate() {
19181        let AtomView::Pow(power) = power_factor.as_view() else {
19182            continue;
19183        };
19184        let base = power.get_base().to_owned();
19185        let exponent = power.get_exp().to_owned();
19186        if rational_number(&exponent).is_none_or(|(_, denominator)| denominator == 1) {
19187            continue;
19188        }
19189
19190        for (base_index, factor) in factors.iter().enumerate() {
19191            if base_index == power_index {
19192                continue;
19193            }
19194            let (factor_exponent, sign) = if factor == &base {
19195                (Atom::num(1), 1)
19196            } else if factor == &(-&base).expand() {
19197                (Atom::num(1), -1)
19198            } else {
19199                let (factor_base, factor_exponent) = rubi_factor_base_exponent(factor);
19200                let Some(factor_exponent_integer) = integer_i64(&factor_exponent) else {
19201                    continue;
19202                };
19203                if factor_base == base {
19204                    (factor_exponent, 1)
19205                } else if factor_base == (-&base).expand() {
19206                    let sign = if factor_exponent_integer % 2 == 0 {
19207                        1
19208                    } else {
19209                        -1
19210                    };
19211                    (factor_exponent, sign)
19212                } else {
19213                    continue;
19214                }
19215            };
19216            // Combining a fractional power with an integer power of the same
19217            // (or negated) base is branch-safe.  Mathematica's
19218            // TogetherSimplify uses this for forms such as
19219            // Sqrt[D]/(-D) -> -1/Sqrt[D].
19220            let combined_power = base.pow(exponent + factor_exponent);
19221            let candidate = factors
19222                .iter()
19223                .enumerate()
19224                .filter_map(|(index, factor)| {
19225                    (index != power_index && index != base_index).then_some(factor)
19226                })
19227                .fold(Atom::num(sign) * combined_power, |product, factor| {
19228                    product * factor
19229                });
19230            return Some(candidate);
19231        }
19232    }
19233
19234    None
19235}
19236
19237fn rubi_simplified_quotient(numerator: &Atom, denominator: &Atom) -> Option<Atom> {
19238    let denominator = rubi_simplify(denominator);
19239    if denominator.is_zero() {
19240        return None;
19241    }
19242
19243    Some(rubi_simplify(&(numerator / denominator)))
19244}
19245
19246fn rubi_simplify_hyperbolic_half_angle_quotient(expr: &Atom) -> Option<Atom> {
19247    let (numerator, denominator) = rational_numerator_denominator(expr)?;
19248    let (numerator_symbol, argument) = rubi_hyperbolic_call(&numerator)?;
19249    if numerator_symbol.get_stripped_ascii_name() != Some("sinh") {
19250        return None;
19251    }
19252
19253    let terms = rubi_add_terms(&denominator);
19254    if terms.len() != 2 || !terms.iter().any(|term| term.is_one()) {
19255        return None;
19256    }
19257    let matching_cosh = terms.iter().any(|term| {
19258        rubi_hyperbolic_call(term).is_some_and(|(symbol, candidate_argument)| {
19259            symbol.get_stripped_ascii_name() == Some("cosh") && candidate_argument == argument
19260        })
19261    });
19262
19263    matching_cosh.then(|| (argument / 2).tanh())
19264}
19265
19266fn rubi_mathematica_simplify(expr: &Atom) -> Atom {
19267    let simplified = rubi_simplify(expr);
19268    if rubi_leaf_count(expr.as_view()) <= rubi_leaf_count(simplified.as_view()) {
19269        expr.to_owned()
19270    } else {
19271        simplified
19272    }
19273}
19274
19275fn rubi_mathematica_simplify_in(expr: &Atom, x: Symbol) -> Atom {
19276    let simplified = rubi_mathematica_simplify(expr);
19277    let mut sign = 1;
19278    let normalized = rubi_product_factors(&simplified)
19279        .into_iter()
19280        .map(|factor| {
19281            if rubi_sum_q(&factor)
19282                && let Some(terms) = collect_polynomial_terms_without_expanding(&factor, x)
19283                && let Some((_, leading_coefficient)) = terms.last_key_value()
19284                && is_negative_term(leading_coefficient)
19285            {
19286                sign = -sign;
19287                (-factor).expand()
19288            } else {
19289                factor
19290            }
19291        })
19292        .fold(Atom::num(1), |product, factor| product * factor);
19293
19294    // Mathematica Simplify keeps the sign outside a polynomial factor whose
19295    // highest-degree coefficient it makes positive. Symbolica orders the same
19296    // polynomial from low to high degree and otherwise absorbs this sign.
19297    Atom::num(sign) * normalized
19298}
19299
19300fn rubi_hold_power(base: &Atom, exponent: &Atom) -> Atom {
19301    if rubi_sum_q(base) && integer_i64(exponent).is_some() {
19302        // TODO: Use an inert power head with an explicit release point when
19303        // Rubi helper output must preserve a structural integer power of a sum.
19304        return base.pow(exponent);
19305    }
19306
19307    base.pow(exponent)
19308}
19309
19310fn rubi_equivalent_q(left: &Atom, right: &Atom) -> bool {
19311    left == right || rubi_algebraic_zero_q(&(left - right))
19312}
19313
19314fn rubi_branch_sensitive_ne_q(left: impl RubiAtomArgument, right: impl RubiAtomArgument) -> bool {
19315    let left = left.rubi_atom_or_view();
19316    let right = right.rubi_atom_or_view();
19317    if left == right {
19318        return false;
19319    }
19320
19321    // Mathematica's Rubi NeQ does not collapse branch-sensitive symbolic roots
19322    // such as (x^(2*n))^(1/(2*n)) to x. Symbolica can prove those equal through
19323    // algebraic simplification, but doing so changes the Rubi substitution path.
19324    if rubi_contains_symbolic_fractional_power(left.as_view())
19325        || rubi_contains_symbolic_fractional_power(right.as_view())
19326    {
19327        return true;
19328    }
19329
19330    !rubi_algebraic_zero_q(&(left.as_view() - right.as_view()))
19331}
19332
19333fn rubi_contains_symbolic_fractional_power(expr: AtomView<'_>) -> bool {
19334    match expr {
19335        AtomView::Pow(power) => {
19336            let (base, exponent) = power.get_base_exp();
19337            integer_i64_view(exponent).is_none() || rubi_contains_symbolic_fractional_power(base)
19338        }
19339        AtomView::Add(add) => add.into_iter().any(rubi_contains_symbolic_fractional_power),
19340        AtomView::Mul(mul) => mul.into_iter().any(rubi_contains_symbolic_fractional_power),
19341        AtomView::Fun(function) => function
19342            .into_iter()
19343            .any(rubi_contains_symbolic_fractional_power),
19344        AtomView::Num(_) | AtomView::Var(_) => false,
19345    }
19346}
19347
19348fn rubi_algebraic_zero_q(expr: &Atom) -> bool {
19349    let simplified = rubi_simplify(expr);
19350    simplified.is_zero()
19351        || (!rubi_contains_bare_function_head_symbol(&simplified)
19352            && !matches!(simplified.zero_test(16, 1e-12), ConditionResult::False))
19353}
19354
19355fn rubi_contains_bare_function_head_symbol(expr: &Atom) -> bool {
19356    fn recur(expr: AtomView<'_>) -> bool {
19357        match expr {
19358            AtomView::Var(variable) => {
19359                let symbol = variable.get_symbol();
19360                rubi_inert_or_builtin_trig_symbol_q(symbol)
19361                    || rubi_hyperbolic_function_symbol(symbol)
19362                    || rubi_calculus_function_symbol(symbol)
19363            }
19364            AtomView::Add(add) => add.into_iter().any(recur),
19365            AtomView::Mul(mul) => mul.into_iter().any(recur),
19366            AtomView::Pow(power) => recur(power.get_base()) || recur(power.get_exp()),
19367            AtomView::Fun(fun) => fun.into_iter().any(recur),
19368            AtomView::Num(_) => false,
19369        }
19370    }
19371
19372    recur(expr.as_view())
19373}
19374
19375fn rubi_full_simplify(expr: &Atom) -> Atom {
19376    rubi_simplify(expr)
19377}
19378
19379fn rubi_function_expand(expr: &Atom) -> Atom {
19380    expr.to_owned()
19381}
19382
19383fn rubi_expand(expr: &Atom, _x: Symbol) -> Atom {
19384    expr.expand()
19385}
19386
19387fn rubi_log(expr: &Atom) -> Atom {
19388    if rubi_euler_symbol_q(expr.as_view()) {
19389        Atom::num(1)
19390    } else {
19391        expr.log()
19392    }
19393}
19394
19395fn rubi_normalize_euler_logs(expr: AtomView<'_>) -> Atom {
19396    if let Some(exponent) = rubi_exp_argument(expr) {
19397        if let Some(normalized) = rubi_inverse_trig_exponential(&exponent) {
19398            return normalized;
19399        }
19400    }
19401
19402    match expr {
19403        AtomView::Fun(function) => {
19404            let symbol = function.get_symbol();
19405            if (symbol == Symbol::LOG || symbol.get_stripped_name() == "log")
19406                && function.get_nargs() == 1
19407            {
19408                let argument = rubi_normalize_euler_logs(function.get(0));
19409                if rubi_euler_symbol_q(argument.as_view()) {
19410                    return Atom::num(1);
19411                }
19412                if let Some(exponent) = rubi_exp_argument(argument.as_view()) {
19413                    return exponent;
19414                }
19415                let simplified_argument = rubi_simpler_expanded_log_argument(&argument);
19416                return symbol.call((simplified_argument,));
19417            }
19418
19419            let args: Vec<_> = function
19420                .into_iter()
19421                .map(rubi_normalize_euler_logs)
19422                .collect();
19423            symbol.call_args(args)
19424        }
19425        AtomView::Add(add) => add
19426            .into_iter()
19427            .map(rubi_normalize_euler_logs)
19428            .fold(Atom::num(0), |sum, term| sum + term),
19429        AtomView::Mul(mul) => mul
19430            .into_iter()
19431            .map(rubi_normalize_euler_logs)
19432            .fold(Atom::num(1), |product, factor| product * factor),
19433        AtomView::Pow(power) => rubi_normalize_euler_logs(power.get_base())
19434            .pow(rubi_normalize_euler_logs(power.get_exp())),
19435        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
19436    }
19437}
19438
19439fn rubi_exp_argument(expr: AtomView<'_>) -> Option<Atom> {
19440    if let AtomView::Fun(function) = expr
19441        && function.get_symbol().get_stripped_name() == "exp"
19442        && function.get_nargs() == 1
19443    {
19444        return Some(function.get(0).to_owned());
19445    }
19446
19447    let AtomView::Pow(power) = expr else {
19448        return None;
19449    };
19450    let (base, exponent) = power.get_base_exp();
19451    rubi_euler_symbol_q(base).then(|| exponent.to_owned())
19452}
19453
19454fn rubi_simpler_expanded_log_argument(expr: &Atom) -> Atom {
19455    let simplified = expr.expand().cancel();
19456    if rubi_leaf_count(simplified.as_view()) < rubi_leaf_count(expr.as_view()) {
19457        simplified
19458    } else {
19459        expr.to_owned()
19460    }
19461}
19462
19463fn rubi_euler_symbol_q<T: AtomCore>(expr: T) -> bool {
19464    expr.as_atom_view()
19465        .get_symbol()
19466        .is_some_and(|symbol| symbol == Symbol::E || symbol.get_stripped_name() == "e")
19467}
19468
19469fn rubi_normalize_product_log_exponentials(expr: &Atom) -> Atom {
19470    expr.replace_map(|part, _context, out| {
19471        let AtomView::Pow(power) = part else {
19472            return;
19473        };
19474        let (base, exponent) = power.get_base_exp();
19475        if !rubi_euler_symbol_q(base) {
19476            return;
19477        }
19478        let AtomView::Fun(function) = exponent else {
19479            return;
19480        };
19481        if function.get_symbol() != rubi_symbols().product_log || function.get_nargs() != 1 {
19482            return;
19483        }
19484
19485        let argument = function.get(0).to_owned();
19486        let product_log = function.get_symbol().call((argument.to_owned(),));
19487        **out = argument / product_log;
19488    })
19489}
19490
19491fn rubi_normalize_atanh_logs(expr: &Atom) -> Atom {
19492    expr.replace_map_bottom_up(|part, _context, out| {
19493        let AtomView::Fun(function) = part else {
19494            return;
19495        };
19496        if function.get_symbol() != symbolica::transcendental::atanh() || function.get_nargs() != 1
19497        {
19498            return;
19499        }
19500
19501        let argument = function.get(0).to_owned();
19502        **out = ((Atom::num(1) + &argument).log() - (Atom::num(1) - argument).log()) / Atom::num(2);
19503    })
19504}
19505
19506fn rubi_normalize_inverse_trig_exponentials(expr: AtomView<'_>) -> Atom {
19507    if let Some(exponent) = rubi_exp_argument(expr) {
19508        if let Some(normalized) = rubi_inverse_trig_exponential(&exponent) {
19509            return normalized;
19510        }
19511    }
19512
19513    match expr {
19514        AtomView::Fun(function) => {
19515            let args: Vec<_> = function
19516                .into_iter()
19517                .map(rubi_normalize_inverse_trig_exponentials)
19518                .collect();
19519            function.get_symbol().call_args(args)
19520        }
19521        AtomView::Add(add) => add
19522            .into_iter()
19523            .map(rubi_normalize_inverse_trig_exponentials)
19524            .fold(Atom::num(0), |sum, term| sum + term),
19525        AtomView::Mul(mul) => mul
19526            .into_iter()
19527            .map(rubi_normalize_inverse_trig_exponentials)
19528            .fold(Atom::num(1), |product, factor| product * factor),
19529        AtomView::Pow(power) => rubi_normalize_inverse_trig_exponentials(power.get_base())
19530            .pow(rubi_normalize_inverse_trig_exponentials(power.get_exp())),
19531        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
19532    }
19533}
19534
19535fn rubi_inverse_trig_exponential(exponent: &Atom) -> Option<Atom> {
19536    let angle = rubi_explicit_imaginary_angle(exponent)?;
19537    rubi_inverse_trig_angle_exponential(&angle)
19538}
19539
19540fn rubi_explicit_imaginary_angle(exponent: &Atom) -> Option<Atom> {
19541    if let Some(angle) = rubi_explicit_imaginary_argument(exponent) {
19542        return Some(angle);
19543    }
19544
19545    let AtomView::Add(add) = exponent.as_view() else {
19546        return None;
19547    };
19548    let mut angle = Atom::num(0);
19549    for term in add {
19550        angle += rubi_explicit_imaginary_argument(&term.to_owned())?;
19551    }
19552    Some(angle)
19553}
19554
19555fn rubi_inverse_trig_angle_exponential(angle: &Atom) -> Option<Atom> {
19556    if let Some((scale, head, argument)) = rubi_scaled_inverse_trig_angle(angle) {
19557        return rubi_powered_inverse_trig_exponential(scale, head, argument);
19558    }
19559
19560    let AtomView::Add(add) = angle.as_view() else {
19561        return None;
19562    };
19563    let terms: Vec<_> = add.into_iter().map(|term| term.to_owned()).collect();
19564    for (index, term) in terms.iter().enumerate() {
19565        let shift = if eqq!(term, Atom::var(Symbol::PI) / 2) {
19566            Some(rubi_i())
19567        } else if eqq!(term, -Atom::var(Symbol::PI) / 2) {
19568            Some(-rubi_i())
19569        } else if eqq!(term, Atom::var(Symbol::PI)) || eqq!(term, -Atom::var(Symbol::PI)) {
19570            Some(-Atom::num(1))
19571        } else {
19572            None
19573        };
19574        let Some(shift) = shift else {
19575            continue;
19576        };
19577        let mut rest = Atom::num(0);
19578        for (term_index, other_term) in terms.iter().enumerate() {
19579            if term_index != index {
19580                rest += other_term.to_owned();
19581            }
19582        }
19583        return Some(shift * rubi_inverse_trig_angle_exponential(&rest)?);
19584    }
19585
19586    None
19587}
19588
19589fn rubi_scaled_inverse_trig_angle(angle: &Atom) -> Option<(Atom, Symbol, Atom)> {
19590    if let AtomView::Fun(function) = angle.as_view()
19591        && function.get_nargs() == 1
19592        && matches!(function.get_symbol().get_stripped_name(), "asin" | "acos")
19593    {
19594        return Some((
19595            Atom::num(1),
19596            function.get_symbol(),
19597            function.get(0).to_owned(),
19598        ));
19599    }
19600
19601    let AtomView::Mul(mul) = angle.as_view() else {
19602        return None;
19603    };
19604    let factors: Vec<_> = mul.into_iter().map(|factor| factor.to_owned()).collect();
19605    for (index, factor) in factors.iter().enumerate() {
19606        let AtomView::Fun(function) = factor.as_view() else {
19607            continue;
19608        };
19609        if function.get_nargs() != 1
19610            || !matches!(function.get_symbol().get_stripped_name(), "asin" | "acos")
19611        {
19612            continue;
19613        }
19614        let mut scale = Atom::num(1);
19615        for (factor_index, other_factor) in factors.iter().enumerate() {
19616            if factor_index != index {
19617                scale *= other_factor.to_owned();
19618            }
19619        }
19620        return Some((scale, function.get_symbol(), function.get(0).to_owned()));
19621    }
19622
19623    None
19624}
19625
19626fn rubi_powered_inverse_trig_exponential(
19627    scale: Atom,
19628    head: Symbol,
19629    argument: Atom,
19630) -> Option<Atom> {
19631    let sqrt = (Atom::num(1) - argument.pow(2)).sqrt();
19632    let base = match head.get_stripped_name() {
19633        "asin" => sqrt + rubi_i() * argument,
19634        "acos" => argument + rubi_i() * sqrt,
19635        _ => return None,
19636    };
19637
19638    if eqq!(scale, 1) {
19639        return Some(base);
19640    }
19641    if eqq!(scale, -1) {
19642        return Some(Atom::num(1) / base);
19643    }
19644    if eqq!(scale, 2) {
19645        return Some(base.pow(2).expand());
19646    }
19647    if eqq!(scale, -2) {
19648        return Some((Atom::num(1) / base).pow(2).expand());
19649    }
19650
19651    None
19652}
19653
19654fn rubi_normalize_inverse_trig_trig<T: AtomCore>(expr: T) -> Atom {
19655    let expr = expr.as_atom_view();
19656    match expr {
19657        AtomView::Fun(function) if function.get_nargs() == 1 => {
19658            let argument = rubi_normalize_inverse_trig_trig(function.get(0));
19659            if rubi_inert_or_builtin_trig_symbol_q(function.get_symbol()) {
19660                if let Some(inverse_argument) = rubi_argument_of_inverse_trig_multiple(&argument) {
19661                    return rubi_subst_for_trig_function(
19662                        function.get_symbol(),
19663                        inverse_argument.multiple,
19664                        &inverse_argument.sin,
19665                        &inverse_argument.cos,
19666                    );
19667                }
19668            }
19669            function.get_symbol().call((argument,))
19670        }
19671        AtomView::Fun(function) => {
19672            let args: Vec<_> = function
19673                .into_iter()
19674                .map(rubi_normalize_inverse_trig_trig)
19675                .collect();
19676            function.get_symbol().call_args(args)
19677        }
19678        AtomView::Add(add) => add
19679            .into_iter()
19680            .map(rubi_normalize_inverse_trig_trig)
19681            .fold(Atom::num(0), |sum, term| sum + term),
19682        AtomView::Mul(mul) => mul
19683            .into_iter()
19684            .map(rubi_normalize_inverse_trig_trig)
19685            .fold(Atom::num(1), |product, factor| product * factor),
19686        AtomView::Pow(power) => rubi_normalize_inverse_trig_trig(power.get_base())
19687            .pow(rubi_normalize_inverse_trig_trig(power.get_exp())),
19688        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
19689    }
19690}
19691
19692/// Sine and cosine data for an integer multiple of an inverse-trig argument.
19693struct RubiInverseTrigArgument {
19694    multiple: i64,
19695    sin: Atom,
19696    cos: Atom,
19697}
19698
19699fn rubi_argument_of_inverse_trig_multiple(argument: &Atom) -> Option<RubiInverseTrigArgument> {
19700    let (multiple, inverse_symbol, inverse_argument) =
19701        rubi_integer_multiple_of_unary_function(argument)?;
19702    let (sin, cos) = match inverse_symbol.get_stripped_ascii_name() {
19703        Some("asin") => {
19704            let sin = inverse_argument;
19705            let cos = (Atom::num(1) - sin.pow(2)).sqrt();
19706            (sin, cos)
19707        }
19708        Some("acos") => {
19709            let cos = inverse_argument;
19710            let sin = (Atom::num(1) - cos.pow(2)).sqrt();
19711            (sin, cos)
19712        }
19713        Some("atan") => {
19714            let denominator = (Atom::num(1) + inverse_argument.pow(2)).sqrt();
19715            (inverse_argument / &denominator, Atom::num(1) / denominator)
19716        }
19717        Some("acot") => {
19718            let denominator = (Atom::num(1) + inverse_argument.pow(2)).sqrt();
19719            (Atom::num(1) / &denominator, inverse_argument / denominator)
19720        }
19721        Some("asec") => {
19722            let cos = Atom::num(1) / &inverse_argument;
19723            let sin = (Atom::num(1) - Atom::num(1) / inverse_argument.pow(2)).sqrt();
19724            (sin, cos)
19725        }
19726        Some("acsc") => {
19727            let sin = Atom::num(1) / &inverse_argument;
19728            let cos = (Atom::num(1) - Atom::num(1) / inverse_argument.pow(2)).sqrt();
19729            (sin, cos)
19730        }
19731        _ => return None,
19732    };
19733    Some(RubiInverseTrigArgument { multiple, sin, cos })
19734}
19735
19736fn rubi_integer_multiple_of_unary_function(argument: &Atom) -> Option<(i64, Symbol, Atom)> {
19737    match argument.as_view() {
19738        AtomView::Fun(function) if function.get_nargs() == 1 => {
19739            Some((1, function.get_symbol(), function.get(0).to_owned()))
19740        }
19741        AtomView::Mul(mul) => {
19742            let mut multiple = 1;
19743            let mut function = None;
19744            for factor in mul {
19745                let factor_atom = factor.to_owned();
19746                if let Some(integer) = rubi_integer_atom(&factor_atom) {
19747                    multiple *= integer;
19748                } else if let AtomView::Fun(candidate) = factor {
19749                    if candidate.get_nargs() == 1 && function.is_none() {
19750                        function = Some((candidate.get_symbol(), candidate.get(0).to_owned()));
19751                    } else {
19752                        return None;
19753                    }
19754                } else {
19755                    return None;
19756                }
19757            }
19758            function.map(|(symbol, argument)| (multiple, symbol, argument))
19759        }
19760        _ => None,
19761    }
19762}
19763
19764fn rubi_log_base(base: &Atom, expr: &Atom) -> Atom {
19765    if let Some(base) = integer_i64(base).filter(|base| *base > 1)
19766        && let Some((numerator, denominator)) = rational_number(expr)
19767        && numerator > 0
19768        && denominator > 0
19769    {
19770        if numerator == denominator {
19771            return Atom::num(0);
19772        }
19773        if denominator == 1
19774            && let Some((power_numerator, power_denominator)) = integer_log_ratio(numerator, base)
19775        {
19776            return Atom::num(power_numerator) / power_denominator;
19777        }
19778        if numerator == 1
19779            && let Some((power_numerator, power_denominator)) = integer_log_ratio(denominator, base)
19780        {
19781            return -Atom::num(power_numerator) / power_denominator;
19782        }
19783    }
19784
19785    rubi_log(expr) / rubi_log(base)
19786}
19787
19788/// A function-of-logarithm decomposition and its substitution exponent.
19789struct RubiFunctionOfLog {
19790    function: Atom,
19791    argument: Atom,
19792    n: Atom,
19793}
19794
19795fn rubi_function_of_log(expr: &Atom, x: Symbol) -> Option<RubiFunctionOfLog> {
19796    let mut logarithmic_argument = None;
19797    collect_rubi_function_of_log_argument(expr.as_view(), x, &mut logarithmic_argument)?;
19798    let (argument, n) = logarithmic_argument?;
19799
19800    let substitution_guard = fresh_substitution_symbol()?;
19801    let substitution_symbol = substitution_guard.symbol();
19802    let substitution_variable = Atom::var(substitution_symbol);
19803    let transformed = rubi_subst_expression(expr, &argument.log(), substitution_variable);
19804    if !freeq!(transformed, x) {
19805        return None;
19806    }
19807
19808    Some(RubiFunctionOfLog {
19809        function: rubi_subst(&transformed, substitution_symbol, Atom::var(x)),
19810        argument,
19811        n,
19812    })
19813}
19814
19815fn collect_rubi_function_of_log_argument(
19816    expr: AtomView<'_>,
19817    x: Symbol,
19818    logarithmic_argument: &mut Option<(Atom, Atom)>,
19819) -> Option<()> {
19820    if is_free_of(expr, x) {
19821        return Some(());
19822    }
19823
19824    match expr {
19825        AtomView::Fun(function) if function.get_symbol() == symbol!("log") => {
19826            let arguments: Vec<Atom> = function
19827                .into_iter()
19828                .map(|argument| argument.to_owned())
19829                .collect();
19830            let [argument] = arguments.as_slice() else {
19831                return None;
19832            };
19833            if let Some((base_argument, exponent)) =
19834                rubi_function_of_log_monomial_argument(argument, x)
19835            {
19836                match logarithmic_argument {
19837                    Some((existing_argument, existing_n)) => {
19838                        if existing_argument != &base_argument || existing_n != &exponent {
19839                            return None;
19840                        }
19841                    }
19842                    None => *logarithmic_argument = Some((base_argument, exponent)),
19843                }
19844
19845                return Some(());
19846            }
19847
19848            collect_rubi_function_of_log_argument(argument.as_view(), x, logarithmic_argument)?;
19849            Some(())
19850        }
19851        AtomView::Fun(function) => {
19852            if rubi_calculus_function_symbol(function.get_symbol()) {
19853                return None;
19854            }
19855
19856            for argument in function {
19857                collect_rubi_function_of_log_argument(argument, x, logarithmic_argument)?;
19858            }
19859            Some(())
19860        }
19861        AtomView::Add(add) => {
19862            for term in add {
19863                collect_rubi_function_of_log_argument(term, x, logarithmic_argument)?;
19864            }
19865            Some(())
19866        }
19867        AtomView::Mul(mul) => {
19868            for factor in mul {
19869                collect_rubi_function_of_log_argument(factor, x, logarithmic_argument)?;
19870            }
19871            Some(())
19872        }
19873        AtomView::Pow(power) => {
19874            collect_rubi_function_of_log_argument(power.get_base(), x, logarithmic_argument)?;
19875            collect_rubi_function_of_log_argument(power.get_exp(), x, logarithmic_argument)
19876        }
19877        AtomView::Var(_) | AtomView::Num(_) => None,
19878    }
19879}
19880
19881fn rubi_function_of_log_monomial_argument(argument: &Atom, x: Symbol) -> Option<(Atom, Atom)> {
19882    if let Some(parts) = rubi_binomial_parts(argument.as_view(), x) {
19883        if parts.a.is_zero() {
19884            return Some((argument.to_owned(), parts.n));
19885        }
19886    }
19887
19888    rubi_monomial_coefficient_exponent(argument, x).and_then(|(_coefficient, exponent)| {
19889        if exponent.is_zero() {
19890            None
19891        } else {
19892            Some((argument.to_owned(), exponent))
19893        }
19894    })
19895}
19896
19897fn rubi_monomial_coefficient_exponent(expr: &Atom, x: Symbol) -> Option<(Atom, Atom)> {
19898    let x_atom = Atom::var(x);
19899    if *expr == x_atom {
19900        return Some((Atom::num(1), Atom::num(1)));
19901    }
19902
19903    match expr.as_view() {
19904        AtomView::Pow(power) => {
19905            let (base, exponent) = power.get_base_exp();
19906            if base.to_owned() == x_atom && is_free_of(&exponent.to_owned(), x) {
19907                Some((Atom::num(1), exponent.to_owned()))
19908            } else {
19909                None
19910            }
19911        }
19912        AtomView::Mul(mul) => {
19913            let mut coefficient = Atom::num(1);
19914            let mut monomial_exponent = None;
19915            for factor in mul {
19916                let factor = factor.to_owned();
19917                if let Some((factor_coefficient, factor_exponent)) =
19918                    rubi_monomial_coefficient_exponent(&factor, x)
19919                {
19920                    if monomial_exponent.is_some() {
19921                        return None;
19922                    }
19923                    coefficient *= factor_coefficient;
19924                    monomial_exponent = Some(factor_exponent);
19925                } else if is_free_of(&factor, x) {
19926                    coefficient *= factor;
19927                } else {
19928                    return None;
19929                }
19930            }
19931
19932            monomial_exponent.map(|exponent| (coefficient, exponent))
19933        }
19934        AtomView::Num(_) | AtomView::Var(_) | AtomView::Fun(_) | AtomView::Add(_) => None,
19935    }
19936}
19937
19938fn rubi_calculus_function_symbol(symbol: Symbol) -> bool {
19939    let symbols = rubi_symbols();
19940    matches!(
19941        symbol,
19942        s if s == symbol!("D")
19943            || s == symbol!("Integrate")
19944            || s == symbol!("Sum")
19945            || s == symbol!("Product")
19946            || s == symbol!("Int")
19947            || s == symbol!("CannotIntegrate")
19948            || s == symbol!("Dif")
19949            || s == symbol!("Subst")
19950    ) || symbol == symbols.rubi_int
19951        || symbol == symbols.unintegrable
19952}
19953
19954fn rubi_held_form_symbol(symbol: Symbol) -> bool {
19955    matches!(
19956        symbol,
19957        s if s == symbol!("Hold")
19958            || s == symbol!("HoldForm")
19959            || s == symbol!("Defer")
19960            || s == symbol!("Pattern")
19961    )
19962}
19963
19964fn rubi_independent_q(expr: &Atom, x: Symbol) -> bool {
19965    is_free_of(expr, x)
19966}
19967
19968fn rubi_calculus_operator_symbol(symbol: Symbol) -> bool {
19969    let symbols = rubi_symbols();
19970    matches!(
19971        symbol,
19972        s if s == symbol!("D")
19973            || s == symbol!("Integrate")
19974            || s == symbol!("Sum")
19975            || s == symbol!("Product")
19976            || s == symbol!("Int")
19977            || s == symbol!("CannotIntegrate")
19978            || s == symbol!("Dif")
19979            || s == symbol!("Subst")
19980    ) || symbol == symbols.unintegrable
19981}
19982
19983fn rubi_nonsum_q(expr: &Atom) -> bool {
19984    !rubi_sum_q(expr)
19985}
19986
19987fn rubi_true_q_use_gamma() -> bool {
19988    false
19989}
19990
19991fn rubi_simplify_integrand(expr: &Atom, x: Symbol) -> Atom {
19992    if let Some(simplified) = rubi_normalize_laurent_power_sum(expr, x) {
19993        return simplified;
19994    }
19995    if let Some(simplified) = rubi_normalize_powered_monomial_binomial_derivative(expr, x) {
19996        return simplified;
19997    }
19998    if let Some(simplified) = rubi_simplify_monomial_binomial_quotient(expr, x) {
19999        return simplified;
20000    }
20001    if let Some(simplified) = rubi_preserve_affine_inverse_function_integer_power(expr, x) {
20002        return simplified;
20003    }
20004
20005    if let Some(simplified) = rubi_simplify_integrand_mathematica_simplify_candidate(expr, x) {
20006        return rubi_finish_simplify_integrand(expr, &simplified, x);
20007    }
20008
20009    if rubi_sum_q(expr) {
20010        if let Some(factored) = rubi_factor_common_symbolic_terms(expr, x) {
20011            if let Some(simplified) =
20012                rubi_normalize_powered_monomial_binomial_derivative(&factored, x)
20013            {
20014                return simplified;
20015            }
20016            if factored != *expr && rubi_simpler_integrand_q(&factored, expr, x) {
20017                return factored;
20018            }
20019        }
20020
20021        if let Some(factored) = rubi_try_factor(expr.as_view()) {
20022            let factored = rubi_simp(&factored, x);
20023            if let Some(simplified) =
20024                rubi_normalize_powered_monomial_binomial_derivative(&factored, x)
20025            {
20026                return simplified;
20027            }
20028            if factored != *expr && rubi_simpler_integrand_q(&factored, expr, x) {
20029                return factored;
20030            }
20031        }
20032    }
20033
20034    if !rubi_sum_q(expr) {
20035        if let Some(normalized) = rubi_simplify_integrand_normalized_candidate(expr, x) {
20036            return normalized;
20037        }
20038
20039        let simplified_for_normalization = rubi_simplify_for_integrand_normalization(expr);
20040        if simplified_for_normalization != rubi_simplify(expr) {
20041            if let Some(normalized) =
20042                rubi_simplify_integrand_normalized_candidate(&simplified_for_normalization, x)
20043            {
20044                return normalized;
20045            }
20046        }
20047    }
20048
20049    if rubi_algebraic_function_q(expr, x, false) && !rubi_rational_function_q(expr, x) {
20050        return expr.to_owned();
20051    }
20052
20053    // Mathematica Simplify preserves an integer power of a sum here. Expanding
20054    // it prevents downstream Rubi rules from seeing the source-level power.
20055    if let AtomView::Pow(power) = expr.as_view()
20056        && rubi_sum_q(&power.get_base().to_owned())
20057        && integer_i64_view(power.get_exp()).is_some()
20058    {
20059        return expr.to_owned();
20060    }
20061
20062    let simplified = expr.expand().cancel();
20063    let simplified =
20064        rubi_normalize_integrand_function_arguments(&simplified, x).unwrap_or(simplified);
20065    if let Some(simplified) = rubi_simplify_monomial_binomial_quotient(&simplified, x) {
20066        return simplified;
20067    }
20068    if let Some(factored) = rubi_factor_common_symbolic_rational_numerator(&simplified, x) {
20069        if factored != *expr && rubi_simpler_integrand_q(&factored, expr, x) {
20070            return factored;
20071        }
20072    }
20073    let normalized = rubi_simp(&simplified, x);
20074    rubi_finish_simplify_integrand(expr, &normalized, x)
20075}
20076
20077fn rubi_preserve_affine_inverse_function_integer_power(expr: &Atom, x: Symbol) -> Option<Atom> {
20078    let factors = rubi_product_factors(expr);
20079    let inverse_sum_index = factors
20080        .iter()
20081        .position(|factor| rubi_match_affine_inverse_function_q(factor, x))?;
20082
20083    // Mathematica Simplify preserves both the affine inverse-function factor
20084    // and a source-level positive integer power such as (f+g*x)^2 here.  The
20085    // intact expression reaches DownValue 5298, whose ExpandIntegrand call
20086    // then exposes the pieces handled by algebraic DownValue 715.
20087    let preserves_integer_power = factors.iter().enumerate().any(|(index, factor)| {
20088        if index == inverse_sum_index {
20089            return false;
20090        }
20091        let AtomView::Pow(power) = factor.as_view() else {
20092            return false;
20093        };
20094        integer_i64_view(power.get_exp()).is_some_and(|exponent| exponent > 1)
20095            && rubi_linear_q(power.get_base(), x)
20096    });
20097    if !preserves_integer_power {
20098        return None;
20099    }
20100    Some(expr.to_owned())
20101}
20102
20103fn rubi_finish_simplify_integrand(expr: &Atom, simplified: &Atom, x: Symbol) -> Atom {
20104    let simplified = rubi_expand_rational_denominator_if_simpler(simplified, x)
20105        .unwrap_or_else(|| simplified.to_owned());
20106    // Mathematica's Map over Plus preserves a Simplify-produced termwise sum.
20107    // Rebuilding the same Add with Symbolica may combine it back over a common
20108    // denominator, undoing a cancellation such as (d+e*x)*Log[d+e*x].
20109    if rubi_sum_q(&simplified)
20110        && !rubi_sum_q(expr)
20111        && rubi_contains_function_symbol(&simplified, Symbol::LOG)
20112        && (rubi_simplify_integrand_mathematica_simplify_candidate_q(expr, &simplified, x)
20113            || rubi_log_apart_cancellation_q(expr, &simplified))
20114    {
20115        return simplified;
20116    }
20117    let normalized = rubi_normalize_lead_term_signs(&rubi_normalize_integrand_aux(&simplified, x));
20118    // Mathematica Simplify recombines inverse polynomial factors when their
20119    // expanded product is structurally smaller.  This is important for source
20120    // rules such as the quartic-trinomial substitution:
20121    // (1-x+x^2)^-1 (1+x+x^2)^-1 becomes (1+x^2+x^4)^-1.
20122    let normalized = rubi_recombine_simpler_polynomial_inverse_factors(&normalized, x);
20123    let normalized = rubi_normalize_polynomial_power_lead_signs(normalized.as_view(), x);
20124    let normalized_leaf_count = rubi_leaf_count(normalized.as_view());
20125    let expr_leaf_count = rubi_leaf_count(expr.as_view());
20126    if 5 * normalized_leaf_count < 4 * expr_leaf_count {
20127        normalized
20128    } else if rubi_normalize_lead_term_signs(&normalized) != rubi_normalize_lead_term_signs(expr) {
20129        normalized
20130    } else {
20131        expr.to_owned()
20132    }
20133}
20134
20135fn rubi_expand_rational_denominator_if_simpler(expr: &Atom, x: Symbol) -> Option<Atom> {
20136    if !rubi_rational_function_q(expr, x) {
20137        return None;
20138    }
20139
20140    let numerator = rubi_numerator(expr).expand();
20141    let denominator = rubi_denominator_atom(expr);
20142    let expanded_denominator = denominator.expand();
20143    if expanded_denominator == denominator {
20144        return None;
20145    }
20146
20147    let candidate = numerator / expanded_denominator;
20148    (rubi_leaf_count(candidate.as_view()) < rubi_leaf_count(expr.as_view())).then_some(candidate)
20149}
20150
20151fn rubi_normalize_polynomial_power_lead_signs(expr: AtomView<'_>, x: Symbol) -> Atom {
20152    match expr {
20153        AtomView::Pow(power) => {
20154            let (base, exponent) = power.get_base_exp();
20155            let base = rubi_normalize_polynomial_power_lead_signs(base, x);
20156            let exponent = exponent.to_owned();
20157            if rubi_sum_q(&base)
20158                && let Some(exponent_integer) = integer_i64(&exponent)
20159                && let Some(terms) = collect_polynomial_terms_without_expanding(&base, x)
20160                && let Some((_, coefficient)) = terms.first_key_value()
20161                && is_negative_term(coefficient)
20162            {
20163                let sign = if exponent_integer % 2 == 0 { 1 } else { -1 };
20164                let negated_base = (-base).expand();
20165                return Atom::num(sign) * rubi_hold_power(&negated_base, &exponent);
20166            }
20167            base.pow(exponent)
20168        }
20169        AtomView::Add(add) => add
20170            .into_iter()
20171            .map(|term| rubi_normalize_polynomial_power_lead_signs(term, x))
20172            .fold(Atom::num(0), |sum, term| sum + term),
20173        AtomView::Mul(mul) => mul
20174            .into_iter()
20175            .map(|factor| rubi_normalize_polynomial_power_lead_signs(factor, x))
20176            .fold(Atom::num(1), |product, factor| product * factor),
20177        AtomView::Fun(function) => function.get_symbol().call_args(
20178            function
20179                .into_iter()
20180                .map(|argument| rubi_normalize_polynomial_power_lead_signs(argument, x))
20181                .collect::<Vec<_>>(),
20182        ),
20183        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
20184    }
20185}
20186
20187fn rubi_simplify_integrand_mathematica_simplify_candidate(expr: &Atom, x: Symbol) -> Option<Atom> {
20188    // Rubi's SimplifyIntegrand starts with Mathematica Simplify[u] before
20189    // NormalizeIntegrandAux.  Symbolica's generic simplify does not always
20190    // cancel algebraic common factors such as
20191    // Sqrt[1+x^2]*(1+x/Sqrt[1+x^2])/(x+Sqrt[1+x^2]), so mirror that shared
20192    // helper behavior here instead of changing individual integration rules.
20193    if let Some(simplified) = rubi_simplify_integrand_exponential_denominator_candidate(expr, x) {
20194        return Some(simplified);
20195    }
20196    if let Some(simplified) = rubi_simplify_hyperbolic_cosh_tanh_odd_cubic_candidate(expr, x) {
20197        return Some(simplified);
20198    }
20199    if let Some(simplified) = rubi_simplify_equal_power_conjugate_product(expr) {
20200        return Some(simplified);
20201    }
20202    if let Some(simplified) = rubi_simplify_trig_square_quotient_candidate(expr)
20203        && rubi_simplify_integrand_mathematica_simplify_candidate_q(expr, &simplified, x)
20204    {
20205        return Some(simplified);
20206    }
20207    let factored_radicands = rubi_factor_fractional_power_radicands(expr.as_view(), x);
20208    if factored_radicands != *expr
20209        && rubi_leaf_count(factored_radicands.as_view()) < rubi_leaf_count(expr.as_view())
20210        && rubi_equivalent_q(&factored_radicands, expr)
20211    {
20212        return Some(factored_radicands);
20213    }
20214    if rubi_contains_function_symbol(expr, Symbol::LOG) {
20215        let apart = expr.apart(x);
20216        if rubi_simplify_integrand_mathematica_simplify_candidate_q(expr, &apart, x)
20217            || rubi_log_apart_cancellation_q(expr, &apart)
20218        {
20219            return Some(apart);
20220        }
20221    }
20222    if let Some(factored) = rubi_try_factor(expr.as_view())
20223        && factored != *expr
20224        && rubi_leaf_count(factored.as_view()) < rubi_leaf_count(expr.as_view())
20225        && rubi_equivalent_q(&factored, expr)
20226    {
20227        return Some(factored);
20228    }
20229    let recursive = rubi_simplify_rational_subexpressions(expr, x);
20230    if recursive != *expr
20231        && rubi_equivalent_q(&recursive, expr)
20232        && (!rubi_contains_symbolic_fractional_power(expr.as_view())
20233            || rubi_simplify_integrand_mathematica_simplify_candidate_q(expr, &recursive, x))
20234    {
20235        return Some(recursive);
20236    }
20237
20238    for candidate in [
20239        expr.to_owned(),
20240        expr.expand(),
20241        rubi_simplify_for_integrand_normalization(expr),
20242        expr.together(),
20243    ] {
20244        if candidate != *expr
20245            && rubi_leaf_count(candidate.as_view()) < rubi_leaf_count(expr.as_view())
20246            && rubi_equivalent_q(&candidate, expr)
20247        {
20248            return Some(candidate);
20249        }
20250
20251        if let Some(simplified) = rubi_simplify_trig_square_quotient_candidate(&candidate) {
20252            if rubi_simplify_integrand_mathematica_simplify_candidate_q(expr, &simplified, x) {
20253                return Some(simplified);
20254            }
20255        }
20256
20257        if let Some(simplified) = rubi_cancel_common_denominator_candidate(&candidate, x) {
20258            if rubi_simplify_integrand_mathematica_simplify_candidate_q(expr, &simplified, x) {
20259                return Some(simplified);
20260            }
20261        }
20262
20263        if let Some(simplified) = rubi_simplify_common_denominator_sum(&candidate, x) {
20264            if rubi_simplify_integrand_mathematica_simplify_candidate_q(expr, &simplified, x) {
20265                return Some(simplified);
20266            }
20267        }
20268    }
20269
20270    None
20271}
20272
20273fn rubi_factor_fractional_power_radicands(expr: AtomView<'_>, x: Symbol) -> Atom {
20274    match expr {
20275        AtomView::Pow(power) => {
20276            let base = rubi_factor_fractional_power_radicands(power.get_base(), x);
20277            let exponent = rubi_factor_fractional_power_radicands(power.get_exp(), x);
20278            if rationalq!(exponent)
20279                && !integerq!(exponent)
20280                && !freeq!(base, x)
20281                && rubi_rational_function_q(&base, x)
20282            {
20283                let (numerator, denominator) = rational_numerator_denominator_unexpanded(&base)
20284                    .unwrap_or_else(|| (base.to_owned(), Atom::num(1)));
20285                let factored_base = numerator.factor() / denominator.factor();
20286                if factored_base != base
20287                    && rubi_leaf_count(factored_base.as_view()) < rubi_leaf_count(base.as_view())
20288                    && rubi_equivalent_q(&factored_base, &base)
20289                {
20290                    return factored_base.pow(exponent);
20291                }
20292            }
20293            base.pow(exponent)
20294        }
20295        AtomView::Add(add) => add
20296            .into_iter()
20297            .map(|term| rubi_factor_fractional_power_radicands(term, x))
20298            .fold(Atom::num(0), |sum, term| sum + term),
20299        AtomView::Mul(mul) => mul
20300            .into_iter()
20301            .map(|factor| rubi_factor_fractional_power_radicands(factor, x))
20302            .fold(Atom::num(1), |product, factor| product * factor),
20303        AtomView::Fun(function) => function.get_symbol().call_args(
20304            function
20305                .into_iter()
20306                .map(|argument| rubi_factor_fractional_power_radicands(argument, x))
20307                .collect::<Vec<_>>(),
20308        ),
20309        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
20310    }
20311}
20312
20313fn rubi_log_apart_cancellation_q(expr: &Atom, apart: &Atom) -> bool {
20314    if apart == expr || !rubi_sum_q(apart) {
20315        return false;
20316    }
20317    let together = expr.together();
20318    let Some((_, denominator)) = rational_numerator_denominator(&together) else {
20319        return false;
20320    };
20321    let denominator_leaf_count = rubi_leaf_count(denominator.as_view());
20322
20323    rubi_add_terms(apart).into_iter().any(|term| {
20324        if !rubi_contains_function_symbol(&term, Symbol::LOG) {
20325            return false;
20326        }
20327        let term_together = term.together();
20328        rational_numerator_denominator(&term_together).is_some_and(|(_, term_denominator)| {
20329            rubi_leaf_count(term_denominator.as_view()) < denominator_leaf_count
20330        })
20331    })
20332}
20333
20334fn rubi_simplify_hyperbolic_cosh_tanh_odd_cubic_candidate(expr: &Atom, x: Symbol) -> Option<Atom> {
20335    let factors = rubi_product_factors(expr);
20336    for (cosh_index, cosh_factor) in factors.iter().enumerate() {
20337        let Some((cosh_symbol, argument)) = rubi_hyperbolic_call(cosh_factor) else {
20338            continue;
20339        };
20340        if cosh_symbol.get_stripped_ascii_name() != Some("cosh") {
20341            continue;
20342        }
20343
20344        for (polynomial_index, polynomial_factor) in factors.iter().enumerate() {
20345            if polynomial_index == cosh_index || !rubi_sum_q(polynomial_factor) {
20346                continue;
20347            }
20348            let substitution_guard = fresh_substitution_symbol()?;
20349            let substitution = substitution_guard.symbol();
20350            let replaced = rubi_subst_for(polynomial_factor, &argument.tanh(), substitution);
20351            if replaced == *polynomial_factor {
20352                continue;
20353            }
20354            let Some(terms) = collect_polynomial_terms_without_expanding(&replaced, substitution)
20355            else {
20356                continue;
20357            };
20358            if terms.len() != 2 || !terms.contains_key(&1) || !terms.contains_key(&3) {
20359                continue;
20360            }
20361            let linear = terms.get(&1)?.to_owned();
20362            let cubic = terms.get(&3)?.to_owned();
20363            if !is_free_of((&linear, &cubic), x) {
20364                continue;
20365            }
20366
20367            let rest = factors
20368                .iter()
20369                .enumerate()
20370                .filter_map(|(index, factor)| {
20371                    (index != cosh_index && index != polynomial_index).then_some(factor)
20372                })
20373                .fold(Atom::num(1), |product, factor| product * factor);
20374            let doubled = Atom::num(2) * &argument;
20375            let candidate = rest
20376                * ((&linear - &cubic) + (&linear + &cubic) * doubled.cosh())
20377                * argument.sech()
20378                * argument.tanh()
20379                / 2;
20380            let exponential_candidate = rubi_hyperbolic_trig_to_exp(candidate.as_view());
20381            let exponential_expr = rubi_hyperbolic_trig_to_exp(expr.as_view());
20382            if rubi_equivalent_q(&candidate, expr)
20383                || rubi_equivalent_q(&exponential_candidate, &exponential_expr)
20384            {
20385                return Some(candidate);
20386            }
20387        }
20388    }
20389
20390    None
20391}
20392
20393fn rubi_simplify_rational_subexpressions(expr: &Atom, x: Symbol) -> Atom {
20394    match expr.as_view() {
20395        AtomView::Add(add) => {
20396            let rebuilt = add
20397                .into_iter()
20398                .map(|term| rubi_simplify_rational_subexpressions(&term.to_owned(), x))
20399                .fold(Atom::num(0), |sum, term| sum + term);
20400            if !rubi_structural_rational_function_q(rebuilt.as_view(), x) {
20401                return rebuilt;
20402            }
20403            let together = rubi_together_simplify(&rebuilt);
20404            if together != rebuilt && rubi_equivalent_q(&together, &rebuilt) {
20405                together
20406            } else {
20407                rebuilt
20408            }
20409        }
20410        AtomView::Mul(mul) => mul
20411            .into_iter()
20412            .map(|factor| rubi_simplify_rational_subexpressions(&factor.to_owned(), x))
20413            .fold(Atom::num(1), |product, factor| product * factor),
20414        AtomView::Pow(power) => {
20415            let (base, exponent) = power.get_base_exp();
20416            rubi_hold_power(
20417                &rubi_simplify_rational_subexpressions(&base.to_owned(), x),
20418                &rubi_simplify_rational_subexpressions(&exponent.to_owned(), x),
20419            )
20420        }
20421        AtomView::Fun(function) => function.get_symbol().call_args(
20422            function
20423                .into_iter()
20424                .map(|argument| rubi_simplify_rational_subexpressions(&argument.to_owned(), x))
20425                .collect::<Vec<_>>(),
20426        ),
20427        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
20428    }
20429}
20430
20431fn rubi_simplify_integrand_exponential_denominator_candidate(
20432    expr: &Atom,
20433    x: Symbol,
20434) -> Option<Atom> {
20435    let (numerator, denominator) = rational_numerator_denominator(expr)?;
20436    if denominator.is_one() {
20437        return None;
20438    }
20439
20440    let function = rubi_function_of_exponential(denominator.as_view(), x)?;
20441    let function_denominator =
20442        rubi_simplify_function_of_exponential_denominator(&function.function);
20443    let simplified_denominator = rubi_subst(&function_denominator, x, function.exponential);
20444    if simplified_denominator == denominator {
20445        return None;
20446    }
20447
20448    let simplified = numerator / simplified_denominator;
20449    if rubi_simplify_integrand_mathematica_simplify_result_q(expr, &simplified) {
20450        Some(simplified)
20451    } else {
20452        None
20453    }
20454}
20455
20456fn rubi_simplify_function_of_exponential_denominator(expr: &Atom) -> Atom {
20457    if let Some(factored) = rubi_try_factor(expr.as_view()) {
20458        if factored != *expr
20459            && rubi_equivalent_q(&factored, expr)
20460            && rubi_leaf_count(factored.as_view()) <= rubi_leaf_count(expr.as_view())
20461        {
20462            return factored;
20463        }
20464    }
20465
20466    expr.to_owned()
20467}
20468
20469fn rubi_simplify_integrand_mathematica_simplify_result_q(expr: &Atom, simplified: &Atom) -> bool {
20470    if simplified == expr {
20471        return false;
20472    }
20473    if !rubi_equivalent_q(simplified, expr) {
20474        return false;
20475    }
20476
20477    let normalized = rubi_normalize_lead_term_signs(simplified);
20478    if 5 * rubi_leaf_count(normalized.as_view()) < 4 * rubi_leaf_count(expr.as_view()) {
20479        return true;
20480    }
20481
20482    normalized != rubi_normalize_lead_term_signs(expr)
20483}
20484
20485fn rubi_simplify_integrand_mathematica_simplify_candidate_q(
20486    expr: &Atom,
20487    simplified: &Atom,
20488    x: Symbol,
20489) -> bool {
20490    if simplified == expr {
20491        return false;
20492    }
20493    if rubi_contains_function_symbol(expr, Symbol::SIN)
20494        && rubi_contains_function_symbol(expr, Symbol::COS)
20495        && rubi_contains_function_name(simplified, "tan")
20496    {
20497        return true;
20498    }
20499    if !rubi_simpler_integrand_q(simplified, expr, x) {
20500        return rubi_leaf_count(simplified.as_view()) < rubi_leaf_count(expr.as_view());
20501    }
20502    if rubi_leaf_count(simplified.as_view()) < rubi_leaf_count(expr.as_view()) {
20503        return true;
20504    }
20505    if simplified.is_one() {
20506        return true;
20507    }
20508    (rubi_contains_function_symbol(expr, Symbol::LOG)
20509        && rubi_contains_function_symbol(simplified, Symbol::LOG))
20510        || (rubi_contains_function_name(expr, "atan")
20511            && rubi_contains_function_name(simplified, "atan"))
20512        || (rubi_contains_function_name(expr, "acot")
20513            && rubi_contains_function_name(simplified, "acot"))
20514}
20515
20516fn rubi_contains_function_symbol(expr: &Atom, symbol: Symbol) -> bool {
20517    fn recur(expr: AtomView<'_>, symbol: Symbol) -> bool {
20518        match expr {
20519            AtomView::Fun(function) => {
20520                function.get_symbol() == symbol
20521                    || function.into_iter().any(|argument| recur(argument, symbol))
20522            }
20523            AtomView::Add(add) => add.into_iter().any(|term| recur(term, symbol)),
20524            AtomView::Mul(mul) => mul.into_iter().any(|factor| recur(factor, symbol)),
20525            AtomView::Pow(power) => {
20526                recur(power.get_base(), symbol) || recur(power.get_exp(), symbol)
20527            }
20528            AtomView::Num(_) | AtomView::Var(_) => false,
20529        }
20530    }
20531
20532    recur(expr.as_view(), symbol)
20533}
20534
20535fn rubi_contains_function_name(expr: &Atom, name: &str) -> bool {
20536    fn recur(expr: AtomView<'_>, name: &str) -> bool {
20537        match expr {
20538            AtomView::Fun(function) => {
20539                rubi_symbol_name_eq(function.get_symbol(), name)
20540                    || function.into_iter().any(|argument| recur(argument, name))
20541            }
20542            AtomView::Add(add) => add.into_iter().any(|term| recur(term, name)),
20543            AtomView::Mul(mul) => mul.into_iter().any(|factor| recur(factor, name)),
20544            AtomView::Pow(power) => recur(power.get_base(), name) || recur(power.get_exp(), name),
20545            AtomView::Num(_) | AtomView::Var(_) => false,
20546        }
20547    }
20548
20549    recur(expr.as_view(), name)
20550}
20551
20552fn rubi_cancel_common_denominator_candidate(expr: &Atom, x: Symbol) -> Option<Atom> {
20553    let (numerator, denominator) = rational_numerator_denominator(expr)?;
20554    if denominator.is_one() {
20555        return None;
20556    }
20557
20558    for numerator in rubi_common_denominator_numerator_candidates(&numerator, x) {
20559        if numerator == denominator {
20560            return Some(Atom::num(1));
20561        }
20562
20563        if let Some(reduced) = rubi_cancel_common_product_factor(&numerator, &denominator) {
20564            return Some(reduced);
20565        }
20566    }
20567
20568    None
20569}
20570
20571fn rubi_simplify_common_denominator_sum(expr: &Atom, x: Symbol) -> Option<Atom> {
20572    let AtomView::Add(_) = expr.as_view() else {
20573        return None;
20574    };
20575
20576    let mut denominator: Option<Atom> = None;
20577    let mut numerator = Atom::num(0);
20578    for term in rubi_add_terms(expr) {
20579        let (term_numerator, term_denominator) = rational_numerator_denominator(&term)?;
20580        if term_denominator.is_one() {
20581            return None;
20582        }
20583        match &denominator {
20584            Some(denominator) if denominator != &term_denominator => return None,
20585            None => denominator = Some(term_denominator.to_owned()),
20586            _ => {}
20587        }
20588        numerator += term_numerator;
20589    }
20590
20591    let denominator = denominator?;
20592    for numerator in rubi_common_denominator_numerator_candidates(&numerator, x) {
20593        if numerator == denominator {
20594            return Some(Atom::num(1));
20595        }
20596        if let Some(reduced) = rubi_cancel_common_product_factor(&numerator, &denominator) {
20597            if reduced != *expr {
20598                return Some(reduced);
20599            }
20600        }
20601    }
20602    None
20603}
20604
20605fn rubi_common_denominator_numerator_candidates(numerator: &Atom, x: Symbol) -> Vec<Atom> {
20606    let mut candidates = Vec::new();
20607    if let Some(factored) = rubi_factor_common_symbolic_terms_unexpanded(numerator, x) {
20608        candidates.push(factored);
20609    }
20610    if let Some(factored) = rubi_factor_common_symbolic_terms(numerator, x) {
20611        candidates.push(factored);
20612    }
20613    if let Some(factored) = rubi_try_factor(numerator.as_view()) {
20614        candidates.push(factored);
20615    }
20616    candidates.push(numerator.to_owned());
20617    candidates
20618}
20619
20620fn rubi_cancel_common_product_factor(numerator: &Atom, denominator: &Atom) -> Option<Atom> {
20621    let factors = rubi_product_factors(numerator);
20622    let index = factors.iter().position(|factor| factor == denominator)?;
20623    Some(
20624        factors
20625            .into_iter()
20626            .enumerate()
20627            .filter_map(|(factor_index, factor)| (factor_index != index).then_some(factor))
20628            .fold(Atom::num(1), |product, factor| product * factor),
20629    )
20630}
20631
20632fn rubi_simplify_trig_square_quotient_candidate(expr: &Atom) -> Option<Atom> {
20633    let factors = rubi_product_factors(expr);
20634    let (radical_index, angle) = factors.iter().enumerate().find_map(|(index, factor)| {
20635        rubi_negative_half_power_of_one_minus_sin_square(factor).map(|angle| (index, angle))
20636    })?;
20637    let cos_index = factors.iter().enumerate().find_map(|(index, factor)| {
20638        (index != radical_index)
20639            .then(|| rubi_active_trig_function(factor))
20640            .flatten()
20641            .and_then(|(symbol, argument)| {
20642                (rubi_trig_symbol_family(symbol) == Some(RubiTrigFamily::Cos) && argument == angle)
20643                    .then_some(index)
20644            })
20645    })?;
20646    let (sin_index, sin_exponent) = factors.iter().enumerate().find_map(|(index, factor)| {
20647        (index != radical_index && index != cos_index)
20648            .then(|| rubi_positive_integer_power_of_trig(factor, RubiTrigFamily::Sin, &angle))
20649            .flatten()
20650            .map(|exponent| (index, exponent))
20651    })?;
20652    if sin_exponent < 1 {
20653        return None;
20654    }
20655
20656    let rest = factors
20657        .iter()
20658        .enumerate()
20659        .filter_map(|(index, factor)| {
20660            (index != radical_index && index != cos_index && index != sin_index).then_some(factor)
20661        })
20662        .fold(Atom::num(1), |product, factor| product * factor);
20663    let sin_power = if sin_exponent == 1 {
20664        Atom::num(1)
20665    } else {
20666        angle.sin().pow(sin_exponent - 1)
20667    };
20668
20669    Some(rest * angle.cos().pow(2).sqrt() * sin_power * angle.tan())
20670}
20671
20672fn rubi_negative_half_power_of_one_minus_sin_square(expr: &Atom) -> Option<Atom> {
20673    let AtomView::Pow(power) = expr.as_view() else {
20674        return None;
20675    };
20676    let exponent = power.get_exp().to_owned();
20677    (rational_number(&exponent) == Some((-1, 2)))
20678        .then(|| power.get_base().to_owned())
20679        .and_then(|base| rubi_one_minus_sin_square_angle(&base))
20680}
20681
20682fn rubi_one_minus_sin_square_angle(expr: &Atom) -> Option<Atom> {
20683    let AtomView::Add(add) = expr.as_view() else {
20684        return None;
20685    };
20686    let terms = add
20687        .into_iter()
20688        .map(|term| term.to_owned())
20689        .collect::<Vec<_>>();
20690    if terms.len() != 2 {
20691        return None;
20692    }
20693
20694    for one_index in 0..2 {
20695        if !terms[one_index].is_one() {
20696            continue;
20697        }
20698        let negative_sin_square = -terms[1 - one_index].to_owned();
20699        if let Some(angle) = rubi_sin_square_angle(&negative_sin_square) {
20700            return Some(angle);
20701        }
20702    }
20703    None
20704}
20705
20706fn rubi_sin_square_angle(expr: &Atom) -> Option<Atom> {
20707    let AtomView::Pow(power) = expr.as_view() else {
20708        return None;
20709    };
20710    if integer_i64_view(power.get_exp())? != 2 {
20711        return None;
20712    }
20713    let (symbol, angle) = rubi_active_trig_function(&power.get_base().to_owned())?;
20714    (rubi_trig_symbol_family(symbol) == Some(RubiTrigFamily::Sin)).then_some(angle)
20715}
20716
20717fn rubi_positive_integer_power_of_trig(
20718    expr: &Atom,
20719    family: RubiTrigFamily,
20720    angle: &Atom,
20721) -> Option<i64> {
20722    if let Some((symbol, argument)) = rubi_active_trig_function(expr)
20723        && rubi_trig_symbol_family(symbol) == Some(family)
20724        && argument == *angle
20725    {
20726        return Some(1);
20727    }
20728
20729    let AtomView::Pow(power) = expr.as_view() else {
20730        return None;
20731    };
20732    let exponent = integer_i64_view(power.get_exp())?;
20733    if exponent <= 0 {
20734        return None;
20735    }
20736    let (symbol, argument) = rubi_active_trig_function(&power.get_base().to_owned())?;
20737    (rubi_trig_symbol_family(symbol) == Some(family) && argument == *angle).then_some(exponent)
20738}
20739
20740fn rubi_simplify_integrand_normalized_candidate(expr: &Atom, x: Symbol) -> Option<Atom> {
20741    for candidate in [expr.to_owned(), rubi_mathematica_simplify(expr)] {
20742        let normalized =
20743            rubi_normalize_lead_term_signs(&rubi_normalize_integrand_aux(&candidate, x));
20744        let normalized = rubi_recombine_simpler_polynomial_factors(&normalized, x);
20745        if rubi_log_rational_product_q(&normalized, x) {
20746            return Some(normalized);
20747        }
20748        let normalized_leaf_count = rubi_leaf_count(normalized.as_view());
20749        let expr_leaf_count = rubi_leaf_count(expr.as_view());
20750        let lead_term_normalized =
20751            rubi_normalize_lead_term_signs(&normalized) != rubi_normalize_lead_term_signs(expr);
20752        if 5 * normalized_leaf_count < 4 * expr_leaf_count || lead_term_normalized {
20753            return Some(normalized);
20754        }
20755    }
20756
20757    None
20758}
20759
20760fn rubi_simplify_for_integrand_normalization(expr: &Atom) -> Atom {
20761    let simplified = rubi_simplify(expr);
20762    let together = rubi_together(expr);
20763    if rubi_leaf_count(together.as_view()) < rubi_leaf_count(simplified.as_view()) {
20764        together
20765    } else {
20766        simplified
20767    }
20768}
20769
20770fn rubi_log_rational_product_q(expr: &Atom, x: Symbol) -> bool {
20771    let factors = rubi_product_factors(expr);
20772    if factors.len() < 2 {
20773        return false;
20774    }
20775
20776    let mut saw_log = false;
20777    let mut rational_factors = Vec::new();
20778    for factor in factors {
20779        if rubi_log_product_factor_q(&factor, x) {
20780            saw_log = true;
20781        } else {
20782            rational_factors.push(factor);
20783        }
20784    }
20785
20786    saw_log && rubi_rational_function_q(&product_atoms(&rational_factors), x)
20787}
20788
20789fn rubi_recombine_simpler_polynomial_factors(expr: &Atom, x: Symbol) -> Atom {
20790    match expr.as_view() {
20791        AtomView::Mul(mul) => {
20792            let mut factors = mul
20793                .into_iter()
20794                .map(|factor| rubi_recombine_simpler_polynomial_factors(&factor.to_owned(), x))
20795                .collect::<Vec<_>>();
20796
20797            let mut changed = true;
20798            while changed {
20799                changed = false;
20800                'outer: for left in 0..factors.len() {
20801                    if !rubi_small_polynomial_factor_q(&factors[left], x) {
20802                        continue;
20803                    }
20804                    for right in (left + 1)..factors.len() {
20805                        if !rubi_small_polynomial_factor_q(&factors[right], x) {
20806                            continue;
20807                        }
20808                        let product = &factors[left] * &factors[right];
20809                        let expanded = product.expand();
20810                        if polynomial_degree(&expanded, x).is_some()
20811                            && rubi_leaf_count(expanded.as_view())
20812                                < rubi_leaf_count(product.as_view())
20813                        {
20814                            factors[left] = expanded;
20815                            let _ = factors.remove(right);
20816                            changed = true;
20817                            break 'outer;
20818                        }
20819                    }
20820                }
20821            }
20822
20823            factors
20824                .into_iter()
20825                .fold(Atom::num(1), |product, factor| product * factor)
20826        }
20827        AtomView::Add(add) => add
20828            .into_iter()
20829            .map(|term| rubi_recombine_simpler_polynomial_factors(&term.to_owned(), x))
20830            .fold(Atom::num(0), |sum, term| sum + term),
20831        AtomView::Pow(power) => {
20832            let (base, exponent) = power.get_base_exp();
20833            rubi_recombine_simpler_polynomial_factors(&base.to_owned(), x).pow(
20834                rubi_recombine_simpler_polynomial_factors(&exponent.to_owned(), x),
20835            )
20836        }
20837        AtomView::Fun(fun) => fun
20838            .get_symbol()
20839            .call_args(fun.into_iter().map(|argument| {
20840                rubi_recombine_simpler_polynomial_factors(&argument.to_owned(), x)
20841            })),
20842        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
20843    }
20844}
20845
20846fn rubi_recombine_simpler_polynomial_inverse_factors(expr: &Atom, x: Symbol) -> Atom {
20847    let AtomView::Mul(mul) = expr.as_view() else {
20848        return expr.to_owned();
20849    };
20850    let mut factors = mul
20851        .into_iter()
20852        .map(|factor| factor.to_owned())
20853        .collect::<Vec<_>>();
20854    let mut changed = false;
20855
20856    'outer: for left in 0..factors.len() {
20857        let Some((left_base, left_exponent)) =
20858            rubi_small_polynomial_factor_power(&factors[left], x)
20859        else {
20860            continue;
20861        };
20862        if left_exponent != Atom::num(-1) || !rubi_sum_q(&left_base) {
20863            continue;
20864        }
20865        for right in (left + 1)..factors.len() {
20866            let Some((right_base, right_exponent)) =
20867                rubi_small_polynomial_factor_power(&factors[right], x)
20868            else {
20869                continue;
20870            };
20871            if right_exponent != Atom::num(-1) || !rubi_sum_q(&right_base) {
20872                continue;
20873            }
20874
20875            let product = &factors[left] * &factors[right];
20876            let expanded_base = (&left_base * &right_base).expand();
20877            let expanded = expanded_base.pow(-1);
20878            if rubi_leaf_count(expanded.as_view()) < rubi_leaf_count(product.as_view()) {
20879                factors[left] = expanded;
20880                let _ = factors.remove(right);
20881                changed = true;
20882                break 'outer;
20883            }
20884        }
20885    }
20886
20887    if changed {
20888        product_atoms(&factors)
20889    } else {
20890        expr.to_owned()
20891    }
20892}
20893
20894fn rubi_small_polynomial_factor_q(expr: &Atom, x: Symbol) -> bool {
20895    rubi_leaf_count(expr.as_view()) <= 12 && polynomial_degree(expr, x).is_some()
20896}
20897
20898fn rubi_small_polynomial_factor_power(expr: &Atom, x: Symbol) -> Option<(Atom, Atom)> {
20899    if rubi_small_polynomial_factor_q(expr, x) {
20900        return Some((expr.to_owned(), Atom::num(1)));
20901    }
20902
20903    let AtomView::Pow(power) = expr.as_view() else {
20904        return None;
20905    };
20906    let base = power.get_base().to_owned();
20907    let exponent = power.get_exp().to_owned();
20908    (integer_i64(&exponent).is_some() && rubi_small_polynomial_factor_q(&base, x))
20909        .then_some((base, exponent))
20910}
20911
20912fn rubi_factor_common_symbolic_rational_numerator(expr: &Atom, x: Symbol) -> Option<Atom> {
20913    let (numerator, denominator) = rational_numerator_denominator(expr)?;
20914    if denominator == Atom::num(1) {
20915        return None;
20916    }
20917
20918    let factored_numerator = rubi_factor_common_symbolic_terms(&numerator, x)?;
20919    if factored_numerator == numerator {
20920        return None;
20921    }
20922
20923    Some(factored_numerator / denominator)
20924}
20925
20926fn rubi_normalize_integrand_function_arguments(expr: &Atom, x: Symbol) -> Option<Atom> {
20927    match expr.as_view() {
20928        AtomView::Fun(fun) => {
20929            let mut changed = false;
20930            let arguments = fun
20931                .into_iter()
20932                .map(|argument| {
20933                    let argument = argument.to_owned();
20934                    let normalized = rubi_normalize_integrand_function_arguments(&argument, x)
20935                        .unwrap_or(argument);
20936                    if rubi_linear_q(normalized.as_view(), x)
20937                        && !rubi_linear_match_q(&normalized, x)
20938                    {
20939                        if let Some((constant, slope)) =
20940                            linear_coefficients(normalized.as_view(), x)
20941                        {
20942                            let candidate = (constant + slope * Atom::var(x)).expand();
20943                            if candidate != normalized {
20944                                changed = true;
20945                                return candidate;
20946                            }
20947                        }
20948                    }
20949                    normalized
20950                })
20951                .collect::<Vec<_>>();
20952            if changed {
20953                Some(fun.get_symbol().call_args(arguments))
20954            } else {
20955                None
20956            }
20957        }
20958        AtomView::Add(add) => {
20959            let mut changed = false;
20960            let terms = add
20961                .into_iter()
20962                .map(|term| {
20963                    let term = term.to_owned();
20964                    if let Some(normalized) = rubi_normalize_integrand_function_arguments(&term, x)
20965                    {
20966                        changed = true;
20967                        normalized
20968                    } else {
20969                        term
20970                    }
20971                })
20972                .collect::<Vec<_>>();
20973            changed.then(|| terms.into_iter().fold(Atom::num(0), |sum, term| sum + term))
20974        }
20975        AtomView::Mul(mul) => {
20976            let mut changed = false;
20977            let factors = mul
20978                .into_iter()
20979                .map(|factor| {
20980                    let factor = factor.to_owned();
20981                    if let Some(normalized) =
20982                        rubi_normalize_integrand_function_arguments(&factor, x)
20983                    {
20984                        changed = true;
20985                        normalized
20986                    } else {
20987                        factor
20988                    }
20989                })
20990                .collect::<Vec<_>>();
20991            changed.then(|| product_atoms(&factors))
20992        }
20993        AtomView::Pow(power) => {
20994            let (base, exponent) = power.get_base_exp();
20995            let base = base.to_owned();
20996            let exponent = exponent.to_owned();
20997            let normalized_base = rubi_normalize_integrand_function_arguments(&base, x);
20998            let normalized_exponent = rubi_normalize_integrand_function_arguments(&exponent, x);
20999            match (normalized_base, normalized_exponent) {
21000                (None, None) => None,
21001                (normalized_base, normalized_exponent) => Some(
21002                    normalized_base
21003                        .unwrap_or(base)
21004                        .pow(normalized_exponent.unwrap_or(exponent)),
21005                ),
21006            }
21007        }
21008        AtomView::Num(_) | AtomView::Var(_) => None,
21009    }
21010}
21011
21012fn rubi_normalize_laurent_power_sum(expr: &Atom, x: Symbol) -> Option<Atom> {
21013    match expr.as_view() {
21014        AtomView::Pow(power) => {
21015            let exponent = power.get_exp().to_owned();
21016            let exponent_integer = integer_i64(&exponent)?;
21017            if exponent_integer >= 0 {
21018                return None;
21019            }
21020
21021            let base = power.get_base().to_owned();
21022            let terms = collect_laurent_terms(&base, x)?;
21023            let min_degree = *terms.keys().next()?;
21024            if min_degree >= 0 {
21025                return None;
21026            }
21027
21028            let shifted_base =
21029                terms
21030                    .into_iter()
21031                    .fold(Atom::num(0), |sum, (degree, coefficient)| {
21032                        sum + coefficient * rubi_variable_power(x, Atom::num(degree - min_degree))
21033                    });
21034            let normalized = rubi_variable_power(x, Atom::num(min_degree * exponent_integer))
21035                * shifted_base.pow(exponent);
21036            if normalized == *expr {
21037                None
21038            } else {
21039                Some(normalized)
21040            }
21041        }
21042        AtomView::Mul(mul) => {
21043            let mut changed = false;
21044            let factors = mul
21045                .into_iter()
21046                .map(|factor| {
21047                    let factor = factor.to_owned();
21048                    if let Some(normalized) = rubi_normalize_laurent_power_sum(&factor, x) {
21049                        changed = true;
21050                        normalized
21051                    } else {
21052                        factor
21053                    }
21054                })
21055                .collect::<Vec<_>>();
21056            changed.then(|| product_atoms(&factors))
21057        }
21058        _ => None,
21059    }
21060}
21061
21062fn rubi_factor_common_symbolic_terms(expr: &Atom, x: Symbol) -> Option<Atom> {
21063    let (common, sum) = rubi_factor_common_symbolic_terms_parts(expr, x)?;
21064    Some(rubi_simp(&(common * sum), x))
21065}
21066
21067fn rubi_factor_common_symbolic_terms_unexpanded(expr: &Atom, x: Symbol) -> Option<Atom> {
21068    let (common, sum) = rubi_factor_common_symbolic_terms_parts(expr, x)?;
21069    Some(common * sum)
21070}
21071
21072fn rubi_factor_common_symbolic_terms_parts(expr: &Atom, x: Symbol) -> Option<(Atom, Atom)> {
21073    let AtomView::Add(add) = expr.as_view() else {
21074        return None;
21075    };
21076    let mut terms: Vec<Vec<Atom>> = add
21077        .into_iter()
21078        .map(|term| rubi_product_factors(&term.to_owned()))
21079        .collect();
21080    if terms.len() < 2 {
21081        return None;
21082    }
21083
21084    let mut common = Vec::new();
21085    let mut changed = false;
21086    loop {
21087        let mut factored_one = false;
21088        let first_factors = terms.first()?.to_owned();
21089        for candidate in first_factors {
21090            let mut next_terms = Vec::with_capacity(terms.len());
21091            let mut residual_common = Vec::with_capacity(terms.len());
21092            let mut matched_all = true;
21093            for term in &terms {
21094                let Some((rest, residual)) =
21095                    rubi_remove_common_symbolic_factor(term, &candidate, x)
21096                else {
21097                    matched_all = false;
21098                    break;
21099                };
21100                next_terms.push(rest);
21101                residual_common.push(residual);
21102            }
21103
21104            if !matched_all {
21105                continue;
21106            }
21107
21108            common.push(candidate);
21109            terms = next_terms
21110                .into_iter()
21111                .zip(residual_common)
21112                .map(|(mut factors, residual)| {
21113                    if !eqq!(residual, 1) {
21114                        factors.push(residual);
21115                    }
21116                    factors
21117                })
21118                .collect();
21119            changed = true;
21120            factored_one = true;
21121            break;
21122        }
21123
21124        if !factored_one {
21125            break;
21126        }
21127    }
21128
21129    if !changed {
21130        return None;
21131    }
21132
21133    let common = product_atoms(&common);
21134    let sum = terms
21135        .into_iter()
21136        .map(|factors| product_atoms(&factors))
21137        .fold(Atom::num(0), |sum, term| sum + term);
21138    Some((common, sum))
21139}
21140
21141fn rubi_product_factors(expr: &Atom) -> Vec<Atom> {
21142    match expr.as_view() {
21143        AtomView::Mul(mul) => mul.into_iter().map(|factor| factor.to_owned()).collect(),
21144        _ => vec![expr.to_owned()],
21145    }
21146}
21147
21148fn rubi_remove_common_symbolic_factor(
21149    factors: &[Atom],
21150    candidate: &Atom,
21151    x: Symbol,
21152) -> Option<(Vec<Atom>, Atom)> {
21153    for (index, factor) in factors.iter().enumerate() {
21154        if factor == candidate {
21155            let mut rest = factors.to_vec();
21156            let _ = rest.remove(index);
21157            return Some((rest, Atom::num(1)));
21158        }
21159
21160        let Some(residual) = rubi_power_factor_residual(factor, candidate, x) else {
21161            continue;
21162        };
21163        let mut rest = factors.to_vec();
21164        let _ = rest.remove(index);
21165        return Some((rest, residual));
21166    }
21167
21168    None
21169}
21170
21171fn rubi_power_factor_residual(factor: &Atom, candidate: &Atom, x: Symbol) -> Option<Atom> {
21172    if let AtomView::Pow(factor_power) = factor.as_view()
21173        && factor_power.get_base().to_owned() == *candidate
21174        && let Some(exponent) = integer_i64_view(factor_power.get_exp())
21175        && exponent >= 1
21176    {
21177        return Some(if exponent == 1 {
21178            Atom::num(1)
21179        } else {
21180            candidate.pow(exponent - 1)
21181        });
21182    }
21183
21184    let AtomView::Pow(factor_power) = factor.as_view() else {
21185        return None;
21186    };
21187    let AtomView::Pow(candidate_power) = candidate.as_view() else {
21188        return None;
21189    };
21190    let factor_base = factor_power.get_base().to_owned();
21191    let candidate_base = candidate_power.get_base().to_owned();
21192    if factor_base != candidate_base || is_free_of(&factor_base, x) {
21193        return None;
21194    }
21195
21196    let factor_exponent = factor_power.get_exp().to_owned();
21197    let candidate_exponent = candidate_power.get_exp().to_owned();
21198    let difference = rubi_simplify(&(&factor_exponent - &candidate_exponent));
21199    if let Some(difference) = integer_i64(&difference) {
21200        return (difference >= 0).then(|| {
21201            if difference == 0 {
21202                Atom::num(1)
21203            } else {
21204                factor_base.pow(difference)
21205            }
21206        });
21207    }
21208
21209    let ratio = rubi_simplify(&(factor_exponent / &candidate_exponent));
21210    let ratio = integer_i64(&ratio)?;
21211    (ratio >= 1).then(|| factor_base.pow((ratio - 1) * candidate_exponent))
21212}
21213
21214fn rubi_normalize_powered_monomial_binomial_derivative(expr: &Atom, x: Symbol) -> Option<Atom> {
21215    let factors = match expr.as_view() {
21216        AtomView::Mul(mul) => mul
21217            .into_iter()
21218            .map(|factor| factor.to_owned())
21219            .collect::<Vec<_>>(),
21220        _ => vec![expr.to_owned()],
21221    };
21222
21223    for (index, factor) in factors.iter().enumerate() {
21224        let AtomView::Pow(power) = factor.as_view() else {
21225            continue;
21226        };
21227        let (base, exponent) = power.get_base_exp();
21228        let Some(p) = integer_i64_view(exponent) else {
21229            continue;
21230        };
21231        if p >= -1 {
21232            continue;
21233        }
21234
21235        let (common_power, denominator_base) =
21236            rubi_factor_common_integer_variable_power_from_sum(&base.to_owned(), x)?;
21237        let (a, b, n) = rubi_constant_plus_monomial_parts(&denominator_base, x)?;
21238        if a.is_zero() || b.is_zero() {
21239            continue;
21240        }
21241
21242        let mut rest_factors = factors.to_owned();
21243        let _ = rest_factors.remove(index);
21244        let rest = product_atoms(&rest_factors);
21245        let Some((numerator, monomial_rest)) = rubi_split_product(
21246            |candidate| rubi_derivative_binomial_numerator_q(candidate, &a, &b, &n, x),
21247            &rest,
21248        ) else {
21249            continue;
21250        };
21251        let (monomial_exponent, monomial_coefficient) =
21252            rubi_symbolic_monomial_term(&monomial_rest, x)?;
21253        let expected_exponent =
21254            (&n - Atom::num(1) + (&n - Atom::num(common_power)) * Atom::num(p)).expand();
21255        if !eqq!((monomial_exponent - expected_exponent).expand(), 0) {
21256            continue;
21257        }
21258
21259        let x_atom = Atom::var(x);
21260        let y = x_atom.pow(&n) * (&a + &b * x_atom.pow(&n));
21261        let normalized =
21262            monomial_coefficient * x_atom.pow(&n - Atom::num(1)) * numerator * y.pow(p);
21263        if normalized != *expr {
21264            return Some(normalized);
21265        }
21266    }
21267
21268    None
21269}
21270
21271fn rubi_derivative_binomial_numerator_q(
21272    expr: &Atom,
21273    a: &Atom,
21274    b: &Atom,
21275    n: &Atom,
21276    x: Symbol,
21277) -> bool {
21278    let Some((num_a, num_b, num_n)) = rubi_constant_plus_monomial_parts(expr, x) else {
21279        return false;
21280    };
21281
21282    eqq!((num_n - n).expand(), 0)
21283        && eqq!((num_a - a).expand(), 0)
21284        && eqq!((num_b - Atom::num(2) * b).expand(), 0)
21285}
21286
21287fn rubi_simpler_integrand_q(u: &Atom, v: &Atom, x: Symbol) -> bool {
21288    if rubi_simplify_trig_square_quotient_candidate(v).is_some_and(|candidate| candidate == *u) {
21289        return true;
21290    }
21291
21292    let (u, v) = rubi_cancel_common_factors(u, v);
21293
21294    if 10 * rubi_leaf_count(u.as_view()) < 6 * rubi_leaf_count(v.as_view()) {
21295        return true;
21296    }
21297
21298    if !rubi_rational_function_q(&u, x) {
21299        return false;
21300    }
21301    if !rubi_rational_function_q(&v, x) {
21302        return true;
21303    }
21304
21305    match (
21306        rubi_rational_function_exponents(u.as_view(), x),
21307        rubi_rational_function_exponents(v.as_view(), x),
21308    ) {
21309        (Some((u_num, u_den)), Some((v_num, v_den))) => u_num + u_den < v_num + v_den,
21310        _ => false,
21311    }
21312}
21313
21314fn rubi_cancel_common_factors(u: &Atom, v: &Atom) -> (Atom, Atom) {
21315    let mut u_factors = rubi_product_factors(u);
21316    let mut v_factors = rubi_product_factors(v);
21317
21318    let mut index = 0;
21319    while index < u_factors.len() {
21320        if let Some(other_index) = v_factors
21321            .iter()
21322            .position(|factor| factor == &u_factors[index])
21323        {
21324            let _ = u_factors.remove(index);
21325            let _ = v_factors.remove(other_index);
21326        } else {
21327            index += 1;
21328        }
21329    }
21330
21331    (product_atoms(&u_factors), product_atoms(&v_factors))
21332}
21333
21334fn rubi_simplify_monomial_binomial_quotient(expr: &Atom, x: Symbol) -> Option<Atom> {
21335    let (numerator, denominator) = rational_numerator_denominator(expr)?;
21336    if denominator == Atom::num(1) {
21337        return None;
21338    }
21339
21340    let (common_power, denominator_base) =
21341        rubi_factor_common_integer_variable_power_from_sum(&denominator, x)?;
21342    let (a, b, n) = rubi_constant_plus_monomial_parts(&denominator_base, x)?;
21343    if a.is_zero() {
21344        return None;
21345    }
21346
21347    let (num_a, num_b, num_n) = rubi_constant_plus_monomial_parts(&numerator, x)?;
21348    if !eqq!((num_n - &n).expand(), 0) {
21349        return None;
21350    }
21351
21352    let x_atom = Atom::var(x);
21353    let first = &num_a * rubi_variable_power(x, Atom::num(-common_power)) / &a;
21354    let remainder = (&num_b - &num_a * &b / &a).expand();
21355    let second = if remainder.is_zero() {
21356        Atom::num(0)
21357    } else {
21358        remainder * rubi_variable_power(x, (&n - Atom::num(common_power)).expand())
21359            / (&a + &b * x_atom.pow(&n))
21360    };
21361    let simplified = first + second;
21362
21363    if simplified != *expr {
21364        Some(simplified)
21365    } else {
21366        None
21367    }
21368}
21369
21370fn rubi_factor_common_integer_variable_power_from_sum(
21371    expr: &Atom,
21372    x: Symbol,
21373) -> Option<(i64, Atom)> {
21374    let terms = rubi_symbolic_monomial_terms(expr, x)?;
21375    let common_power = terms
21376        .iter()
21377        .filter_map(|(exponent, _)| integer_i64(exponent))
21378        .filter(|exponent| *exponent > 0)
21379        .min()?;
21380
21381    let mut reduced = Atom::num(0);
21382    for (exponent, coefficient) in terms {
21383        let reduced_exponent = (&exponent - Atom::num(common_power)).expand();
21384        if !is_free_of(&reduced_exponent, x) {
21385            return None;
21386        }
21387        if integer_i64(&reduced_exponent).is_some_and(|integer| integer < 0) {
21388            return None;
21389        }
21390
21391        reduced += coefficient * rubi_variable_power(x, reduced_exponent);
21392    }
21393
21394    Some((common_power, reduced))
21395}
21396
21397fn rubi_constant_plus_monomial_parts(expr: &Atom, x: Symbol) -> Option<(Atom, Atom, Atom)> {
21398    let terms = rubi_symbolic_monomial_terms(expr, x)?;
21399    if terms.len() != 2 {
21400        return None;
21401    }
21402
21403    let mut constant = None;
21404    let mut monomial = None;
21405    for (exponent, coefficient) in terms {
21406        if eqq!(exponent, 0) {
21407            constant = Some(coefficient);
21408        } else {
21409            monomial = Some((coefficient, exponent));
21410        }
21411    }
21412
21413    let constant = constant?;
21414    let (coefficient, exponent) = monomial?;
21415    if coefficient.is_zero() || !is_free_of(&exponent, x) {
21416        return None;
21417    }
21418
21419    Some((constant, coefficient, exponent))
21420}
21421
21422fn rubi_symbolic_monomial_terms(expr: &Atom, x: Symbol) -> Option<Vec<(Atom, Atom)>> {
21423    let raw_terms = match expr.as_view() {
21424        AtomView::Add(add) => add
21425            .into_iter()
21426            .map(|term| rubi_symbolic_monomial_term(&term.to_owned(), x))
21427            .collect::<Option<Vec<_>>>()?,
21428        _ => vec![rubi_symbolic_monomial_term(expr, x)?],
21429    };
21430
21431    let mut terms: Vec<(Atom, Atom)> = Vec::new();
21432    for (exponent, coefficient) in raw_terms {
21433        if coefficient.is_zero() {
21434            continue;
21435        }
21436        if let Some((_, existing_coefficient)) = terms
21437            .iter_mut()
21438            .find(|(existing_exponent, _)| eqq!((existing_exponent - &exponent).expand(), 0))
21439        {
21440            *existing_coefficient += coefficient;
21441        } else {
21442            terms.push((exponent, coefficient));
21443        }
21444    }
21445
21446    Some(terms)
21447}
21448
21449fn rubi_symbolic_monomial_term(term: &Atom, x: Symbol) -> Option<(Atom, Atom)> {
21450    let x_atom = Atom::var(x);
21451    let mut coefficient = Atom::num(1);
21452    let mut exponent = Atom::num(0);
21453
21454    let factors = match term.as_view() {
21455        AtomView::Mul(mul) => mul
21456            .into_iter()
21457            .map(|factor| factor.to_owned())
21458            .collect::<Vec<_>>(),
21459        _ => vec![term.to_owned()],
21460    };
21461
21462    for factor in factors {
21463        if is_free_of(&factor, x) {
21464            coefficient *= factor;
21465            continue;
21466        }
21467
21468        if factor == x_atom {
21469            exponent += Atom::num(1);
21470            continue;
21471        }
21472
21473        let AtomView::Pow(power) = factor.as_view() else {
21474            return None;
21475        };
21476        let (base, power_exponent) = power.get_base_exp();
21477        if base.to_owned() != x_atom || !is_free_of(power_exponent, x) {
21478            return None;
21479        }
21480
21481        exponent += power_exponent.to_owned();
21482    }
21483
21484    Some((exponent.expand(), coefficient))
21485}
21486
21487fn rubi_variable_power(x: Symbol, exponent: Atom) -> Atom {
21488    if eqq!(exponent, 0) {
21489        Atom::num(1)
21490    } else if eqq!(exponent, 1) {
21491        Atom::var(x)
21492    } else {
21493        Atom::var(x).pow(exponent)
21494    }
21495}
21496
21497fn rubi_normalize_integrand(expr: &Atom, x: Symbol) -> Atom {
21498    let aux = rubi_normalize_integrand_aux(expr, x);
21499    let normalized = rubi_normalize_lead_term_signs(&aux);
21500    if normalized == rubi_normalize_lead_term_signs(expr) {
21501        expr.to_owned()
21502    } else {
21503        normalized
21504    }
21505}
21506
21507fn rubi_normalize_exponential_integrand(exponent: &Atom, x: Symbol) -> Atom {
21508    // Rubi rule bodies sometimes call NormalizeIntegrand[E^z, x]. In Mathematica,
21509    // that expression reaches NormalizeIntegrand as Power[E, z], so the helper
21510    // normalizes z first; for example x*Log[a]-x*Log[b] becomes
21511    // x*(Log[a]-Log[b]). Symbolica eagerly rewrites the expanded construction
21512    // E^(x*log(a)-x*log(b)) to a^x*b^(-x), which sends Rubi 2.3.100 back to the
21513    // same product-of-powers rule. This helper intentionally models Rubi's
21514    // Power[E, z] normalization branch before constructing the Symbolica atom.
21515    let normalized_exponent = rubi_normalize_integrand_factor_base(exponent, x);
21516    let normalized_exponent =
21517        rubi_normalize_exponential_polynomial_exponent(&normalized_exponent, x)
21518            .unwrap_or(normalized_exponent);
21519    let normalized = rubi_normalize_integrand(&normalized_exponent.exp(), x);
21520    if rubi_x_dependent_constant_base_power_count(&normalized, x) < 2 {
21521        return normalized;
21522    }
21523
21524    // Mathematica keeps NormalizeIntegrand[E^z,x] as one exponential even when
21525    // z contains logarithms of other constant bases. Symbolica eagerly expands
21526    // that form back into a product such as E^v*F^w, which immediately re-enters
21527    // the calling Rubi rule. Re-express the same E^z using one logarithmic base
21528    // so the normalized polynomial exponent remains structurally visible.
21529    rubi_first_logarithm_base(normalized_exponent.as_view(), x)
21530        .map(|base| {
21531            let exponent_in_base = rubi_simplify(&(&normalized_exponent / rubi_log(&base)));
21532            base.pow(exponent_in_base)
21533        })
21534        .unwrap_or(normalized)
21535}
21536
21537fn rubi_x_dependent_constant_base_power_count(expr: &Atom, x: Symbol) -> usize {
21538    let factors = match expr.as_view() {
21539        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
21540        _ => vec![expr.as_view()],
21541    };
21542    factors
21543        .into_iter()
21544        .filter(|factor| {
21545            matches!(
21546                factor,
21547                AtomView::Pow(power)
21548                    if is_free_of(power.get_base(), x)
21549                        && power.get_exp().contains_symbol(x)
21550            )
21551        })
21552        .count()
21553}
21554
21555fn rubi_first_logarithm_base(expr: AtomView<'_>, x: Symbol) -> Option<Atom> {
21556    match expr {
21557        AtomView::Fun(function)
21558            if function.get_symbol() == symbol!("log") && function.get_nargs() == 1 =>
21559        {
21560            let base = function.get(0).to_owned();
21561            is_free_of(base.as_view(), x).then_some(base)
21562        }
21563        AtomView::Pow(power) => rubi_first_logarithm_base(power.get_base(), x)
21564            .or_else(|| rubi_first_logarithm_base(power.get_exp(), x)),
21565        AtomView::Add(sum) => sum
21566            .into_iter()
21567            .find_map(|term| rubi_first_logarithm_base(term, x)),
21568        AtomView::Mul(product) => product
21569            .into_iter()
21570            .find_map(|factor| rubi_first_logarithm_base(factor, x)),
21571        AtomView::Fun(function) => function
21572            .into_iter()
21573            .find_map(|argument| rubi_first_logarithm_base(argument, x)),
21574        AtomView::Num(_) | AtomView::Var(_) => None,
21575    }
21576}
21577
21578fn rubi_normalize_exponential_polynomial_exponent(expr: &Atom, x: Symbol) -> Option<Atom> {
21579    let terms = collect_polynomial_terms(expr, x)?;
21580    let minimum_degree = terms.keys().next().copied()?;
21581    if minimum_degree <= 0 {
21582        return Some(polynomial_from_terms(&terms, x));
21583    }
21584
21585    let shifted_terms = terms
21586        .into_iter()
21587        .map(|(degree, coefficient)| (degree - minimum_degree, coefficient))
21588        .collect();
21589    Some(Atom::var(x).pow(minimum_degree) * polynomial_from_terms(&shifted_terms, x))
21590}
21591
21592fn rubi_normalize_integrand_aux(expr: &Atom, x: Symbol) -> Atom {
21593    match expr.as_view() {
21594        AtomView::Add(add) => add
21595            .into_iter()
21596            .map(|term| rubi_normalize_integrand_aux(&term.to_owned(), x))
21597            .fold(Atom::num(0), |sum, term| sum + term),
21598        _ => {
21599            let merged = rubi_merge_monomials(expr, x);
21600            match merged.as_view() {
21601                AtomView::Mul(mul) => mul
21602                    .into_iter()
21603                    .map(|factor| rubi_normalize_integrand_factor(&factor.to_owned(), x))
21604                    .fold(Atom::num(1), |product, factor| product * factor),
21605                _ => rubi_normalize_integrand_factor(&merged, x),
21606            }
21607        }
21608    }
21609}
21610
21611fn rubi_normalize_integrand_factor(expr: &Atom, x: Symbol) -> Atom {
21612    match expr.as_view() {
21613        AtomView::Pow(power) => {
21614            let base = power.get_base().to_owned();
21615            let exponent = power.get_exp().to_owned();
21616            if is_free_of(&exponent, x) {
21617                let normalized_base = rubi_normalize_integrand_factor_base(&base, x);
21618                if integerq!(exponent.to_owned())
21619                    && rubi_sum_q(&normalized_base)
21620                    && rubi_add_terms(&normalized_base)
21621                        .iter()
21622                        .all(|term| rubi_monomial_q(term, x))
21623                {
21624                    if let Some(minimum_exponent) =
21625                        rubi_minimum_monomial_exponent(&normalized_base, x)
21626                    {
21627                        let x_atom = Atom::var(x);
21628                        let shifted = map_sum_terms(&normalized_base, |term| {
21629                            rubi_simplify(&(term / x_atom.pow(minimum_exponent)))
21630                        });
21631                        return x_atom.pow(Atom::num(minimum_exponent) * &exponent)
21632                            * shifted.pow(exponent);
21633                    }
21634                }
21635                rubi_hold_power(&normalized_base, &exponent)
21636            } else if is_free_of(&base, x) {
21637                base.pow(rubi_normalize_integrand_factor_base(&exponent, x))
21638            } else {
21639                rubi_normalize_integrand_factor_base(expr, x)
21640            }
21641        }
21642        _ => {
21643            let normalized_base = rubi_normalize_integrand_factor_base(expr, x);
21644            if rubi_sum_q(&normalized_base)
21645                && rubi_add_terms(&normalized_base)
21646                    .iter()
21647                    .all(|term| rubi_monomial_q(term, x))
21648            {
21649                if let Some(minimum_exponent) = rubi_minimum_monomial_exponent(&normalized_base, x)
21650                {
21651                    let x_atom = Atom::var(x);
21652                    return x_atom.pow(minimum_exponent)
21653                        * map_sum_terms(&normalized_base, |term| {
21654                            term / x_atom.pow(minimum_exponent)
21655                        });
21656                }
21657            }
21658            normalized_base
21659        }
21660    }
21661}
21662
21663fn rubi_normalize_integrand_factor_base(expr: &Atom, x: Symbol) -> Atom {
21664    if let Some(factored) = rubi_factor_symbolic_power_canonicalization(expr, x) {
21665        return rubi_normalize_integrand_factor_base(&factored, x);
21666    }
21667
21668    if let Some(distributed) = rubi_distribute_monomial_over_sum(expr, x) {
21669        return rubi_normalize_integrand_factor_base(&distributed, x);
21670    }
21671
21672    if rubi_binomial_q(expr.as_view(), x) {
21673        return if rubi_binomial_match_q(expr, x) {
21674            expr.to_owned()
21675        } else {
21676            rubi_expand_to_sum(expr, x)
21677        };
21678    }
21679
21680    if rubi_trinomial_q(expr, x) {
21681        return if rubi_trinomial_match_q(expr, x) {
21682            expr.to_owned()
21683        } else {
21684            rubi_expand_to_sum(expr, x)
21685        };
21686    }
21687
21688    match expr.as_view() {
21689        AtomView::Mul(mul) => mul
21690            .into_iter()
21691            .map(|factor| rubi_normalize_integrand_factor(&factor.to_owned(), x))
21692            .fold(Atom::num(1), |product, factor| product * factor),
21693        AtomView::Add(_) if polynomial_degree(expr, x).is_some_and(|degree| degree <= 4) => {
21694            rubi_expand_to_sum(expr, x)
21695        }
21696        AtomView::Add(_) => {
21697            let simplified = rubi_together_simplify(expr);
21698            if rubi_sum_q(&simplified)
21699                || rubi_monomial_times_sum_q(&simplified, x)
21700                || rubi_leaf_count(simplified.as_view()) > rubi_leaf_count(expr.as_view()) + 2
21701            {
21702                rubi_unify_sum(expr, x)
21703            } else {
21704                rubi_normalize_integrand_factor_base(&simplified, x)
21705            }
21706        }
21707        AtomView::Fun(function) => {
21708            let args = function
21709                .into_iter()
21710                .map(|argument| rubi_normalize_integrand_factor(&argument.to_owned(), x))
21711                .collect::<Vec<_>>();
21712            function.get_symbol().call_args(args)
21713        }
21714        _ => expr.to_owned(),
21715    }
21716}
21717
21718fn rubi_factor_symbolic_power_canonicalization(expr: &Atom, x: Symbol) -> Option<Atom> {
21719    let (common, sum) = rubi_factor_common_symbolic_terms_parts(expr, x)?;
21720    let has_symbolic_power = rubi_product_factors(&common).iter().any(|factor| {
21721        matches!(
21722            factor.as_view(),
21723            AtomView::Pow(power)
21724                if !matches!(power.get_base(), AtomView::Var(variable) if variable.get_symbol() == x)
21725                    && integer_i64_view(power.get_exp()).is_none()
21726        )
21727    });
21728    has_symbolic_power.then(|| common * sum)
21729}
21730
21731fn rubi_distribute_monomial_over_sum(expr: &Atom, x: Symbol) -> Option<Atom> {
21732    let AtomView::Mul(mul) = expr.as_view() else {
21733        return None;
21734    };
21735
21736    let factors = mul
21737        .into_iter()
21738        .map(|factor| factor.to_owned())
21739        .collect::<Vec<_>>();
21740    let (monomial_index, monomial_exponent) =
21741        factors.iter().enumerate().find_map(|(index, factor)| {
21742            let AtomView::Pow(power) = factor.as_view() else {
21743                return None;
21744            };
21745            let base = power.get_base();
21746            let exponent = power.get_exp().to_owned();
21747            matches!(base, AtomView::Var(variable) if variable.get_symbol() == x)
21748                .then_some((index, exponent))
21749                .filter(|(_, exponent)| is_free_of(exponent, x))
21750        })?;
21751    let (sum_index, _) = factors
21752        .iter()
21753        .enumerate()
21754        .find(|(index, factor)| *index != monomial_index && rubi_sum_q(factor))?;
21755
21756    let mut rest = Atom::num(1);
21757    for (index, factor) in factors.iter().enumerate() {
21758        if index != monomial_index && index != sum_index {
21759            rest *= factor;
21760        }
21761    }
21762
21763    let x_power = Atom::var(x).pow(monomial_exponent);
21764    let distributed = map_sum_terms(&factors[sum_index], |term| &x_power * term);
21765    Some(rest * distributed)
21766}
21767
21768fn rubi_monomial_q(expr: &Atom, x: Symbol) -> bool {
21769    polynomial_term(expr.as_view(), x).is_some()
21770}
21771
21772fn rubi_monomial_times_sum_q(expr: &Atom, x: Symbol) -> bool {
21773    match expr.as_view() {
21774        AtomView::Mul(_) => {
21775            let factors = rubi_product_factors(expr);
21776            factors.iter().enumerate().any(|(index, factor)| {
21777                rubi_x_power_factor_q(factor, x)
21778                    && rubi_sum_q(
21779                        &factors
21780                            .iter()
21781                            .enumerate()
21782                            .filter(|(other_index, _)| *other_index != index)
21783                            .fold(Atom::num(1), |product, (_, factor)| product * factor),
21784                    )
21785            })
21786        }
21787        _ => false,
21788    }
21789}
21790
21791fn rubi_x_power_factor_q(expr: &Atom, x: Symbol) -> bool {
21792    match expr.as_view() {
21793        AtomView::Var(variable) => variable.get_symbol() == x,
21794        AtomView::Pow(power) => {
21795            matches!(power.get_base(), AtomView::Var(variable) if variable.get_symbol() == x)
21796                && is_free_of(&power.get_exp().to_owned(), x)
21797        }
21798        _ => false,
21799    }
21800}
21801
21802fn rubi_normalize_lead_term_signs(expr: &Atom) -> Atom {
21803    let (sign, factor) = rubi_sign_of_factor(expr);
21804    if sign == 1 {
21805        factor
21806    } else {
21807        rubi_absorb_minus_sign(&factor)
21808    }
21809}
21810
21811fn rubi_factor(expr: &Atom) -> Atom {
21812    expr.factor()
21813}
21814
21815fn rubi_try_factor(expr: AtomView<'_>) -> Option<Atom> {
21816    static PANIC_HOOK_LOCK: Mutex<()> = Mutex::new(());
21817    const GENERIC_FACTOR_LEAF_LIMIT: usize = 128;
21818
21819    if rubi_leaf_count(expr) > GENERIC_FACTOR_LEAF_LIMIT {
21820        return None;
21821    }
21822
21823    let _guard = PANIC_HOOK_LOCK
21824        .lock()
21825        .unwrap_or_else(|poison| poison.into_inner());
21826    let hook = std::panic::take_hook();
21827    std::panic::set_hook(Box::new(|_| {}));
21828    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| expr.factor()));
21829    std::panic::set_hook(hook);
21830    result.ok()
21831}
21832
21833fn rubi_numeric_and_nonnumeric_factors(expr: &Atom) -> (Atom, Atom) {
21834    if matches!(expr.as_view(), AtomView::Num(_)) {
21835        return (expr.to_owned(), Atom::num(1));
21836    }
21837
21838    let AtomView::Mul(mul) = expr.as_view() else {
21839        return (Atom::num(1), expr.to_owned());
21840    };
21841
21842    let mut numeric = Atom::num(1);
21843    let mut nonnumeric = Atom::num(1);
21844    for factor in mul {
21845        if matches!(factor, AtomView::Num(_)) {
21846            numeric *= factor.to_owned();
21847        } else {
21848            nonnumeric *= factor.to_owned();
21849        }
21850    }
21851    (numeric, nonnumeric)
21852}
21853
21854fn rubi_simp_help(expr: &Atom, x: Symbol) -> Atom {
21855    if atom_q(expr.as_view()) || starts_with_opaque_rubi_function(expr.as_view()) {
21856        return expr.to_owned();
21857    }
21858
21859    if is_free_of(expr, x) {
21860        return rubi_smart_simplify(expr);
21861    }
21862
21863    match expr.as_view() {
21864        AtomView::Mul(mul) => {
21865            let x_atom = Atom::var(x);
21866            let mut free_factors = Atom::num(1);
21867            let mut nonfree_factors = Atom::num(1);
21868            for factor in mul {
21869                if is_free_of(factor, x) {
21870                    free_factors *= factor.to_owned();
21871                } else {
21872                    nonfree_factors *= rubi_simp_help(&factor.to_owned(), x);
21873                }
21874            }
21875
21876            let (numeric_factor, nonnumeric_factors) =
21877                rubi_numeric_and_nonnumeric_factors(&free_factors);
21878            let free_factors = numeric_factor
21879                * rubi_smart_simplify(&(nonnumeric_factors * x_atom.pow(2)))
21880                / Atom::var(x).pow(2);
21881            free_factors * rubi_factor_numeric_gcd(&nonfree_factors)
21882        }
21883        AtomView::Add(add) => {
21884            if let Some(degree) = polynomial_degree(expr, x) {
21885                if degree <= 0 {
21886                    if let Some(coefficient) = polynomial_coefficient(expr, x, 0) {
21887                        return rubi_simp_help(&coefficient, x);
21888                    }
21889                }
21890                if degree == 1 {
21891                    if let (Some(constant), Some(coefficient)) = (
21892                        polynomial_coefficient(expr, x, 0),
21893                        polynomial_coefficient(expr, x, 1),
21894                    ) {
21895                        if constant.is_zero() {
21896                            return rubi_simp_help(&coefficient, x) * Atom::var(x);
21897                        }
21898                    }
21899                }
21900            }
21901
21902            let mut free_terms = Atom::num(0);
21903            let mut nonfree_terms = Vec::new();
21904            for term in add {
21905                if is_free_of(term, x) {
21906                    free_terms += term.to_owned();
21907                } else {
21908                    nonfree_terms.push(term.to_owned());
21909                }
21910            }
21911
21912            nonfree_terms
21913                .into_iter()
21914                .map(|term| rubi_simp_help(&term, x))
21915                .fold(rubi_smart_simplify(&free_terms), |sum, term| sum + term)
21916        }
21917        AtomView::Pow(power) => {
21918            let (base, exponent) = power.get_base_exp();
21919            rubi_simp_help(&base.to_owned(), x).pow(rubi_simp_help(&exponent.to_owned(), x))
21920        }
21921        AtomView::Fun(fun) => fun.get_symbol().call_args(
21922            fun.into_iter()
21923                .map(|arg| rubi_simp_help(&arg.to_owned(), x)),
21924        ),
21925        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
21926    }
21927}
21928
21929fn rubi_smart_simplify(expr: &Atom) -> Atom {
21930    let simplified = rubi_mathematica_simplify(expr);
21931    let factor_complexity = rubi_leaf_count(simplified.as_view())
21932        .saturating_mul(simplified.get_all_symbols(false).len());
21933    // Rubi wraps SmartSimplify in TimeConstrained[..., $TimeLimit, expr], where
21934    // $TimeLimit defaults to five seconds. Symbolica's factor() cannot be
21935    // interrupted, so use its bounded square-free pass before taking Rubi's
21936    // documented timeout fallback.
21937    if factor_complexity > 800 {
21938        let square_free = rubi_square_free_factorization(&simplified);
21939        let bounded = square_free
21940            .filter(|candidate| {
21941                rubi_leaf_count(candidate.as_view()) < rubi_leaf_count(simplified.as_view())
21942            })
21943            .unwrap_or(simplified);
21944        if rubi_leaf_count(bounded.as_view()) < rubi_leaf_count(expr.as_view()) {
21945            return bounded;
21946        }
21947        return expr.to_owned();
21948    }
21949    let factored = simplified.factor();
21950    if rubi_leaf_count(factored.as_view()) < rubi_leaf_count(simplified.as_view()) {
21951        factored
21952    } else {
21953        simplified
21954    }
21955}
21956
21957fn rubi_square_free_factorization(expr: &Atom) -> Option<Atom> {
21958    fn factor_polynomial(expr: &Atom) -> Option<Atom> {
21959        let polynomial: MultivariatePolynomial<_, u16> = expr.try_to_polynomial(&Q, None).ok()?;
21960        Some(
21961            polynomial
21962                .square_free_factorization()
21963                .into_iter()
21964                .fold(Atom::num(1), |product, (factor, exponent)| {
21965                    product * factor.to_expression().pow(exponent as i64)
21966                }),
21967        )
21968    }
21969
21970    let (numerator, denominator) = rational_numerator_denominator(expr)?;
21971    let numerator = factor_polynomial(&numerator)?;
21972    let denominator = factor_polynomial(&denominator)?;
21973    Some(numerator / denominator)
21974}
21975
21976fn rubi_normalize_sum_factors(expr: AtomView<'_>) -> Atom {
21977    match expr {
21978        AtomView::Add(add) => add
21979            .into_iter()
21980            .map(rubi_normalize_sum_factors)
21981            .fold(Atom::num(0), |sum, term| sum + term),
21982        AtomView::Mul(mul) => {
21983            let normalized_product = mul
21984                .into_iter()
21985                .map(rubi_normalize_sum_factors)
21986                .fold(Atom::num(1), |product, factor| product * factor);
21987            let (sign, factor) = rubi_sign_of_factor(&normalized_product);
21988            if sign < 0 {
21989                rubi_absorb_minus_sign(&factor)
21990            } else {
21991                factor
21992            }
21993        }
21994        AtomView::Pow(power) => {
21995            let (base, exponent) = power.get_base_exp();
21996            let normalized_base = rubi_normalize_sum_factors(base);
21997            let normalized_exponent = rubi_normalize_sum_factors(exponent);
21998            normalized_base.pow(normalized_exponent)
21999        }
22000        AtomView::Fun(fun) => fun
22001            .get_symbol()
22002            .call_args(fun.into_iter().map(rubi_normalize_sum_factors)),
22003        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
22004    }
22005}
22006
22007fn rubi_sign_of_factor(expr: &Atom) -> (i64, Atom) {
22008    if rational_q(expr) && is_number_less_than(expr, 0)
22009        || rubi_sum_q(expr) && rubi_first_term_neg_q(expr)
22010    {
22011        return (-1, (-expr).expand());
22012    }
22013
22014    if let Some((base, exponent)) = rubi_power_base_exponent(expr)
22015        && rubi_sum_q(&base)
22016        && rubi_first_term_neg_q(&base)
22017        && let Some(exponent_integer) = integer_i64(&exponent)
22018    {
22019        let sign = if exponent_integer % 2 == 0 { 1 } else { -1 };
22020        return (sign, (-base).expand().pow(exponent));
22021    }
22022
22023    if let AtomView::Mul(mul) = expr.as_view() {
22024        let mut sign = 1;
22025        let mut factor = Atom::num(1);
22026        for item in mul {
22027            let (item_sign, item_factor) = rubi_sign_of_factor(&item.to_owned());
22028            sign *= item_sign;
22029            factor *= item_factor;
22030        }
22031        return (sign, factor);
22032    }
22033
22034    (1, expr.to_owned())
22035}
22036
22037fn rubi_absorb_minus_sign(expr: &Atom) -> Atom {
22038    if rubi_sum_q(expr) {
22039        return (-expr).expand();
22040    }
22041
22042    let factors = rubi_product_factors(expr);
22043    if factors.len() > 1 {
22044        for (index, factor) in factors.iter().enumerate() {
22045            if rubi_sum_q(factor) {
22046                return factors
22047                    .iter()
22048                    .enumerate()
22049                    .map(|(factor_index, item)| {
22050                        if factor_index == index {
22051                            (-item).expand()
22052                        } else {
22053                            item.to_owned()
22054                        }
22055                    })
22056                    .fold(Atom::num(1), |product, item| product * item);
22057            }
22058        }
22059
22060        for (index, factor) in factors.iter().enumerate() {
22061            if let Some((base, exponent)) = rubi_power_base_exponent(factor)
22062                && rubi_sum_q(&base)
22063                && integer_i64(&exponent).is_some_and(|integer| integer % 2 != 0)
22064            {
22065                return factors
22066                    .iter()
22067                    .enumerate()
22068                    .map(|(factor_index, item)| {
22069                        if factor_index == index {
22070                            (-base.to_owned()).expand().pow(exponent.to_owned())
22071                        } else {
22072                            item.to_owned()
22073                        }
22074                    })
22075                    .fold(Atom::num(1), |product, item| product * item);
22076            }
22077        }
22078    }
22079
22080    if let Some((base, exponent)) = rubi_power_base_exponent(expr)
22081        && rubi_sum_q(&base)
22082        && integer_i64(&exponent).is_some_and(|integer| integer % 2 != 0)
22083    {
22084        return (-base).expand().pow(exponent);
22085    }
22086
22087    -expr
22088}
22089
22090fn rubi_factor_numeric_gcd(expr: &Atom) -> Atom {
22091    // IntegrationUtilityFunctions.m defines this as structural numeric-content
22092    // extraction, not general polynomial factorization.
22093    match expr.as_view() {
22094        AtomView::Pow(power) => {
22095            let (base, exponent) = power.get_base_exp();
22096            let exponent = exponent.to_owned();
22097            if rubi_exact_rational(exponent.as_view()).is_some() {
22098                rubi_factor_numeric_gcd(&base.to_owned()).pow(exponent)
22099            } else {
22100                expr.to_owned()
22101            }
22102        }
22103        AtomView::Mul(product) => product
22104            .into_iter()
22105            .map(|factor| rubi_factor_numeric_gcd(&factor.to_owned()))
22106            .fold(Atom::num(1), |result, factor| result * factor),
22107        AtomView::Add(sum) => {
22108            let terms = sum
22109                .into_iter()
22110                .map(|term| term.to_owned())
22111                .collect::<Vec<_>>();
22112            let Some(gcd) = terms
22113                .iter()
22114                .map(|term| rubi_numeric_factor_value(term.as_view()))
22115                .reduce(|left, right| left.gcd(&right))
22116            else {
22117                return expr.to_owned();
22118            };
22119            if gcd.is_zero() || gcd.is_one() {
22120                return expr.to_owned();
22121            }
22122
22123            let gcd_atom = Atom::num(gcd);
22124            gcd_atom.to_owned()
22125                * terms
22126                    .into_iter()
22127                    .map(|term| term / &gcd_atom)
22128                    .fold(Atom::num(0), |result, term| result + term)
22129        }
22130        AtomView::Num(_) | AtomView::Var(_) | AtomView::Fun(_) => expr.to_owned(),
22131    }
22132}
22133
22134fn rubi_numeric_factor_value(expr: AtomView<'_>) -> Rational {
22135    match expr {
22136        AtomView::Num(number) => match number.get_coeff_view() {
22137            CoefficientView::Natural(real_numerator, real_denominator, 0, 1) => {
22138                Rational::new(real_numerator, real_denominator)
22139            }
22140            CoefficientView::Natural(0, 1, imaginary_numerator, imaginary_denominator) => {
22141                Rational::new(imaginary_numerator, imaginary_denominator)
22142            }
22143            CoefficientView::Large(real, imaginary) if imaginary.is_zero() => real.to_rat(),
22144            CoefficientView::Large(real, imaginary) if real.is_zero() => imaginary.to_rat(),
22145            _ => Rational::one(),
22146        },
22147        AtomView::Pow(power) => {
22148            let (base, exponent) = power.get_base_exp();
22149            let Some(base) = rubi_exact_rational(base) else {
22150                return Rational::one();
22151            };
22152            let Some(exponent) = rubi_exact_rational(exponent) else {
22153                return Rational::one();
22154            };
22155            if exponent.is_integer() {
22156                return Rational::one();
22157            }
22158
22159            let denominator = if exponent.is_negative() {
22160                base.numerator_ref().abs()
22161            } else {
22162                base.denominator()
22163            };
22164            Rational::new(Integer::from(1), denominator)
22165        }
22166        AtomView::Mul(product) => product
22167            .into_iter()
22168            .map(rubi_numeric_factor_value)
22169            .fold(Rational::one(), |result, factor| result * factor),
22170        AtomView::Add(sum) => {
22171            let factors = sum
22172                .into_iter()
22173                .map(rubi_numeric_factor_value)
22174                .collect::<Vec<_>>();
22175            let all_negative = factors.iter().all(Rational::is_negative);
22176            let gcd = factors
22177                .into_iter()
22178                .reduce(|left, right| left.gcd(&right))
22179                .unwrap_or_else(Rational::one);
22180            if all_negative { -gcd } else { gcd }
22181        }
22182        AtomView::Var(_) | AtomView::Fun(_) => Rational::one(),
22183    }
22184}
22185
22186fn rubi_exact_rational(expr: AtomView<'_>) -> Option<Rational> {
22187    let AtomView::Num(number) = expr else {
22188        return None;
22189    };
22190    match number.get_coeff_view() {
22191        CoefficientView::Natural(numerator, denominator, 0, 1) => {
22192            Some(Rational::new(numerator, denominator))
22193        }
22194        CoefficientView::Large(real, imaginary) if imaginary.is_zero() => Some(real.to_rat()),
22195        _ => None,
22196    }
22197}
22198
22199fn linear_coefficients<T: AtomCore>(expr: T, x: Symbol) -> Option<(Atom, Atom)> {
22200    let expr = expr.as_atom_view();
22201    if rubi_contains_symbolic_order_derivative(expr, x) {
22202        return None;
22203    }
22204    let variable = Atom::var(x);
22205    let slope = expr.derivative(x).expand();
22206    if !is_free_of(&slope, x) {
22207        return None;
22208    }
22209
22210    let linear_term = &slope * variable;
22211    let constant = (expr - linear_term.as_view()).expand();
22212    if !is_free_of(&constant, x) {
22213        return None;
22214    }
22215
22216    Some((constant, slope))
22217}
22218
22219fn rubi_contains_symbolic_order_derivative(expr: AtomView<'_>, x: Symbol) -> bool {
22220    match expr {
22221        AtomView::Fun(function) => {
22222            let arguments = function.into_iter().collect::<Vec<_>>();
22223            if function.get_symbol() == Symbol::DERIVATIVE
22224                && arguments.len() == 3
22225                && integer_i64_view(arguments[0]).is_none()
22226                && !is_free_of(arguments[2], x)
22227            {
22228                return true;
22229            }
22230            arguments
22231                .into_iter()
22232                .any(|argument| rubi_contains_symbolic_order_derivative(argument, x))
22233        }
22234        AtomView::Add(add) => add
22235            .into_iter()
22236            .any(|term| rubi_contains_symbolic_order_derivative(term, x)),
22237        AtomView::Mul(mul) => mul
22238            .into_iter()
22239            .any(|factor| rubi_contains_symbolic_order_derivative(factor, x)),
22240        AtomView::Pow(power) => {
22241            rubi_contains_symbolic_order_derivative(power.get_base(), x)
22242                || rubi_contains_symbolic_order_derivative(power.get_exp(), x)
22243        }
22244        AtomView::Num(_) | AtomView::Var(_) => false,
22245    }
22246}
22247
22248fn polygamma_primitive(order: Atom, argument: Atom, slope: Atom, x: Symbol) -> Option<Atom> {
22249    if !is_free_of(&order, x) {
22250        return None;
22251    }
22252
22253    Some(argument.polygamma(order - Atom::num(1)) / slope)
22254}
22255
22256fn linear_pair_q(u: AtomView<'_>, v: AtomView<'_>, x: Symbol) -> bool {
22257    if !u.contains_symbol(x) || !v.contains_symbol(x) {
22258        return false;
22259    }
22260
22261    let variable = Atom::var(x);
22262    let Some((u0, u1)) = linear_coefficients(u, x) else {
22263        return false;
22264    };
22265    if u1.is_zero() {
22266        return false;
22267    }
22268
22269    let Some((v0, v1)) = linear_coefficients(v, x) else {
22270        return false;
22271    };
22272    if v1.is_zero() {
22273        return false;
22274    }
22275
22276    !(u - variable.as_view()).expand().is_zero() && eqq!(u0 * v1 - u1 * v0, 0)
22277}
22278
22279fn rubi_linear_pair_q<U: AtomCore, V: AtomCore>(u: U, v: V, x: Symbol) -> bool {
22280    linear_pair_q(u.as_atom_view(), v.as_atom_view(), x)
22281}
22282
22283fn rubi_polynomial_derivative_pair_q(polynomial: &Atom, derivative: &Atom, x: Symbol) -> bool {
22284    if !rubi_poly_q(polynomial, x) || !rubi_poly_q(derivative, x) {
22285        return false;
22286    }
22287    let Some(q) = rubi_expon(polynomial.as_view(), x) else {
22288        return false;
22289    };
22290    let Some(r) = rubi_expon(derivative.as_view(), x) else {
22291        return false;
22292    };
22293    if r != q - 1 {
22294        return false;
22295    }
22296    let Some(q_coefficient) = rubi_coeff(polynomial, x, q) else {
22297        return false;
22298    };
22299    let Some(r_coefficient) = rubi_coeff(derivative, x, r) else {
22300        return false;
22301    };
22302    eqq!(
22303        (&r_coefficient * rubi_d(polynomial, x)).expand(),
22304        (Atom::num(q) * q_coefficient * derivative).expand()
22305    )
22306}
22307
22308fn rubi_has_polynomial_derivative_factor_pair(expr: AtomView<'_>, x: Symbol) -> bool {
22309    let AtomView::Mul(product) = expr else {
22310        return true;
22311    };
22312    let factors = product.into_iter().collect::<Vec<_>>();
22313    if factors.len() < 2 {
22314        return true;
22315    }
22316
22317    fn contains_derivative_pair(candidate: AtomView<'_>, derivative: &Atom, x: Symbol) -> bool {
22318        if rubi_polynomial_derivative_pair_q(&candidate.to_owned(), derivative, x) {
22319            return true;
22320        }
22321        rubi_child_views(candidate).any(|child| contains_derivative_pair(child, derivative, x))
22322    }
22323
22324    factors.iter().enumerate().any(|(main_index, main)| {
22325        let derivative = factors
22326            .iter()
22327            .enumerate()
22328            .filter(|(index, _)| *index != main_index)
22329            .map(|(_, factor)| *factor)
22330            .fold(Atom::num(1), |product, factor| product * factor);
22331        rubi_poly_q(&derivative, x) && contains_derivative_pair(*main, &derivative, x)
22332    })
22333}
22334
22335fn rubi_has_proportional_affine_factor_pair(expr: AtomView<'_>, x: Symbol) -> bool {
22336    fn affine_coefficients(factor: AtomView<'_>, x: Symbol) -> Option<(Atom, Atom)> {
22337        let base = match factor {
22338            AtomView::Pow(power) if is_free_of(power.get_exp(), x) => power.get_base().to_owned(),
22339            AtomView::Pow(_) => return None,
22340            _ => factor.to_owned(),
22341        };
22342        linear_coefficients(base.as_view(), x).filter(|(_constant, slope)| !slope.is_zero())
22343    }
22344
22345    let factors = match expr {
22346        AtomView::Mul(product) => product
22347            .into_iter()
22348            .filter_map(|factor| affine_coefficients(factor, x))
22349            .collect::<Vec<_>>(),
22350        _ => affine_coefficients(expr, x).into_iter().collect(),
22351    };
22352
22353    factors.iter().enumerate().any(|(index, (a, b))| {
22354        factors[index + 1..]
22355            .iter()
22356            .any(|(c, d)| rubi_algebraic_zero_q(&(b * c - a * d)))
22357    })
22358}
22359
22360fn rubi_has_proportional_common_expression_factor_pair(expr: AtomView<'_>, x: Symbol) -> bool {
22361    fn parts(base: AtomView<'_>, x: Symbol) -> Result<Option<(Atom, Atom, Atom)>, ()> {
22362        let AtomView::Add(add) = base else {
22363            return Ok(None);
22364        };
22365        let terms = add
22366            .into_iter()
22367            .map(|term| term.to_owned())
22368            .collect::<Vec<_>>();
22369        let dependent = terms
22370            .iter()
22371            .enumerate()
22372            .filter_map(|(index, term)| term.contains_symbol(x).then_some(index))
22373            .collect::<Vec<_>>();
22374        if dependent.len() != 1 {
22375            return if dependent.is_empty() {
22376                Ok(None)
22377            } else {
22378                Err(())
22379            };
22380        }
22381
22382        let dependent_index = dependent[0];
22383        let a = rubi_sum_except(&terms, dependent_index);
22384        let term = &terms[dependent_index];
22385        let factors = rubi_product_factors(term);
22386        let (free_factors, dependent_factors): (Vec<_>, Vec<_>) = factors
22387            .into_iter()
22388            .partition(|factor| !factor.contains_symbol(x));
22389        if dependent_factors.is_empty() {
22390            return Err(());
22391        }
22392
22393        Ok(Some((
22394            a,
22395            product_atoms(&free_factors),
22396            product_atoms(&dependent_factors),
22397        )))
22398    }
22399
22400    let factors = match expr {
22401        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
22402        _ => vec![expr],
22403    };
22404    let mut candidates = Vec::new();
22405    for factor in factors {
22406        let base = match factor {
22407            AtomView::Pow(power) if is_free_of(power.get_exp(), x) => power.get_base(),
22408            AtomView::Pow(_) => continue,
22409            _ => factor,
22410        };
22411        match parts(base, x) {
22412            Ok(Some(candidate)) => candidates.push(candidate),
22413            Ok(None) => {}
22414            // A flattened multi-term dependent part can still bind to v__.
22415            Err(()) => return true,
22416        }
22417    }
22418
22419    candidates.iter().enumerate().any(|(index, (a, b, v))| {
22420        candidates[index + 1..]
22421            .iter()
22422            .any(|(c, d, w)| v == w && rubi_algebraic_zero_q(&(b * c - a * d)))
22423    })
22424}
22425
22426fn rubi_explicit_pattern_x_factor_bound(
22427    pattern: &Atom,
22428    required: &[Symbol],
22429) -> Option<ExplicitPatternXFactorBound> {
22430    let AtomView::Mul(product) = pattern.as_view() else {
22431        return None;
22432    };
22433
22434    let x = rubi_symbols().x_;
22435    let (x_factors, non_x_factors): (Vec<_>, Vec<_>) = product
22436        .into_iter()
22437        .partition(|factor| factor.contains_symbol(x));
22438    if x_factors.is_empty() {
22439        return None;
22440    }
22441
22442    let affine_base_factors = x_factors
22443        .iter()
22444        .filter(|factor| rubi_affine_base_factor_q(**factor, x))
22445        .collect::<Vec<_>>();
22446    let affine_base_count = affine_base_factors.len();
22447    let unpowered_affine_factor_count = affine_base_factors
22448        .iter()
22449        .filter(|factor| !matches!(**factor, AtomView::Pow(_)))
22450        .count();
22451    let polynomial_base_count = x_factors
22452        .iter()
22453        .filter(|factor| rubi_explicit_polynomial_base_q(**factor, x))
22454        .count();
22455    let x_factor_symbols = required
22456        .iter()
22457        .copied()
22458        .filter(|symbol| {
22459            *symbol != x
22460                && x_factors.iter().any(|factor| {
22461                    let base = match *factor {
22462                        AtomView::Pow(power) => power.get_base(),
22463                        base => base,
22464                    };
22465                    base.contains_symbol(*symbol)
22466                })
22467        })
22468        .collect();
22469    let non_x_factor_symbols = required
22470        .iter()
22471        .copied()
22472        .filter(|symbol| {
22473            non_x_factors
22474                .iter()
22475                .any(|factor| factor.contains_symbol(*symbol))
22476        })
22477        .collect();
22478    Some(ExplicitPatternXFactorBound {
22479        factor_count: x_factors.len(),
22480        affine_base_count,
22481        unpowered_affine_factor_count,
22482        polynomial_base_count,
22483        x_factor_symbols,
22484        non_x_factor_symbols,
22485    })
22486}
22487
22488impl RubiCandidateBounds {
22489    fn new(expr: AtomView<'_>, x: Symbol) -> Self {
22490        let affine_power_bounds = rubi_affine_power_bounds(expr, x);
22491        Self {
22492            function_heads: rubi_function_heads(expr),
22493            top_level_is_sum: matches!(expr, AtomView::Add(_)),
22494            top_level_term_count: match expr {
22495                AtomView::Add(sum) => sum.into_iter().count(),
22496                _ => 1,
22497            },
22498            top_level_factor_count: match expr {
22499                AtomView::Mul(product) => product.into_iter().count(),
22500                _ => 1,
22501            },
22502            top_level_x_factor_count: rubi_top_level_x_factor_count(expr, x),
22503            top_level_affine_base_factor_count: rubi_top_level_affine_base_factor_count(expr, x),
22504            top_level_unpowered_affine_factor_count: rubi_top_level_unpowered_affine_factor_count(
22505                expr, x,
22506            ),
22507            top_level_polynomial_base_count: rubi_top_level_polynomial_base_count(expr, x),
22508            has_even_quadratic_binomial_base: rubi_has_even_quadratic_binomial_base(expr, x),
22509            has_perfect_square_quadratic_base: rubi_has_perfect_square_quadratic_base(expr, x),
22510            has_half_integer_affine_power: affine_power_bounds.has_half_integer,
22511            has_positive_integer_affine_power: affine_power_bounds.has_positive_integer,
22512            has_rational_noninteger_affine_power_below_negative_one: affine_power_bounds
22513                .has_rational_noninteger_below_negative_one,
22514            has_negative_scaled_affine_and_distinct_noninteger_affine: affine_power_bounds
22515                .has_negative_scaled_and_distinct_noninteger,
22516            has_noninteger_affine_exponent_with_positive_difference: affine_power_bounds
22517                .has_noninteger_with_positive_difference,
22518            has_x_dependent_exponent: rubi_has_x_dependent_exponent(expr, x),
22519            noninteger_affine_power_count: affine_power_bounds.noninteger_count,
22520            has_negated_binomial_exponent_pair: rubi_has_negated_binomial_exponent_pair(expr, x),
22521            max_common_binomial_exponent_factor_count:
22522                rubi_max_common_binomial_exponent_factor_count(expr, x),
22523            max_common_positive_integer_binomial_factor_count:
22524                rubi_max_common_positive_integer_binomial_factor_count(expr, x),
22525            max_common_polynomial_base_degree_count: rubi_max_common_polynomial_base_degree_count(
22526                expr, x,
22527            ),
22528            top_level_noninteger_power_factor_count: rubi_top_level_noninteger_power_factor_count(
22529                expr,
22530            ),
22531            has_explicit_variable_power_factor: rubi_has_explicit_variable_power_factor(expr, x),
22532        }
22533    }
22534}
22535
22536fn rubi_top_level_noninteger_power_factor_count(expr: AtomView<'_>) -> usize {
22537    let factors = match expr {
22538        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
22539        _ => vec![expr],
22540    };
22541    factors
22542        .into_iter()
22543        .filter(|factor| {
22544            matches!(factor, AtomView::Pow(power) if !integerq!(power.get_exp().to_owned()))
22545        })
22546        .count()
22547}
22548
22549fn rubi_literal_function_heads(expr: &Atom, wildcards: &[Symbol]) -> Vec<Symbol> {
22550    rubi_function_heads(expr.as_view())
22551        .into_iter()
22552        .filter(|head| !wildcards.contains(head))
22553        .collect()
22554}
22555
22556fn rubi_required_explicit_power_exponents(
22557    pattern: &Atom,
22558    required: &[Symbol],
22559    optional: &[Symbol],
22560) -> Vec<Symbol> {
22561    fn visit(
22562        expr: AtomView<'_>,
22563        required: &[Symbol],
22564        optional: &[Symbol],
22565        exponents: &mut Vec<Symbol>,
22566    ) {
22567        match expr {
22568            AtomView::Pow(power) => {
22569                if power.get_base() == InlineVar::new(rubi_symbols().x_).as_view()
22570                    && let AtomView::Var(variable) = power.get_exp()
22571                {
22572                    let symbol = variable.get_symbol();
22573                    if required.contains(&symbol)
22574                        && !optional.contains(&symbol)
22575                        && !exponents.contains(&symbol)
22576                    {
22577                        exponents.push(symbol);
22578                    }
22579                }
22580                visit(power.get_base(), required, optional, exponents);
22581                visit(power.get_exp(), required, optional, exponents);
22582            }
22583            AtomView::Add(sum) => {
22584                for term in sum {
22585                    visit(term, required, optional, exponents);
22586                }
22587            }
22588            AtomView::Mul(product) => {
22589                for factor in product {
22590                    visit(factor, required, optional, exponents);
22591                }
22592            }
22593            AtomView::Fun(function) => {
22594                for argument in function {
22595                    visit(argument, required, optional, exponents);
22596                }
22597            }
22598            AtomView::Num(_) | AtomView::Var(_) => {}
22599        }
22600    }
22601
22602    let mut exponents = Vec::new();
22603    visit(pattern.as_view(), required, optional, &mut exponents);
22604    exponents
22605}
22606
22607fn rubi_pattern_can_match_top_level_sum(pattern: &Atom, optional: &[Symbol]) -> bool {
22608    match pattern.as_view() {
22609        AtomView::Add(_) | AtomView::Var(_) => true,
22610        AtomView::Mul(product) => {
22611            let factors = product
22612                .into_iter()
22613                .map(|factor| factor.to_owned())
22614                .collect::<Vec<_>>();
22615            let required_factors = factors
22616                .iter()
22617                .filter(|factor| {
22618                    !matches!(
22619                        factor.as_view(),
22620                        AtomView::Var(variable) if optional.contains(&variable.get_symbol())
22621                    )
22622                })
22623                .collect::<Vec<_>>();
22624
22625            match required_factors.as_slice() {
22626                [] => factors.iter().any(|factor| {
22627                    matches!(
22628                        factor.as_view(),
22629                        AtomView::Var(variable) if optional.contains(&variable.get_symbol())
22630                    )
22631                }),
22632                [factor] => rubi_pattern_can_match_top_level_sum(factor, optional),
22633                _ => false,
22634            }
22635        }
22636        AtomView::Pow(power) => {
22637            matches!(
22638                power.get_exp(),
22639                AtomView::Var(variable) if optional.contains(&variable.get_symbol())
22640            ) && rubi_pattern_can_match_top_level_sum(&power.get_base().to_owned(), optional)
22641        }
22642        AtomView::Num(_) | AtomView::Fun(_) => false,
22643    }
22644}
22645
22646fn rubi_pattern_max_top_level_term_count(pattern: &Atom, optional: &[Symbol]) -> Option<usize> {
22647    match pattern.as_view() {
22648        AtomView::Add(sum) => {
22649            let terms = sum.into_iter().collect::<Vec<_>>();
22650            if terms.iter().any(|term| {
22651                matches!(
22652                    term,
22653                    AtomView::Var(variable)
22654                        if variable.get_wildcard_level() > 1
22655                )
22656            }) {
22657                None
22658            } else {
22659                Some(terms.len())
22660            }
22661        }
22662        AtomView::Mul(product) => {
22663            let factors = product
22664                .into_iter()
22665                .map(|factor| factor.to_owned())
22666                .collect::<Vec<_>>();
22667            let required_factors = factors
22668                .iter()
22669                .filter(|factor| {
22670                    !matches!(
22671                        factor.as_view(),
22672                        AtomView::Var(variable) if optional.contains(&variable.get_symbol())
22673                    )
22674                })
22675                .collect::<Vec<_>>();
22676            match required_factors.as_slice() {
22677                [factor] => rubi_pattern_max_top_level_term_count(factor, optional),
22678                _ => None,
22679            }
22680        }
22681        AtomView::Pow(power)
22682            if matches!(
22683                power.get_exp(),
22684                AtomView::Var(variable) if optional.contains(&variable.get_symbol())
22685            ) =>
22686        {
22687            rubi_pattern_max_top_level_term_count(&power.get_base().to_owned(), optional)
22688        }
22689        AtomView::Num(_) | AtomView::Var(_) | AtomView::Pow(_) | AtomView::Fun(_) => None,
22690    }
22691}
22692
22693fn rubi_pattern_max_top_level_factor_count(pattern: &Atom) -> Option<usize> {
22694    let AtomView::Mul(product) = pattern.as_view() else {
22695        return None;
22696    };
22697    let factors = product.into_iter().collect::<Vec<_>>();
22698    if factors.iter().any(|factor| {
22699        matches!(
22700            factor,
22701            AtomView::Var(variable) if variable.get_wildcard_level() > 1
22702        )
22703    }) {
22704        None
22705    } else {
22706        Some(factors.len())
22707    }
22708}
22709
22710fn rubi_function_heads(expr: AtomView<'_>) -> Vec<Symbol> {
22711    fn collect(expr: AtomView<'_>, heads: &mut Vec<Symbol>) {
22712        match expr {
22713            AtomView::Fun(function) => {
22714                let head = function.get_symbol();
22715                if !heads.contains(&head) {
22716                    heads.push(head);
22717                }
22718                for argument in function {
22719                    collect(argument, heads);
22720                }
22721            }
22722            AtomView::Add(sum) => {
22723                for term in sum {
22724                    collect(term, heads);
22725                }
22726            }
22727            AtomView::Mul(product) => {
22728                for factor in product {
22729                    collect(factor, heads);
22730                }
22731            }
22732            AtomView::Pow(power) => {
22733                collect(power.get_base(), heads);
22734                collect(power.get_exp(), heads);
22735            }
22736            AtomView::Num(_) | AtomView::Var(_) => {}
22737        }
22738    }
22739
22740    let mut heads = Vec::new();
22741    collect(expr, &mut heads);
22742    heads
22743}
22744
22745fn rubi_has_x_dependent_exponent(expr: AtomView<'_>, x: Symbol) -> bool {
22746    match expr {
22747        AtomView::Pow(power) => {
22748            power.get_exp().contains_symbol(x)
22749                || rubi_has_x_dependent_exponent(power.get_base(), x)
22750                || rubi_has_x_dependent_exponent(power.get_exp(), x)
22751        }
22752        AtomView::Add(sum) => sum
22753            .into_iter()
22754            .any(|term| rubi_has_x_dependent_exponent(term, x)),
22755        AtomView::Mul(product) => product
22756            .into_iter()
22757            .any(|factor| rubi_has_x_dependent_exponent(factor, x)),
22758        AtomView::Fun(function) => function
22759            .into_iter()
22760            .any(|argument| rubi_has_x_dependent_exponent(argument, x)),
22761        AtomView::Num(_) | AtomView::Var(_) => false,
22762    }
22763}
22764
22765fn rubi_has_polynomial_complement_of_affine_power(expr: AtomView<'_>, x: Symbol) -> bool {
22766    let factors = match expr {
22767        AtomView::Mul(product) => product
22768            .into_iter()
22769            .map(|factor| factor.to_owned())
22770            .collect::<Vec<_>>(),
22771        _ => vec![expr.to_owned()],
22772    };
22773
22774    factors.iter().enumerate().any(|(index, factor)| {
22775        let is_affine_power = match factor.as_view() {
22776            AtomView::Pow(power) => {
22777                is_free_of(power.get_exp(), x) && rubi_affine_base_factor_q(power.get_base(), x)
22778            }
22779            factor => rubi_affine_base_factor_q(factor, x),
22780        };
22781        if !is_affine_power {
22782            return false;
22783        }
22784
22785        let complement = factors
22786            .iter()
22787            .enumerate()
22788            .filter(|(other_index, _)| *other_index != index)
22789            .map(|(_, factor)| factor.to_owned())
22790            .fold(Atom::num(1), |product, factor| product * factor);
22791        rubi_polynomial_q(&complement, x)
22792    })
22793}
22794
22795/// Aggregate exponent properties of affine-power factors in a candidate.
22796struct RubiAffinePowerBounds {
22797    has_half_integer: bool,
22798    has_positive_integer: bool,
22799    has_rational_noninteger_below_negative_one: bool,
22800    has_negative_scaled_and_distinct_noninteger: bool,
22801    has_noninteger_with_positive_difference: bool,
22802    noninteger_count: usize,
22803}
22804
22805fn rubi_affine_power_bounds(expr: AtomView<'_>, x: Symbol) -> RubiAffinePowerBounds {
22806    let factors = match expr {
22807        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
22808        _ => vec![expr],
22809    };
22810    let exponents = factors
22811        .into_iter()
22812        .filter_map(|factor| match factor {
22813            AtomView::Pow(power)
22814                if is_free_of(power.get_exp(), x)
22815                    && rubi_affine_base_factor_q(power.get_base(), x) =>
22816            {
22817                Some(power.get_exp().to_owned())
22818            }
22819            AtomView::Pow(_) => None,
22820            _ if rubi_affine_base_factor_q(factor, x) => Some(Atom::num(1)),
22821            _ => None,
22822        })
22823        .collect::<Vec<_>>();
22824
22825    RubiAffinePowerBounds {
22826        has_half_integer: exponents
22827            .iter()
22828            .any(|exponent| integerq!(exponent + Atom::num((1, 2)))),
22829        has_positive_integer: exponents.iter().any(|exponent| igtq!(exponent, 0)),
22830        has_rational_noninteger_below_negative_one: exponents
22831            .iter()
22832            .any(|exponent| rationalq!(exponent) && !integerq!(exponent) && ltq!(exponent, -1)),
22833        has_negative_scaled_and_distinct_noninteger: exponents.iter().enumerate().any(
22834            |(index, exponent)| {
22835                iltq!(Atom::num(2) * exponent, -2)
22836                    && exponents
22837                        .iter()
22838                        .enumerate()
22839                        .any(|(other_index, other)| other_index != index && !integerq!(other))
22840            },
22841        ),
22842        has_noninteger_with_positive_difference: exponents.iter().enumerate().any(
22843            |(index, exponent)| {
22844                !integerq!(exponent)
22845                    && exponents.iter().enumerate().any(|(other_index, other)| {
22846                        other_index != index && igtq!(other - exponent, 0)
22847                    })
22848            },
22849        ),
22850        noninteger_count: exponents
22851            .iter()
22852            .filter(|exponent| !integerq!(*exponent))
22853            .count(),
22854    }
22855}
22856
22857fn rubi_has_algebraic_zero_x_free_additive_part(expr: AtomView<'_>, x: Symbol) -> bool {
22858    let factors = match expr {
22859        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
22860        _ => vec![expr],
22861    };
22862
22863    factors.into_iter().any(|factor| {
22864        let base = match factor {
22865            AtomView::Pow(power) if is_free_of(power.get_exp(), x) => power.get_base(),
22866            AtomView::Pow(_) => return false,
22867            _ => factor,
22868        };
22869        if !base.contains_symbol(x) {
22870            return false;
22871        }
22872
22873        let x_free_part = match base {
22874            AtomView::Add(sum) => sum
22875                .into_iter()
22876                .filter(|term| is_free_of(*term, x))
22877                .map(|term| term.to_owned())
22878                .fold(Atom::num(0), |sum, term| sum + term),
22879            _ => Atom::num(0),
22880        };
22881        rubi_algebraic_zero_q(&x_free_part)
22882    })
22883}
22884
22885fn rubi_has_proportional_binomial_base_pair(expr: AtomView<'_>, x: Symbol) -> bool {
22886    let factors = match expr {
22887        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
22888        _ => vec![expr],
22889    };
22890    let parts = factors
22891        .into_iter()
22892        .filter_map(|factor| {
22893            let base = match factor {
22894                AtomView::Pow(power) if is_free_of(power.get_exp(), x) => power.get_base(),
22895                AtomView::Pow(_) => return None,
22896                _ => factor,
22897            };
22898            rubi_binomial_parts(base, x)
22899        })
22900        .collect::<Vec<_>>();
22901
22902    parts.iter().enumerate().any(|(index, left)| {
22903        parts[index + 1..].iter().any(|right| {
22904            rubi_algebraic_zero_q(&(&left.n - &right.n))
22905                && rubi_algebraic_zero_q(&(&left.b * &right.a - &left.a * &right.b))
22906        })
22907    })
22908}
22909
22910fn rubi_has_opposite_binomial_base_pair(expr: AtomView<'_>, x: Symbol) -> bool {
22911    let factors = match expr {
22912        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
22913        _ => vec![expr],
22914    };
22915    let parts = factors
22916        .into_iter()
22917        .filter_map(|factor| {
22918            let base = match factor {
22919                AtomView::Pow(power) if is_free_of(power.get_exp(), x) => power.get_base(),
22920                AtomView::Pow(_) => return None,
22921                _ => factor,
22922            };
22923            rubi_binomial_parts(base, x)
22924        })
22925        .collect::<Vec<_>>();
22926
22927    parts.iter().enumerate().any(|(index, left)| {
22928        parts[index + 1..].iter().any(|right| {
22929            rubi_algebraic_zero_q(&(&left.n - &right.n))
22930                && rubi_algebraic_zero_q(&(&left.b * &right.a + &left.a * &right.b))
22931        })
22932    })
22933}
22934
22935fn rubi_has_negated_binomial_exponent_pair(expr: AtomView<'_>, x: Symbol) -> bool {
22936    let factors = match expr {
22937        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
22938        _ => vec![expr],
22939    };
22940    let parts = factors
22941        .into_iter()
22942        .filter_map(|factor| {
22943            let base = match factor {
22944                AtomView::Pow(power) if is_free_of(power.get_exp(), x) => power.get_base(),
22945                AtomView::Pow(_) => return None,
22946                _ => factor,
22947            };
22948            rubi_binomial_parts(base, x)
22949        })
22950        .collect::<Vec<_>>();
22951
22952    parts.iter().enumerate().any(|(index, left)| {
22953        parts[index + 1..]
22954            .iter()
22955            .any(|right| rubi_algebraic_zero_q(&(&left.n + &right.n)))
22956    })
22957}
22958
22959fn rubi_max_common_binomial_exponent_factor_count(expr: AtomView<'_>, x: Symbol) -> usize {
22960    let factors = match expr {
22961        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
22962        _ => vec![expr],
22963    };
22964    let exponents = factors
22965        .into_iter()
22966        .filter_map(|factor| {
22967            let base = match factor {
22968                AtomView::Pow(power) if is_free_of(power.get_exp(), x) => power.get_base(),
22969                AtomView::Pow(_) => return None,
22970                _ => factor,
22971            };
22972            rubi_binomial_parts(base, x).map(|parts| parts.n)
22973        })
22974        .collect::<Vec<_>>();
22975
22976    exponents
22977        .iter()
22978        .map(|left| {
22979            exponents
22980                .iter()
22981                .filter(|right| rubi_algebraic_zero_q(&(left - *right)))
22982                .count()
22983        })
22984        .max()
22985        .unwrap_or(0)
22986}
22987
22988fn rubi_max_common_positive_integer_binomial_factor_count(expr: AtomView<'_>, x: Symbol) -> usize {
22989    let factors = match expr {
22990        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
22991        _ => vec![expr],
22992    };
22993    let exponents = factors
22994        .into_iter()
22995        .filter_map(|factor| {
22996            let base = match factor {
22997                AtomView::Pow(power) => {
22998                    if integer_i64_view(power.get_exp()).is_none_or(|power| power <= 0) {
22999                        return None;
23000                    }
23001                    power.get_base()
23002                }
23003                _ => factor,
23004            };
23005            rubi_binomial_parts(base, x).map(|parts| parts.n)
23006        })
23007        .collect::<Vec<_>>();
23008
23009    exponents
23010        .iter()
23011        .map(|left| {
23012            exponents
23013                .iter()
23014                .filter(|right| rubi_algebraic_zero_q(&(left - *right)))
23015                .count()
23016        })
23017        .max()
23018        .unwrap_or(0)
23019}
23020
23021fn rubi_max_common_polynomial_base_degree_count(expr: AtomView<'_>, x: Symbol) -> Option<usize> {
23022    let factors = match expr {
23023        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
23024        _ => vec![expr],
23025    };
23026    let degrees = factors
23027        .into_iter()
23028        .filter(|factor| factor.contains_symbol(x))
23029        .map(|factor| {
23030            let base = match factor {
23031                AtomView::Pow(power) if is_free_of(power.get_exp(), x) => {
23032                    power.get_base().to_owned()
23033                }
23034                AtomView::Pow(_) => return None,
23035                _ => factor.to_owned(),
23036            };
23037            rubi_polynomial_q(&base, x)
23038                .then(|| rubi_expon(base.as_view(), x))
23039                .flatten()
23040        })
23041        .collect::<Option<Vec<_>>>()?;
23042
23043    degrees
23044        .iter()
23045        .map(|left| degrees.iter().filter(|right| *right == left).count())
23046        .max()
23047}
23048
23049fn rubi_has_explicit_variable_power_factor(expr: AtomView<'_>, x: Symbol) -> bool {
23050    let x_atom = Atom::var(x);
23051    let is_variable_power = |factor: AtomView<'_>| match factor {
23052        AtomView::Pow(power) => {
23053            power.get_base().to_owned() == x_atom && is_free_of(power.get_exp(), x)
23054        }
23055        _ => factor.to_owned() == x_atom,
23056    };
23057    match expr {
23058        AtomView::Mul(product) => product.into_iter().any(is_variable_power),
23059        _ => is_variable_power(expr),
23060    }
23061}
23062
23063fn rubi_has_even_quadratic_binomial_base(expr: AtomView<'_>, x: Symbol) -> bool {
23064    let factors = match expr {
23065        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
23066        _ => vec![expr],
23067    };
23068    factors.into_iter().any(|factor| {
23069        let base = match factor {
23070            AtomView::Pow(power) if is_free_of(power.get_exp(), x) => power.get_base(),
23071            AtomView::Pow(_) => return false,
23072            _ => factor,
23073        };
23074        rubi_binomial_parts(base, x).is_some_and(|parts| eqq!(parts.n, Atom::num(2)))
23075    })
23076}
23077
23078fn rubi_has_perfect_square_quadratic_base(expr: AtomView<'_>, x: Symbol) -> bool {
23079    let factors = match expr {
23080        AtomView::Mul(product) => product.into_iter().collect::<Vec<_>>(),
23081        _ => vec![expr],
23082    };
23083    factors.into_iter().any(|factor| {
23084        let base = match factor {
23085            AtomView::Pow(power) if is_free_of(power.get_exp(), x) => power.get_base().to_owned(),
23086            AtomView::Pow(_) => return false,
23087            _ => factor.to_owned(),
23088        };
23089        if rubi_expon(base.as_view(), x) != Some(2) {
23090            return false;
23091        }
23092        let Some(a) = rubi_coeff(&base, x, 0) else {
23093            return false;
23094        };
23095        let Some(b) = rubi_coeff(&base, x, 1) else {
23096            return false;
23097        };
23098        let Some(c) = rubi_coeff(&base, x, 2) else {
23099            return false;
23100        };
23101        rubi_algebraic_zero_q(&(b.pow(2) - Atom::num(4) * a * c))
23102    })
23103}
23104
23105// Rule patterns are already normalized. Walking their syntax is sufficient here and avoids
23106// derivative, expansion, and polynomial-conversion work while the static rule table is built.
23107fn rubi_explicit_pattern_polynomial_degree(expr: AtomView<'_>, x: Symbol) -> Option<usize> {
23108    match expr {
23109        AtomView::Num(_) => Some(0),
23110        AtomView::Var(variable) => Some(usize::from(variable.get_symbol() == x)),
23111        AtomView::Fun(function) => (!function
23112            .into_iter()
23113            .any(|argument| argument.contains_symbol(x)))
23114        .then_some(0),
23115        AtomView::Add(add) => add.into_iter().try_fold(0, |degree, term| {
23116            Some(degree.max(rubi_explicit_pattern_polynomial_degree(term, x)?))
23117        }),
23118        AtomView::Mul(mul) => mul.into_iter().try_fold(0usize, |degree, factor| {
23119            degree.checked_add(rubi_explicit_pattern_polynomial_degree(factor, x)?)
23120        }),
23121        AtomView::Pow(power) => {
23122            if power.get_exp().contains_symbol(x) {
23123                return None;
23124            }
23125            let base_degree = rubi_explicit_pattern_polynomial_degree(power.get_base(), x)?;
23126            if base_degree == 0 {
23127                return Some(0);
23128            }
23129            let AtomView::Num(exponent) = power.get_exp() else {
23130                return None;
23131            };
23132            let CoefficientView::Natural(exponent, 1, 0, 1) = exponent.get_coeff_view() else {
23133                return None;
23134            };
23135            let exponent = usize::try_from(exponent).ok()?;
23136            base_degree.checked_mul(exponent)
23137        }
23138    }
23139}
23140
23141fn rubi_explicit_polynomial_base_q(expr: AtomView<'_>, x: Symbol) -> bool {
23142    let base = match expr {
23143        AtomView::Pow(power) => power.get_base(),
23144        _ => expr,
23145    };
23146    matches!(base, AtomView::Add(_)) && rubi_explicit_pattern_polynomial_degree(base, x).is_some()
23147}
23148
23149fn rubi_polynomial_base_q(expr: AtomView<'_>, x: Symbol) -> bool {
23150    let base = match expr {
23151        AtomView::Pow(power) if is_free_of(power.get_exp(), x) => power.get_base().to_owned(),
23152        AtomView::Pow(_) => return false,
23153        _ => expr.to_owned(),
23154    };
23155    // Optional additive coefficients let a source affine polynomial degenerate
23156    // to a monomial such as x. It must still satisfy a source-derived
23157    // polynomial-factor bound even though its normalized base is not an Add.
23158    if rubi_direct_affine_factor_q(base.as_view(), x) {
23159        return true;
23160    }
23161    if !matches!(base.as_view(), AtomView::Add(_)) {
23162        return false;
23163    }
23164
23165    rubi_polynomial_terms(&base, x).is_some_and(|terms| (2..=3).contains(&terms.len()))
23166        || rubi_generalized_binomial_q(&base, x)
23167        || rubi_generalized_trinomial_q(&base, x)
23168}
23169
23170fn rubi_top_level_polynomial_base_count(expr: AtomView<'_>, x: Symbol) -> usize {
23171    match expr {
23172        AtomView::Mul(product) => product
23173            .into_iter()
23174            .filter(|factor| rubi_polynomial_base_q(*factor, x))
23175            .count(),
23176        _ => usize::from(rubi_polynomial_base_q(expr, x)),
23177    }
23178}
23179
23180fn rubi_top_level_x_factor_count(expr: AtomView<'_>, x: Symbol) -> usize {
23181    match expr {
23182        AtomView::Mul(product) => product
23183            .into_iter()
23184            .filter(|factor| factor.contains_symbol(x))
23185            .count(),
23186        _ => usize::from(expr.contains_symbol(x)),
23187    }
23188}
23189
23190fn rubi_direct_affine_factor_q(expr: AtomView<'_>, x: Symbol) -> bool {
23191    linear_coefficients(expr, x).is_some_and(|(_constant, slope)| !slope.is_zero())
23192}
23193
23194fn rubi_affine_base_factor_q(expr: AtomView<'_>, x: Symbol) -> bool {
23195    let base = match expr {
23196        AtomView::Pow(power) if is_free_of(power.get_exp(), x) => power.get_base(),
23197        AtomView::Pow(_) => return false,
23198        _ => expr,
23199    };
23200    rubi_direct_affine_factor_q(base, x)
23201}
23202
23203fn rubi_top_level_affine_base_factor_count(expr: AtomView<'_>, x: Symbol) -> usize {
23204    match expr {
23205        AtomView::Mul(product) => product
23206            .into_iter()
23207            .filter(|factor| rubi_affine_base_factor_q(*factor, x))
23208            .count(),
23209        _ => usize::from(rubi_affine_base_factor_q(expr, x)),
23210    }
23211}
23212
23213fn rubi_top_level_unpowered_affine_factor_count(expr: AtomView<'_>, x: Symbol) -> usize {
23214    match expr {
23215        AtomView::Mul(product) => product
23216            .into_iter()
23217            .filter(|factor| {
23218                !matches!(factor, AtomView::Pow(_)) && rubi_direct_affine_factor_q(*factor, x)
23219            })
23220            .count(),
23221        AtomView::Pow(_) => 0,
23222        _ => usize::from(rubi_direct_affine_factor_q(expr, x)),
23223    }
23224}
23225
23226fn rubi_has_repeated_proper_x_dependent_subexpression(expr: AtomView<'_>, x: Symbol) -> bool {
23227    fn visit<'a>(expr: AtomView<'a>, x: Symbol, seen: &mut Vec<AtomView<'a>>) -> bool {
23228        for child in rubi_child_views(expr) {
23229            if !matches!(child, AtomView::Var(variable) if variable.get_symbol() == x)
23230                && child.contains_symbol(x)
23231            {
23232                if seen.contains(&child) {
23233                    return true;
23234                }
23235                seen.push(child);
23236            }
23237            if visit(child, x, seen) {
23238                return true;
23239            }
23240        }
23241        false
23242    }
23243
23244    visit(expr, x, &mut Vec::new())
23245}
23246
23247fn wildcard_atom(matches: &symbolica::id::MatchStack<'_>, wildcard: Symbol) -> Option<Atom> {
23248    matches
23249        .get_atom(wildcard)
23250        .map(|atom| atom.to_owned())
23251        .or_else(|| matches.get(wildcard).map(|m| m.to_atom()))
23252}
23253
23254fn wildcard_atom_for_rule(
23255    matches: &symbolica::id::MatchStack<'_>,
23256    wildcard: Symbol,
23257    rule: &RubiRule,
23258) -> Option<Atom> {
23259    #[cfg(feature = "bake-integration-variable")]
23260    if wildcard == rubi_symbols().x_
23261        && let Some((context_rule, x)) = rubi_replacement_context()
23262        && std::ptr::eq(context_rule, rule)
23263    {
23264        return Some(Atom::var(x));
23265    }
23266    #[cfg(not(feature = "bake-integration-variable"))]
23267    let _ = rule;
23268    wildcard_atom(matches, wildcard)
23269}
23270
23271fn wildcard_atoms_for_rule<const N: usize>(
23272    matches: &symbolica::id::MatchStack<'_>,
23273    wildcards: [Symbol; N],
23274    rule: &RubiRule,
23275) -> Option<[Atom; N]> {
23276    // Zero owns no allocation; a failed capture drops the initialized prefix.
23277    // This avoids a heap allocation and the Vec-to-array copy for every match.
23278    let mut atoms = [const { Atom::Zero }; N];
23279    for (atom, wildcard) in atoms.iter_mut().zip(wildcards) {
23280        *atom = wildcard_atom_for_rule(matches, wildcard, rule)?;
23281    }
23282    Some(atoms)
23283}
23284
23285// Specialize once per capture count instead of duplicating extraction and
23286// failure cleanup in each generated condition and action.
23287#[inline(never)]
23288fn required_wildcard_atoms_for_rule<const N: usize>(
23289    matches: &symbolica::id::MatchStack<'_>,
23290    rule: &RubiRule,
23291) -> Option<[Atom; N]> {
23292    let wildcards: [Symbol; N] = rule.required.as_slice().try_into().ok()?;
23293    wildcard_atoms_for_rule(matches, wildcards, rule)
23294}
23295
23296fn wildcard_view_for_rule<'a>(
23297    matches: &symbolica::id::MatchStack<'a>,
23298    wildcard: Symbol,
23299    rule: &RubiRule,
23300) -> Option<AtomOrView<'a>> {
23301    #[cfg(feature = "bake-integration-variable")]
23302    if wildcard == rubi_symbols().x_
23303        && let Some((context_rule, x)) = rubi_replacement_context()
23304        && std::ptr::eq(context_rule, rule)
23305    {
23306        return Some(x.into());
23307    }
23308    #[cfg(not(feature = "bake-integration-variable"))]
23309    let _ = rule;
23310    matches
23311        .get_atom(wildcard)
23312        .map(AtomOrView::View)
23313        .or_else(|| {
23314            matches
23315                .get(wildcard)
23316                .map(|matched| matched.to_atom().into())
23317        })
23318}
23319
23320fn wildcard_captures_are_free(
23321    matches: &symbolica::id::MatchStack<'_>,
23322    rule: &RubiRule,
23323    wildcards: &[Symbol],
23324    integration_symbol: Symbol,
23325) -> bool {
23326    wildcards.iter().all(|wildcard| {
23327        wildcard_view_for_rule(matches, *wildcard, rule)
23328            .is_some_and(|value| is_free_of(value.as_atom_view(), integration_symbol))
23329    })
23330}
23331
23332#[inline(never)]
23333fn wildcard_captures_are_free_and_integer(
23334    matches: &symbolica::id::MatchStack<'_>,
23335    rule: &RubiRule,
23336    free_wildcards: &[Symbol],
23337    integer_wildcard: Symbol,
23338    integration_symbol: Symbol,
23339    expected_required_count: usize,
23340    expected_integer: bool,
23341) -> bool {
23342    if rule.required.len() != expected_required_count {
23343        return false;
23344    }
23345    #[cfg(feature = "bake-integration-variable")]
23346    let baked_x = rubi_replacement_context()
23347        .and_then(|(context_rule, _)| std::ptr::eq(context_rule, rule).then(|| rubi_symbols().x_));
23348    #[cfg(not(feature = "bake-integration-variable"))]
23349    let baked_x: Option<Symbol> = None;
23350    if !rule
23351        .required
23352        .iter()
23353        .all(|wildcard| Some(*wildcard) == baked_x || matches.get(*wildcard).is_some())
23354    {
23355        return false;
23356    }
23357    wildcard_captures_are_free(matches, rule, free_wildcards, integration_symbol)
23358        && wildcard_view_for_rule(matches, integer_wildcard, rule)
23359            .is_some_and(|value| integer_q_view(value.as_atom_view()) == expected_integer)
23360}
23361
23362#[cfg(feature = "trace")]
23363fn current_rule_id() -> Option<&'static str> {
23364    CURRENT_RUBI_RULE.with(|current| {
23365        let rule = current.get();
23366        if rule.is_null() {
23367            None
23368        } else {
23369            // The pointer is set only for the duration of RubiRule::apply.
23370            Some(unsafe { &*rule }.id)
23371        }
23372    })
23373}
23374
23375#[cfg(feature = "trace")]
23376fn trace_direct_polynomial_integration(kind: &str, expr: &Atom) {
23377    if !RUBI_SETTINGS.trace_fallbacks.load(AtomicOrdering::Relaxed) {
23378        return;
23379    }
23380
23381    if let Some(rule_id) = current_rule_id() {
23382        eprintln!("{kind} inside {rule_id}: {expr}");
23383    } else {
23384        eprintln!("{kind}: {expr}");
23385    }
23386}
23387
23388fn substitute_symbol(expr: &Atom, symbol: Symbol, replacement: impl RubiAtomArgument) -> Atom {
23389    expr.replace(Atom::var(symbol).to_pattern())
23390        .with(replacement.into_rubi_atom())
23391}
23392
23393fn rubi_replace_all(expr: &Atom, symbol: Symbol, replacement: impl RubiAtomArgument) -> Atom {
23394    substitute_symbol(expr, symbol, replacement)
23395}
23396
23397fn rubi_subst(expr: &Atom, symbol: Symbol, replacement: impl RubiAtomArgument) -> Atom {
23398    let replacement = replacement.into_rubi_atom();
23399    #[cfg(feature = "steps")]
23400    record_explanation_substitution(symbol, &replacement);
23401    let substituted = rubi_subst_aux(expr, symbol, &replacement);
23402    let substituted = rubi_evaluate_direct_inverse_trig_trig(substituted.as_view());
23403    let antiderivative_variable = rubi_replacement_context()
23404        .map(|(_, integration_variable)| integration_variable)
23405        .unwrap_or(symbol);
23406    rubi_simplify_antiderivative(&substituted, antiderivative_variable)
23407}
23408
23409// IntegrationUtilityFunctions.m: Subst[u_, (a_.*x_)^n_, v_]. For an Int
23410// payload this expresses the integration variable through the monomial before
23411// applying the requested replacement.
23412fn rubi_subst_integral_monomial(
23413    integrand: &Atom,
23414    x: Symbol,
23415    exponent: &Atom,
23416    replacement: Atom,
23417) -> Option<Atom> {
23418    let sub_guard = fresh_substitution_symbol()?;
23419    let sub = sub_guard.symbol();
23420    let sub_atom = Atom::var(sub);
23421    let inverse_exponent = Atom::num(1) / exponent;
23422    let transformed_variable = sub_atom.pow(&inverse_exponent);
23423    let transformed_integrand = substitute_symbol(integrand, x, transformed_variable)
23424        * &inverse_exponent
23425        * sub_atom.pow(&inverse_exponent - Atom::num(1));
23426    let primitive = rubi_rhs_int(&transformed_integrand, sub);
23427
23428    Some(rubi_subst(&primitive, sub, replacement))
23429}
23430
23431fn rubi_simplify_antiderivative(expr: &Atom, x: Symbol) -> Atom {
23432    if is_free_of(expr, x) {
23433        return Atom::num(0);
23434    }
23435
23436    if matches!(expr.as_view(), AtomView::Add(_)) {
23437        return rubi_add_terms(expr)
23438            .into_iter()
23439            .map(|term| rubi_simplify_antiderivative(&term, x))
23440            .fold(Atom::num(0), |sum, term| sum + term);
23441    }
23442
23443    if matches!(expr.as_view(), AtomView::Mul(_)) {
23444        let constant = rubi_free_factors(expr, x);
23445        let dependent = rubi_nonfree_factors(expr, x);
23446        if !constant.is_one() && dependent != *expr {
23447            let simplified = rubi_simplify_antiderivative(&dependent, x);
23448            if rubi_sum_q(&simplified) && rubi_nonsum_q(&dependent) {
23449                return rubi_add_terms(&simplified)
23450                    .into_iter()
23451                    .map(|term| &constant * term)
23452                    .fold(Atom::num(0), |sum, term| sum + term);
23453            }
23454            return constant * simplified;
23455        }
23456    }
23457
23458    if let AtomView::Fun(function) = expr.as_view()
23459        && function.get_nargs() == 1
23460        && function.get_symbol().get_stripped_ascii_name() == Some("log")
23461    {
23462        let argument = function.get(0).to_owned();
23463        if let AtomView::Pow(power) = argument.as_view() {
23464            let (base, exponent) = power.get_base_exp();
23465            let exponent = exponent.to_owned();
23466            if is_free_of(&exponent, x) {
23467                return exponent * rubi_simplify_antiderivative(&base.to_owned().log(), x);
23468            }
23469        }
23470
23471        let removed = rubi_remove_content(&argument, x);
23472        if removed != argument {
23473            return rubi_simplify_antiderivative(&removed.log(), x);
23474        }
23475    }
23476
23477    expr.to_owned()
23478}
23479
23480fn rubi_subst_aux(expr: &Atom, symbol: Symbol, replacement: &Atom) -> Atom {
23481    if let Some(simplified) = rubi_subst_aux_linear_quotient(expr, symbol, replacement) {
23482        return simplified;
23483    }
23484
23485    match expr.as_view() {
23486        AtomView::Var(variable) if variable.get_symbol() == symbol => replacement.to_owned(),
23487        AtomView::Pow(power) => {
23488            let base = rubi_subst_aux(&power.get_base().to_owned(), symbol, replacement);
23489            let exponent = rubi_subst_aux(&power.get_exp().to_owned(), symbol, replacement);
23490            base.pow(exponent)
23491        }
23492        AtomView::Mul(mul) => mul
23493            .into_iter()
23494            .map(|factor| rubi_subst_aux(&factor.to_owned(), symbol, replacement))
23495            .fold(Atom::num(1), |product, factor| product * factor),
23496        AtomView::Add(add) => add
23497            .into_iter()
23498            .map(|term| rubi_subst_aux(&term.to_owned(), symbol, replacement))
23499            .fold(Atom::num(0), |sum, term| sum + term),
23500        AtomView::Fun(function) => function.get_symbol().call_args(
23501            function
23502                .into_iter()
23503                .map(|argument| rubi_subst_aux(&argument.to_owned(), symbol, replacement)),
23504        ),
23505        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
23506    }
23507}
23508
23509fn rubi_subst_aux_linear_quotient(expr: &Atom, symbol: Symbol, replacement: &Atom) -> Option<Atom> {
23510    if !rubi_linear_q(expr.as_view(), symbol) {
23511        return None;
23512    }
23513    let (e, f) = linear_coefficients(expr.as_view(), symbol)?;
23514
23515    for variable in replacement.get_all_symbols(false) {
23516        if variable == symbol {
23517            continue;
23518        }
23519        let Some((a, b, c, d)) = rubi_quotient_of_linears_parts(replacement, variable) else {
23520            continue;
23521        };
23522        if is_free_of((&a, &b, &c, &d, &e, &f), symbol) && eqq!(&d * &e + &b * &f, 0) {
23523            return Some((&c * &e + &a * &f) / (&c + &d * Atom::var(variable)));
23524        }
23525    }
23526    None
23527}
23528
23529fn rubi_evaluate_direct_inverse_trig_trig(expr: AtomView<'_>) -> Atom {
23530    match expr {
23531        AtomView::Fun(function) if function.get_nargs() == 1 => {
23532            let argument = rubi_evaluate_direct_inverse_trig_trig(function.get(0));
23533            if let AtomView::Fun(inverse) = argument.as_view()
23534                && inverse.get_nargs() == 1
23535            {
23536                let inverse_argument = inverse.get(0).to_owned();
23537                let outer_symbol = function.get_symbol();
23538                let inverse_symbol = inverse.get_symbol();
23539                let outer = outer_symbol.get_stripped_ascii_name();
23540                let inner = inverse_symbol.get_stripped_ascii_name();
23541                match (outer, inner) {
23542                    (Some("csc"), Some("acsc")) => return inverse_argument,
23543                    (Some("sin"), Some("acsc")) => {
23544                        return Atom::num(1) / inverse_argument;
23545                    }
23546                    (Some("cos"), Some("acsc")) => {
23547                        return (Atom::num(1) - Atom::num(1) / inverse_argument.pow(2)).sqrt();
23548                    }
23549                    _ => {}
23550                }
23551            }
23552            function.get_symbol().call((argument,))
23553        }
23554        AtomView::Fun(function) => function.get_symbol().call_args(
23555            function
23556                .into_iter()
23557                .map(rubi_evaluate_direct_inverse_trig_trig)
23558                .collect::<Vec<_>>(),
23559        ),
23560        AtomView::Add(add) => add
23561            .into_iter()
23562            .map(rubi_evaluate_direct_inverse_trig_trig)
23563            .fold(Atom::num(0), |sum, term| sum + term),
23564        AtomView::Mul(mul) => mul
23565            .into_iter()
23566            .map(rubi_evaluate_direct_inverse_trig_trig)
23567            .fold(Atom::num(1), |product, factor| product * factor),
23568        AtomView::Pow(power) => rubi_evaluate_direct_inverse_trig_trig(power.get_base())
23569            .pow(rubi_evaluate_direct_inverse_trig_trig(power.get_exp())),
23570        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
23571    }
23572}
23573
23574fn rubi_log_shift_subst(
23575    function_head: &Atom,
23576    a: &Atom,
23577    b: &Atom,
23578    c: &Atom,
23579    d: &Atom,
23580    e: &Atom,
23581    scale: &Atom,
23582    n: &Atom,
23583    x: Symbol,
23584) -> Option<Atom> {
23585    let sub_guard = fresh_substitution_symbol().unwrap();
23586    let sub = sub_guard.symbol();
23587    let sub_atom = Atom::var(sub);
23588    let payload = rubi_function_head_symbol(function_head)?
23589        .call(scale * (a + b * (c * sub_atom.pow(n)).log()));
23590    let primitive = rubi_rhs_int(&payload, sub);
23591    Some(rubi_star(
23592        Atom::num(1) / e,
23593        rubi_subst(&primitive, sub, d + e * Atom::var(x)),
23594    ))
23595}
23596
23597fn rubi_log_shift_power_subst(
23598    function_head: &Atom,
23599    a: &Atom,
23600    b: &Atom,
23601    c: &Atom,
23602    d: &Atom,
23603    e: &Atom,
23604    scale: &Atom,
23605    g: &Atom,
23606    m: &Atom,
23607    n: &Atom,
23608    x: Symbol,
23609) -> Option<Atom> {
23610    let sub_guard = fresh_substitution_symbol().unwrap();
23611    let sub = sub_guard.symbol();
23612    let sub_atom = Atom::var(sub);
23613    let payload = (g * &sub_atom / d).pow(m)
23614        * rubi_function_head_symbol(function_head)?
23615            .call(scale * (a + b * (c * sub_atom.pow(n)).log()));
23616    let primitive = rubi_rhs_int(&payload, sub);
23617    Some(rubi_star(
23618        Atom::num(1) / e,
23619        rubi_subst(&primitive, sub, d + e * Atom::var(x)),
23620    ))
23621}
23622
23623fn rubi_subst_expression(expr: &Atom, target: &Atom, replacement: impl RubiAtomArgument) -> Atom {
23624    expr.replace(target.to_pattern())
23625        .with(replacement.into_rubi_atom())
23626}
23627
23628// IntegrationUtilityFunctions.m: Subst[u_,(a_.*x_)^n_,v_].
23629fn rubi_subst_power_target(
23630    expr: &Atom,
23631    x: Symbol,
23632    scale: &Atom,
23633    exponent: &Atom,
23634    replacement: &Atom,
23635) -> Atom {
23636    if let Some((numerator, denominator)) = rational_number(exponent)
23637        && numerator != 1
23638    {
23639        let unit_exponent = Atom::num(1) / Atom::num(denominator);
23640        let base = scale * Atom::var(x);
23641        let adjusted_replacement = replacement / base.pow(exponent - &unit_exponent);
23642        return rubi_subst_power_target(expr, x, scale, &unit_exponent, &adjusted_replacement);
23643    }
23644
23645    let target_base = scale * Atom::var(x);
23646    rubi_subst_power_target_aux(expr, x, &target_base, exponent, replacement)
23647}
23648
23649fn rubi_subst_power_target_aux(
23650    expr: &Atom,
23651    x: Symbol,
23652    target_base: &Atom,
23653    target_exponent: &Atom,
23654    replacement: &Atom,
23655) -> Atom {
23656    let target = target_base.pow(target_exponent);
23657    if expr == &target {
23658        return replacement.to_owned();
23659    }
23660
23661    match expr.as_view() {
23662        AtomView::Pow(power) => {
23663            let (base, exponent) = power.get_base_exp();
23664            let base = base.to_owned();
23665            let exponent = exponent.to_owned();
23666
23667            if base == *target_base && freeq!(exponent, x) {
23668                let ratio = rubi_simplify(&(&exponent / target_exponent));
23669                if integerq!(ratio) {
23670                    return rubi_simplify(&replacement.pow(ratio));
23671                }
23672
23673                if rubi_sum_q(&exponent) {
23674                    return rubi_add_terms(&exponent)
23675                        .into_iter()
23676                        .map(|term| {
23677                            rubi_subst_power_target_aux(
23678                                &base.pow(term),
23679                                x,
23680                                target_base,
23681                                target_exponent,
23682                                replacement,
23683                            )
23684                        })
23685                        .fold(Atom::num(1), |product, factor| product * factor);
23686                }
23687
23688                let expanded_exponent = exponent.expand();
23689                if rubi_sum_q(&expanded_exponent) {
23690                    return rubi_add_terms(&expanded_exponent)
23691                        .into_iter()
23692                        .map(|term| {
23693                            rubi_subst_power_target_aux(
23694                                &base.pow(term),
23695                                x,
23696                                target_base,
23697                                target_exponent,
23698                                replacement,
23699                            )
23700                        })
23701                        .fold(Atom::num(1), |product, factor| product * factor);
23702                }
23703
23704                let (numeric, nonnumeric) = rubi_split_numeric_factor(&expanded_exponent);
23705                let numeric_numerator = numeric
23706                    .numerator_ref()
23707                    .to_i64()
23708                    .expect("rational exponent numerator originated as i64");
23709                let numeric_denominator = numeric
23710                    .denominator_ref()
23711                    .to_i64()
23712                    .expect("rational exponent denominator originated as i64");
23713                if numeric_numerator != 1 {
23714                    let reduced_exponent = nonnumeric / Atom::num(numeric_denominator);
23715                    return rubi_subst_power_target_aux(
23716                        &base.pow(reduced_exponent),
23717                        x,
23718                        target_base,
23719                        target_exponent,
23720                        replacement,
23721                    )
23722                    .pow(numeric_numerator);
23723                }
23724            }
23725
23726            let substituted_base =
23727                rubi_subst_power_target_aux(&base, x, target_base, target_exponent, replacement);
23728            let substituted_exponent = rubi_subst_power_target_aux(
23729                &exponent,
23730                x,
23731                target_base,
23732                target_exponent,
23733                replacement,
23734            );
23735            substituted_base.pow(substituted_exponent)
23736        }
23737        AtomView::Mul(mul) => mul
23738            .into_iter()
23739            .map(|factor| {
23740                rubi_subst_power_target_aux(
23741                    &factor.to_owned(),
23742                    x,
23743                    target_base,
23744                    target_exponent,
23745                    replacement,
23746                )
23747            })
23748            .fold(Atom::num(1), |product, factor| product * factor),
23749        AtomView::Add(add) => add
23750            .into_iter()
23751            .map(|term| {
23752                rubi_subst_power_target_aux(
23753                    &term.to_owned(),
23754                    x,
23755                    target_base,
23756                    target_exponent,
23757                    replacement,
23758                )
23759            })
23760            .fold(Atom::num(0), |sum, term| sum + term),
23761        AtomView::Fun(function)
23762            if function.get_symbol() == rubi_symbols().rubi_int
23763                || function.get_symbol() == rubi_symbols().unintegrable =>
23764        {
23765            expr.to_owned()
23766        }
23767        AtomView::Fun(function) => {
23768            function
23769                .get_symbol()
23770                .call_args(function.into_iter().map(|argument| {
23771                    rubi_subst_power_target_aux(
23772                        &argument.to_owned(),
23773                        x,
23774                        target_base,
23775                        target_exponent,
23776                        replacement,
23777                    )
23778                }))
23779        }
23780        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
23781    }
23782}
23783
23784#[cfg(test)]
23785fn integrate_generated_payload(expr: &Atom, x: Symbol) -> Option<Atom> {
23786    if rubi_abort_requested() {
23787        return None;
23788    }
23789
23790    Some(rubi_rhs_int(expr, x))
23791}
23792
23793fn rubi_deferred_integral(expr: &Atom, x: Symbol) -> Atom {
23794    rubi_unintegrable(expr.to_owned(), x)
23795}
23796
23797fn rubi_defer_unintegrable_calls(expr: AtomView<'_>) -> Atom {
23798    match expr {
23799        AtomView::Fun(function) => {
23800            let symbols = rubi_symbols();
23801            if function.get_symbol() == symbols.unintegrable && function.get_nargs() == 2 {
23802                return expr.to_owned();
23803            }
23804
23805            let args: Vec<_> = function
23806                .into_iter()
23807                .map(rubi_defer_unintegrable_calls)
23808                .collect();
23809            function.get_symbol().call_args(args)
23810        }
23811        AtomView::Add(add) => add
23812            .into_iter()
23813            .map(rubi_defer_unintegrable_calls)
23814            .fold(Atom::num(0), |sum, term| sum + term),
23815        AtomView::Mul(mul) => mul
23816            .into_iter()
23817            .map(rubi_defer_unintegrable_calls)
23818            .fold(Atom::num(1), |product, factor| product * factor),
23819        AtomView::Pow(power) => rubi_defer_unintegrable_calls(power.get_base())
23820            .pow(rubi_defer_unintegrable_calls(power.get_exp())),
23821        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
23822    }
23823}
23824
23825fn rubi_rhs_int(expr: impl RubiAtomArgument, x: Symbol) -> Atom {
23826    // Mathematica evaluates active trig calls in an Int RHS before dispatching
23827    // the recursive Rubi rules, e.g. Csc[z+Pi/2] becomes Sec[z].
23828    let expr = expr.rubi_atom_or_view();
23829    let evaluated = rubi_reduce_builtin_trig_pi_shifts_view(expr.as_view());
23830    #[cfg(feature = "steps")]
23831    if RUBI_CAPTURE_RULE_RHS.with(Cell::get) {
23832        return rubi_symbols().rubi_int.call((evaluated, Atom::var(x)));
23833    }
23834    integrate_deferred(evaluated.as_view(), x)
23835        .map(|result| rubi_defer_unintegrable_calls(result.as_view()))
23836        .unwrap_or_else(|| rubi_deferred_integral(&evaluated, x))
23837}
23838
23839fn integer_i64(expr: &Atom) -> Option<i64> {
23840    integer_i64_view(expr.as_view())
23841}
23842
23843fn integer_i64_view(expr: AtomView<'_>) -> Option<i64> {
23844    if let Some(value) = raw_integer_i64(expr) {
23845        return Some(value);
23846    }
23847
23848    let expanded = expr.expand();
23849    if expanded.as_view() != expr {
23850        return raw_integer_i64(expanded.as_view());
23851    }
23852
23853    None
23854}
23855
23856fn raw_integer_i64(expr: AtomView<'_>) -> Option<i64> {
23857    match expr {
23858        AtomView::Num(number) => match number.get_coeff_view() {
23859            CoefficientView::Natural(value, 1, 0, 1) => Some(value),
23860            _ => None,
23861        },
23862        _ => None,
23863    }
23864}
23865
23866fn half_integer_atom(numerator: i64) -> Atom {
23867    Atom::num(numerator) / Atom::num(2)
23868}
23869
23870fn half_integer_numerator(expr: &Atom) -> Option<i64> {
23871    match expr.as_view() {
23872        AtomView::Num(number) => match number.get_coeff_view() {
23873            CoefficientView::Natural(numerator, 2, 0, 1) if numerator % 2 != 0 => Some(numerator),
23874            _ => None,
23875        },
23876        _ => None,
23877    }
23878}
23879
23880fn rational_number(expr: &Atom) -> Option<(i64, i64)> {
23881    rational_number_view(expr.as_view())
23882}
23883
23884fn rational_number_view(expr: AtomView<'_>) -> Option<(i64, i64)> {
23885    match expr {
23886        AtomView::Num(number) => match number.get_coeff_view() {
23887            CoefficientView::Natural(numerator, denominator, 0, 1) if denominator > 0 => {
23888                Some((numerator, denominator))
23889            }
23890            _ => None,
23891        },
23892        _ => None,
23893    }
23894}
23895
23896fn rational_q(expr: &Atom) -> bool {
23897    rational_number(expr).is_some()
23898}
23899
23900fn rational_denominator(expr: &Atom) -> Option<i64> {
23901    rational_number(expr).map(|(_, denominator)| denominator)
23902}
23903
23904fn rubi_denominator(expr: &Atom) -> Option<i64> {
23905    rational_denominator(expr)
23906}
23907
23908fn rubi_numerator(expr: &Atom) -> Atom {
23909    rational_numerator_denominator_unexpanded(expr)
23910        .map(|(numerator, _)| numerator)
23911        .unwrap_or_else(|| expr.to_owned())
23912}
23913
23914fn rubi_denominator_atom(expr: &Atom) -> Atom {
23915    rational_numerator_denominator_unexpanded(expr)
23916        .map(|(_, denominator)| denominator)
23917        .unwrap_or_else(|| Atom::num(1))
23918}
23919
23920fn rubi_nice_sqrt_q(expr: &Atom) -> bool {
23921    if rational_q(expr) {
23922        return gtq!(expr, 0);
23923    }
23924
23925    !rubi_fractional_power_factor_q(&rubi_rt(expr, 2))
23926}
23927
23928fn rubi_fractional_power_factor_q(expr: &Atom) -> bool {
23929    match expr.as_view() {
23930        AtomView::Num(number) => !number.get_coeff_view().is_real(),
23931        AtomView::Pow(power) => {
23932            let (_, exponent) = power.get_base_exp();
23933            rational_number_view(exponent).is_some_and(|(_, denominator)| denominator > 1)
23934        }
23935        AtomView::Mul(mul) => mul
23936            .into_iter()
23937            .any(|factor| rubi_fractional_power_factor_q(&factor.to_owned())),
23938        _ => false,
23939    }
23940}
23941
23942fn fractional_part_atom(expr: &Atom) -> Option<Atom> {
23943    let (numerator, denominator) = rational_number(expr)?;
23944    let fractional_numerator = numerator.rem_euclid(denominator);
23945    Some(Atom::num(fractional_numerator) / Atom::num(denominator))
23946}
23947
23948fn rubi_frac_part(expr: &Atom) -> Atom {
23949    rubi_frac_part_scaled(expr, &Atom::num(1))
23950}
23951
23952fn rubi_frac_part_scaled(expr: &Atom, scale: &Atom) -> Atom {
23953    if let Some(fractional_part) = fractional_part_atom(&(scale * expr)) {
23954        return fractional_part;
23955    }
23956
23957    match expr.as_view() {
23958        AtomView::Add(add) => add
23959            .into_iter()
23960            .map(|term| rubi_frac_part_scaled(&term.to_owned(), scale))
23961            .fold(Atom::num(0), |sum, term| sum + term),
23962        AtomView::Mul(mul) => {
23963            let mut rational_scale = scale.to_owned();
23964            let mut nonrational_factors = Vec::new();
23965            let factor_count = mul.get_nargs();
23966            for factor in mul {
23967                let factor = factor.to_owned();
23968                if rational_number(&factor).is_some() {
23969                    rational_scale *= factor;
23970                } else {
23971                    nonrational_factors.push(factor);
23972                }
23973            }
23974            if nonrational_factors.len() < factor_count {
23975                rubi_frac_part_scaled(&product_atoms(&nonrational_factors), &rational_scale)
23976            } else {
23977                scale * expr
23978            }
23979        }
23980        _ => scale * expr,
23981    }
23982}
23983
23984fn rubi_mathematica_unscaled_reciprocal_power_product(
23985    coefficient: &Atom,
23986    first: Atom,
23987    second: Atom,
23988    exponent: &Atom,
23989) -> Atom {
23990    // Mathematica evaluates unscaled reciprocal products such as
23991    // Cot[z]^(9/2)*Tan[z]^(9/2) to Sqrt[Cot[z]]*Sqrt[Tan[z]], while keeping
23992    // (c*Cot[z])^m*(c*Tan[z])^m structurally present for symbolic c or m.
23993    if coefficient.is_one() && rational_number(exponent).is_some() {
23994        first.pow(rubi_frac_part(exponent)) * second.pow(rubi_frac_part(exponent))
23995    } else {
23996        (coefficient * first).pow(exponent) * (coefficient * second).pow(exponent)
23997    }
23998}
23999
24000fn rubi_mathematica_unscaled_reciprocal_power_product2(
24001    first_coefficient: &Atom,
24002    first: Atom,
24003    second_coefficient: &Atom,
24004    second: Atom,
24005    exponent: &Atom,
24006) -> Atom {
24007    // Same Mathematica simplification as above for source rows with two
24008    // optional coefficients, both defaulting to one.
24009    if first_coefficient.is_one()
24010        && second_coefficient.is_one()
24011        && rational_number(exponent).is_some()
24012    {
24013        first.pow(rubi_frac_part(exponent)) * second.pow(rubi_frac_part(exponent))
24014    } else {
24015        (first_coefficient * first).pow(exponent) * (second_coefficient * second).pow(exponent)
24016    }
24017}
24018
24019fn rubi_int_part(expr: &Atom) -> Atom {
24020    rubi_int_part_scaled(expr, &Atom::num(1))
24021}
24022
24023fn rubi_int_part_scaled(expr: &Atom, scale: &Atom) -> Atom {
24024    if let Some(integer_part) = integer_part_atom(&(scale * expr)) {
24025        return integer_part;
24026    }
24027
24028    match expr.as_view() {
24029        AtomView::Add(add) => add
24030            .into_iter()
24031            .map(|term| rubi_int_part_scaled(&term.to_owned(), scale))
24032            .fold(Atom::num(0), |sum, term| sum + term),
24033        AtomView::Mul(mul) => {
24034            let mut rational_scale = scale.to_owned();
24035            let mut nonrational_factors = Vec::new();
24036            let factor_count = mul.get_nargs();
24037            for factor in mul {
24038                let factor = factor.to_owned();
24039                if rational_number(&factor).is_some() {
24040                    rational_scale *= factor;
24041                } else {
24042                    nonrational_factors.push(factor);
24043                }
24044            }
24045            if nonrational_factors.len() < factor_count {
24046                rubi_int_part_scaled(&product_atoms(&nonrational_factors), &rational_scale)
24047            } else {
24048                Atom::num(0)
24049            }
24050        }
24051        _ => Atom::num(0),
24052    }
24053}
24054
24055fn rubi_signed_quotient_part(expr: &Atom) -> Option<Atom> {
24056    let (numerator, denominator) = rational_number(expr)?;
24057    if numerator == 0 {
24058        return Some(Atom::num(0));
24059    }
24060
24061    let sign = if numerator > 0 { 1 } else { -1 };
24062    Some(Atom::num(sign * (numerator * sign).div_euclid(denominator)))
24063}
24064
24065fn rubi_signed_mod_part(expr: &Atom) -> Option<Atom> {
24066    Some(expr - rubi_signed_quotient_part(expr)?)
24067}
24068
24069fn rubi_mod(left: &Atom, right: &Atom) -> Option<Atom> {
24070    let left = integer_i64(left)?;
24071    let right = integer_i64(right)?;
24072    if right == 0 {
24073        return None;
24074    }
24075    Some(Atom::num(left.rem_euclid(right)))
24076}
24077
24078fn rubi_rt(expr: &Atom, n: i64) -> Atom {
24079    if n == 0 {
24080        return expr.pow(Atom::num(1) / Atom::num(n));
24081    }
24082
24083    // Mathematica TogetherSimplify preserves an already-visible power here;
24084    // Symbolica's together().cancel() may expand its polynomial base.
24085    if matches!(expr.as_view(), AtomView::Pow(_)) {
24086        return rubi_rt_aux(expr, n);
24087    }
24088
24089    let simplified = expr.together();
24090    rubi_rt_aux(&simplified, n)
24091}
24092
24093fn rubi_normalize_numeric_roots(expr: AtomView<'_>) -> Atom {
24094    match expr {
24095        AtomView::Pow(power) => {
24096            let (base, exponent) = power.get_base_exp();
24097            let base = rubi_normalize_numeric_roots(base);
24098            let exponent = rubi_normalize_numeric_roots(exponent);
24099            if let Some((numerator, denominator)) = rational_number(&exponent) {
24100                if denominator > 1 && rational_number(&base).is_some() {
24101                    let root = rubi_rt(&base, denominator);
24102                    return if numerator == 1 {
24103                        root
24104                    } else {
24105                        root.pow(numerator)
24106                    };
24107                }
24108            }
24109            base.pow(exponent)
24110        }
24111        AtomView::Add(add) => add
24112            .into_iter()
24113            .map(rubi_normalize_numeric_roots)
24114            .fold(Atom::num(0), |sum, term| sum + term),
24115        AtomView::Mul(mul) => mul
24116            .into_iter()
24117            .map(rubi_normalize_numeric_roots)
24118            .fold(Atom::num(1), |product, factor| product * factor),
24119        AtomView::Fun(function) => {
24120            let args: Vec<_> = function
24121                .into_iter()
24122                .map(rubi_normalize_numeric_roots)
24123                .collect();
24124            function.get_symbol().call_args(args)
24125        }
24126        AtomView::Var(_) | AtomView::Num(_) => expr.to_owned(),
24127    }
24128}
24129
24130fn rubi_rt_aux(expr: &Atom, n: i64) -> Atom {
24131    if let Some((numerator, denominator)) = rational_number(expr) {
24132        if denominator == 1 {
24133            if let Some(root) = exact_integer_nth_root(numerator, n) {
24134                return Atom::num(root);
24135            }
24136            if let Some((root, radicand)) = extract_integer_nth_power(numerator, n) {
24137                return Atom::num(root) * Atom::num(radicand).pow(Atom::num(1) / Atom::num(n));
24138            }
24139        } else if let (Some(numerator_root), Some(denominator_root)) = (
24140            exact_integer_nth_root(numerator, n),
24141            exact_integer_nth_root(denominator, n),
24142        ) {
24143            return Atom::num(numerator_root) / Atom::num(denominator_root);
24144        } else if n > 1 && numerator > 0 && denominator > 0 {
24145            return rubi_rt_aux(
24146                &(Atom::num(numerator) * Atom::num(denominator).pow(n - 1)),
24147                n,
24148            ) / Atom::num(denominator);
24149        }
24150    }
24151
24152    match expr.as_view() {
24153        AtomView::Pow(power) => {
24154            let (base, exponent) = power.get_base_exp();
24155            return base.to_owned().pow(exponent.to_owned() / Atom::num(n));
24156        }
24157        AtomView::Mul(mul) => {
24158            let mut factors = mul
24159                .into_iter()
24160                .map(|factor| factor.to_owned())
24161                .collect::<Vec<_>>();
24162            if n % 2 == 0
24163                && let Some(minus_index) =
24164                    factors.iter().position(|factor| factor == &Atom::num(-1))
24165            {
24166                let _ = factors.remove(minus_index);
24167                if factors.len() == 1 {
24168                    return (-factors.remove(0)).pow(Atom::num(1) / Atom::num(n));
24169                }
24170                if let Some(first) = factors.first_mut() {
24171                    *first = -first.to_owned();
24172                } else {
24173                    return Atom::num(-1).pow(Atom::num(1) / Atom::num(n));
24174                }
24175            }
24176            return factors
24177                .into_iter()
24178                .map(|factor| rubi_rt_aux(&factor, n))
24179                .fold(Atom::num(1), |product, factor| product * factor);
24180        }
24181        _ => {}
24182    }
24183
24184    if n % 2 != 0 && ltq!(expr, 0) {
24185        return -rubi_rt_aux(&(-expr), n);
24186    }
24187
24188    expr.pow(Atom::num(1) / Atom::num(n))
24189}
24190
24191fn extract_integer_nth_power(value: i64, n: i64) -> Option<(i64, i64)> {
24192    if n <= 0 || value == 0 {
24193        return None;
24194    }
24195    if value < 0 {
24196        if n % 2 == 0 {
24197            return None;
24198        }
24199        return extract_integer_nth_power(value.checked_neg()?, n)
24200            .map(|(root, radicand)| (-root, radicand));
24201    }
24202
24203    let mut remaining = value;
24204    let mut root = 1_i64;
24205    let mut radicand = 1_i64;
24206    let mut factor = 2_i64;
24207    while factor
24208        .checked_mul(factor)
24209        .is_some_and(|square| square <= remaining)
24210    {
24211        let mut exponent = 0_i64;
24212        while remaining % factor == 0 {
24213            remaining /= factor;
24214            exponent += 1;
24215        }
24216        if exponent > 0 {
24217            root = root.checked_mul(checked_i64_pow(factor, (exponent / n) as u32)?)?;
24218            radicand = radicand.checked_mul(checked_i64_pow(factor, (exponent % n) as u32)?)?;
24219        }
24220        factor += if factor == 2 { 1 } else { 2 };
24221    }
24222    if remaining > 1 {
24223        radicand = radicand.checked_mul(remaining)?;
24224    }
24225
24226    (root != 1).then_some((root, radicand))
24227}
24228
24229fn exact_integer_nth_root(value: i64, n: i64) -> Option<i64> {
24230    if n <= 0 {
24231        return None;
24232    }
24233    if value < 0 {
24234        if n % 2 == 0 {
24235            return None;
24236        }
24237        return exact_integer_nth_root(value.checked_neg()?, n).map(|root| -root);
24238    }
24239
24240    let mut low = 0_i64;
24241    let mut high = value.max(1);
24242    while low <= high {
24243        let mid = low + (high - low) / 2;
24244        let powered = checked_i64_pow(mid, n as u32)?;
24245        match powered.cmp(&value) {
24246            std::cmp::Ordering::Equal => return Some(mid),
24247            std::cmp::Ordering::Less => low = mid + 1,
24248            std::cmp::Ordering::Greater => high = mid - 1,
24249        }
24250    }
24251
24252    None
24253}
24254
24255fn checked_i64_pow(base: i64, exponent: u32) -> Option<i64> {
24256    let mut result = 1_i64;
24257    for _ in 0..exponent {
24258        result = result.checked_mul(base)?;
24259    }
24260    Some(result)
24261}
24262
24263fn rubi_inverse_function_free_q(expr: &Atom, x: Symbol) -> bool {
24264    fn is_restricted_head(symbol: Symbol) -> bool {
24265        let symbols = rubi_symbols();
24266        matches!(
24267            symbol,
24268            s if s == symbol!("asin")
24269                || s == symbol!("acos")
24270                || s == symbol!("atan")
24271                || s == symbol!("acot")
24272                || s == symbol!("asec")
24273                || s == symbol!("acsc")
24274                || s == symbol!("asinh")
24275                || s == symbol!("acosh")
24276                || s == symbol!("atanh")
24277                || s == symbol!("acoth")
24278                || s == symbol!("asech")
24279                || s == symbol!("acsch")
24280                || s == symbol!("log")
24281                || s == symbol!("Mods")
24282                || s == symbol!("polylog")
24283                || s == symbol!("D")
24284                || s == symbol!("Integrate")
24285                || s == symbol!("Sum")
24286                || s == symbol!("Product")
24287                || s == symbol!("Dif")
24288                || s == symbol!("Subst")
24289                || s == symbol!("CannotIntegrate")
24290                || s == symbols.rubi_int
24291                || s == symbols.unintegrable
24292                || s == symbols.hypergeometric2f1
24293                || s == symbols.appell_f1
24294        )
24295    }
24296
24297    fn recur(expr: AtomView<'_>, x: Symbol) -> bool {
24298        match expr {
24299            AtomView::Fun(function) => {
24300                if is_restricted_head(function.get_symbol()) && !is_free_of(expr, x) {
24301                    return false;
24302                }
24303                function.into_iter().all(|argument| recur(argument, x))
24304            }
24305            AtomView::Add(add) => add.into_iter().all(|term| recur(term, x)),
24306            AtomView::Mul(mul) => mul.into_iter().all(|factor| recur(factor, x)),
24307            AtomView::Pow(power) => recur(power.get_base(), x) && recur(power.get_exp(), x),
24308            AtomView::Num(_) | AtomView::Var(_) => true,
24309        }
24310    }
24311
24312    recur(expr.as_view(), x)
24313}
24314
24315#[derive(Clone, Copy)]
24316/// Inverse trigonometric or hyperbolic heads used by shared rule helpers.
24317enum RubiInverseKind {
24318    ArcTan,
24319    ArcCot,
24320    ArcTanh,
24321    ArcCoth,
24322}
24323
24324/// A located inverse function whose argument is affine in the integration variable.
24325struct RubiInverseLinear {
24326    tmp: Atom,
24327    argument: Atom,
24328    constant: Atom,
24329    slope: Atom,
24330}
24331
24332fn rubi_has_free_base_power(expr: AtomView<'_>, x: Symbol) -> bool {
24333    match expr {
24334        AtomView::Pow(power) => {
24335            let (base, _) = power.get_base_exp();
24336            is_free_of(base, x)
24337        }
24338        AtomView::Mul(mul) => mul
24339            .into_iter()
24340            .any(|factor| rubi_has_free_base_power(factor, x)),
24341        _ => false,
24342    }
24343}
24344
24345fn rubi_inverse_function_of_linear(
24346    expr: &Atom,
24347    x: Symbol,
24348    kind: RubiInverseKind,
24349) -> Option<RubiInverseLinear> {
24350    fn recur(expr: AtomView<'_>, x: Symbol) -> Option<Atom> {
24351        let owned = expr.to_owned();
24352        if atom_q(expr) || is_free_of(&owned, x) {
24353            return None;
24354        }
24355        if matches!(expr, AtomView::Fun(function) if rubi_calculus_function_symbol(function.get_symbol()))
24356        {
24357            return None;
24358        }
24359        if rubi_inverse_function_q(&owned)
24360            && let AtomView::Fun(function) = expr
24361            && function.get_nargs() >= 1
24362            && rubi_linear_q(function.get(0), x)
24363        {
24364            return Some(owned);
24365        }
24366
24367        match expr {
24368            AtomView::Fun(function) => function.into_iter().find_map(|argument| recur(argument, x)),
24369            AtomView::Add(add) => add.into_iter().find_map(|term| recur(term, x)),
24370            AtomView::Mul(mul) => mul.into_iter().find_map(|factor| recur(factor, x)),
24371            AtomView::Pow(power) => {
24372                let (base, exponent) = power.get_base_exp();
24373                recur(base, x).or_else(|| recur(exponent, x))
24374            }
24375            AtomView::Num(_) | AtomView::Var(_) => None,
24376        }
24377    }
24378
24379    let tmp = recur(expr.as_view(), x)?;
24380    let AtomView::Fun(function) = tmp.as_view() else {
24381        return None;
24382    };
24383    if function.get_symbol() != rubi_inverse_function_symbol(kind) || function.get_nargs() < 1 {
24384        return None;
24385    }
24386    let argument = function.get(0).to_owned();
24387    let constant = polynomial_coefficient(&argument, x, 0)?;
24388    let slope = polynomial_coefficient(&argument, x, 1)?;
24389    if eqq!(slope, 0) {
24390        return None;
24391    }
24392
24393    Some(RubiInverseLinear {
24394        tmp,
24395        argument,
24396        constant,
24397        slope,
24398    })
24399}
24400
24401/// Shared match data for inverse-linear functions paired with a quadratic.
24402struct RubiInverseLinearQuadraticMatch {
24403    inverse_function: Atom,
24404    linear_slope: Atom,
24405    discriminant: Atom,
24406    quadratic_coeff: Atom,
24407    transformed_u: Atom,
24408}
24409
24410fn rubi_inverse_linear_quadratic_match(
24411    u: &Atom,
24412    v: &Atom,
24413    x: Symbol,
24414    kind: RubiInverseKind,
24415) -> Option<RubiInverseLinearQuadraticMatch> {
24416    if !rubi_quadratic_q(v, x) {
24417        return None;
24418    }
24419    if !rubi_has_free_base_power(u.as_view(), x) {
24420        return None;
24421    }
24422
24423    let coefficient_0 = polynomial_coefficient(v, x, 0)?;
24424    let coefficient_1 = polynomial_coefficient(v, x, 1)?;
24425    let coefficient_2 = polynomial_coefficient(v, x, 2)?;
24426    if coefficient_2.is_zero() {
24427        return None;
24428    }
24429
24430    let discriminant = coefficient_1.pow(2) - Atom::num(4) * &coefficient_0 * &coefficient_2;
24431    let discriminant_sign_matches = match kind {
24432        RubiInverseKind::ArcTan | RubiInverseKind::ArcCot => negq!(discriminant.to_owned()),
24433        RubiInverseKind::ArcTanh | RubiInverseKind::ArcCoth => posq!(discriminant.to_owned()),
24434    };
24435    if !discriminant_sign_matches {
24436        return None;
24437    }
24438
24439    let inverse = rubi_inverse_function_of_linear(u, x, kind)?;
24440    let derivative = v.derivative(x).expand();
24441    let discriminant_relation = match kind {
24442        RubiInverseKind::ArcTan | RubiInverseKind::ArcCot => {
24443            &discriminant * inverse.argument.pow(2) + derivative.pow(2)
24444        }
24445        RubiInverseKind::ArcTanh | RubiInverseKind::ArcCoth => {
24446            &discriminant * inverse.argument.pow(2) - derivative.pow(2)
24447        }
24448    };
24449    if !eqq!(discriminant_relation, 0) {
24450        return None;
24451    }
24452
24453    let substitution_guard = fresh_substitution_symbol().unwrap();
24454    let substitution_symbol = substitution_guard.symbol();
24455    let transformed_u = rubi_subst_for_inverse_function(u, x, substitution_symbol, &inverse, kind);
24456    if transformed_u == *u || !is_free_of(&transformed_u, x) {
24457        return None;
24458    }
24459
24460    Some(RubiInverseLinearQuadraticMatch {
24461        inverse_function: inverse.tmp,
24462        linear_slope: inverse.slope,
24463        discriminant,
24464        quadratic_coeff: coefficient_2,
24465        transformed_u,
24466    })
24467}
24468
24469fn rubi_inverse_function_symbol(kind: RubiInverseKind) -> Symbol {
24470    match kind {
24471        RubiInverseKind::ArcTan => symbol!("atan"),
24472        RubiInverseKind::ArcCot => symbol!("acot"),
24473        RubiInverseKind::ArcTanh => symbol!("atanh"),
24474        RubiInverseKind::ArcCoth => symbol!("acoth"),
24475    }
24476}
24477
24478fn rubi_inverse_function_inverse_call(kind: RubiInverseKind, argument: Atom) -> Atom {
24479    match kind {
24480        RubiInverseKind::ArcTan => argument.tan(),
24481        RubiInverseKind::ArcCot => argument.cot(),
24482        RubiInverseKind::ArcTanh => argument.tanh(),
24483        RubiInverseKind::ArcCoth => argument.coth(),
24484    }
24485}
24486
24487fn rubi_subst_for_inverse_function(
24488    expr: &Atom,
24489    x: Symbol,
24490    sub: Symbol,
24491    tmp: &RubiInverseLinear,
24492    kind: RubiInverseKind,
24493) -> Atom {
24494    let sub_atom = Atom::var(sub);
24495    let inverse_x = (rubi_inverse_function_inverse_call(kind, sub_atom.to_owned()) - &tmp.constant)
24496        / &tmp.slope;
24497    let inverse_replaced = rubi_subst_expression(expr, &tmp.tmp, sub_atom);
24498    rubi_subst(&inverse_replaced, x, inverse_x)
24499}
24500
24501fn rubi_function_of_linear_q(expr: &Atom, x: Symbol) -> bool {
24502    rubi_function_of_linear_affine(expr, None, x, false).is_some_and(|affine| {
24503        affine.is_some_and(|(constant, slope)| !(constant.is_zero() && eqq!(slope, 1)))
24504    })
24505}
24506
24507// Port of Rubi's FunctionOfLinear[u,a,b,x,flag] state machine. The affine
24508// state is threaded through children; conflicting zero-constant slopes collapse
24509// to {0,1}, which the public FunctionOfLinear treats as False.
24510fn rubi_function_of_linear_affine(
24511    expr: &Atom,
24512    affine: Option<(Atom, Atom)>,
24513    x: Symbol,
24514    sum_flag: bool,
24515) -> Option<Option<(Atom, Atom)>> {
24516    if is_free_of(expr, x) {
24517        return Some(affine);
24518    }
24519
24520    if matches!(expr.as_view(), AtomView::Fun(function) if rubi_calculus_function_symbol(function.get_symbol()))
24521    {
24522        return None;
24523    }
24524
24525    if let Some((constant, slope)) = linear_coefficients(expr.as_view(), x) {
24526        if slope.is_zero() {
24527            return None;
24528        }
24529        let Some((affine_constant, affine_slope)) = affine else {
24530            return Some(Some((constant, slope)));
24531        };
24532        let common_factor = rubi_function_of_linear_common_slope_factor(&affine_slope, &slope);
24533        if constant.is_zero() && !sum_flag {
24534            return Some(Some((Atom::num(0), common_factor)));
24535        }
24536        if eqq!(&affine_slope * &constant - &affine_constant * &slope, 0) {
24537            let affine_slope_quotient = (&affine_slope / &common_factor).cancel();
24538            if affine_slope_quotient.is_zero() {
24539                return None;
24540            }
24541            return Some(Some((
24542                (&affine_constant / affine_slope_quotient).cancel(),
24543                common_factor,
24544            )));
24545        }
24546        return Some(Some((Atom::num(0), Atom::num(1))));
24547    }
24548
24549    if let AtomView::Pow(power) = expr.as_view() {
24550        let (base, exponent) = power.get_base_exp();
24551        if is_free_of(base, x) {
24552            let logarithmic_exponent = base.to_owned().log() * exponent.to_owned();
24553            return rubi_function_of_linear_affine(&logarithmic_exponent, affine, x, false);
24554        }
24555    }
24556
24557    if let AtomView::Mul(_) = expr.as_view()
24558        && rubi_product_monomial_factor_nonzero_q(expr, x)
24559    {
24560        return None;
24561    }
24562
24563    let mut current = affine;
24564    let child_sum_flag = matches!(expr.as_view(), AtomView::Add(_));
24565    for child in rubi_children(expr.as_view()) {
24566        current = rubi_function_of_linear_affine(&child, current, x, child_sum_flag)?;
24567    }
24568    Some(current)
24569}
24570
24571/// A function-of-linear decomposition and its transformed integrand.
24572struct RubiFunctionOfLinear {
24573    integrand: Atom,
24574    constant: Atom,
24575    slope: Atom,
24576}
24577
24578fn rubi_function_of_linear(expr: &Atom, x: Symbol, sub: Symbol) -> Option<RubiFunctionOfLinear> {
24579    let Some((constant, slope)) = rubi_function_of_linear_affine(expr, None, x, false)? else {
24580        return None;
24581    };
24582    if constant.is_zero() && eqq!(slope, 1) {
24583        return None;
24584    }
24585    let integrand = rubi_function_of_linear_subst(expr, &constant, &slope, x, sub);
24586    Some(RubiFunctionOfLinear {
24587        integrand,
24588        constant,
24589        slope,
24590    })
24591}
24592
24593fn rubi_function_of_linear_subst(
24594    expr: &Atom,
24595    constant: &Atom,
24596    slope: &Atom,
24597    x: Symbol,
24598    sub: Symbol,
24599) -> Atom {
24600    if is_free_of(expr.as_view(), x) {
24601        return expr.to_owned();
24602    }
24603
24604    if let Some((term_constant, term_slope)) = linear_coefficients(expr.as_view(), x)
24605        && !term_slope.is_zero()
24606    {
24607        let ratio = if term_slope == *slope {
24608            Atom::num(1)
24609        } else {
24610            &term_slope / slope
24611        };
24612        return term_constant - constant * &ratio + ratio * Atom::var(sub);
24613    }
24614
24615    if let AtomView::Pow(power) = expr.as_view() {
24616        let (base, exponent) = power.get_base_exp();
24617        if is_free_of(base, x) {
24618            let logarithmic_exponent = base.to_owned().log() * exponent.to_owned();
24619            return rubi_full_simplify(&rubi_function_of_linear_subst(
24620                &logarithmic_exponent,
24621                constant,
24622                slope,
24623                x,
24624                sub,
24625            ))
24626            .exp();
24627        }
24628    }
24629
24630    match expr.as_view() {
24631        AtomView::Add(add) => add
24632            .into_iter()
24633            .map(|term| rubi_function_of_linear_subst(&term.to_owned(), constant, slope, x, sub))
24634            .fold(Atom::num(0), |sum, term| sum + term),
24635        AtomView::Mul(mul) => mul
24636            .into_iter()
24637            .map(|factor| {
24638                rubi_function_of_linear_subst(&factor.to_owned(), constant, slope, x, sub)
24639            })
24640            .fold(Atom::num(1), |product, factor| product * factor),
24641        AtomView::Pow(power) => {
24642            rubi_function_of_linear_subst(&power.get_base().to_owned(), constant, slope, x, sub)
24643                .pow(rubi_function_of_linear_subst(
24644                    &power.get_exp().to_owned(),
24645                    constant,
24646                    slope,
24647                    x,
24648                    sub,
24649                ))
24650        }
24651        AtomView::Fun(function) => {
24652            function
24653                .get_symbol()
24654                .call_args(function.into_iter().map(|argument| {
24655                    rubi_function_of_linear_subst(&argument.to_owned(), constant, slope, x, sub)
24656                }))
24657        }
24658        AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
24659    }
24660}
24661
24662fn rubi_function_of_linear_common_slope_factor(left: &Atom, right: &Atom) -> Atom {
24663    if let (Some((left_numerator, left_denominator)), Some((right_numerator, right_denominator))) =
24664        (rational_number(left), rational_number(right))
24665    {
24666        let numerator_gcd = gcd_i128(left_numerator.abs().into(), right_numerator.abs().into());
24667        let denominator_lcm = integer_lcm_i128(
24668            left_denominator.abs().into(),
24669            right_denominator.abs().into(),
24670        );
24671        if numerator_gcd == 0 || denominator_lcm == 0 {
24672            return Atom::num(1);
24673        }
24674
24675        return Atom::num((numerator_gcd, denominator_lcm));
24676    }
24677
24678    if eqq!(left, right) || eqq!(left, -right) {
24679        return left.to_owned();
24680    }
24681
24682    Atom::num(1)
24683}
24684
24685fn integer_lcm_i128(left: i128, right: i128) -> i128 {
24686    if left == 0 || right == 0 {
24687        0
24688    } else {
24689        (left / gcd_i128(left.abs(), right.abs())) * right
24690    }
24691}
24692
24693fn rubi_product_monomial_factor_nonzero_q(expr: &Atom, x: Symbol) -> bool {
24694    let AtomView::Mul(mul) = expr.as_view() else {
24695        return false;
24696    };
24697
24698    for factor in mul {
24699        let factor = factor.to_owned();
24700        if let Some((_coefficient, exponent)) = rubi_monomial_coefficient_exponent(&factor, x)
24701            && !exponent.is_zero()
24702        {
24703            return true;
24704        }
24705    }
24706    false
24707}
24708
24709fn integer_part_atom(expr: &Atom) -> Option<Atom> {
24710    let (numerator, denominator) = rational_number(expr)?;
24711    Some(Atom::num(numerator.div_euclid(denominator)))
24712}
24713
24714fn is_number_less_than(expr: &Atom, threshold: i64) -> bool {
24715    rubi_numeric_rational(expr)
24716        .map(|(numerator, denominator)| numerator < threshold * denominator)
24717        .unwrap_or(false)
24718}
24719
24720fn is_number_less_or_equal(expr: &Atom, threshold: i64) -> bool {
24721    rubi_numeric_rational(expr)
24722        .map(|(numerator, denominator)| numerator <= threshold * denominator)
24723        .unwrap_or(false)
24724}
24725
24726fn is_number_less_than_atom(left: &Atom, right: &Atom) -> bool {
24727    match (rubi_numeric_rational(left), rubi_numeric_rational(right)) {
24728        (Some((left_numerator, left_denominator)), Some((right_numerator, right_denominator))) => {
24729            left_numerator * right_denominator < right_numerator * left_denominator
24730        }
24731        _ => false,
24732    }
24733}
24734
24735fn is_number_less_or_equal_atom(left: &Atom, right: &Atom) -> bool {
24736    match (rubi_numeric_rational(left), rubi_numeric_rational(right)) {
24737        (Some((left_numerator, left_denominator)), Some((right_numerator, right_denominator))) => {
24738            left_numerator * right_denominator <= right_numerator * left_denominator
24739        }
24740        _ => false,
24741    }
24742}
24743
24744fn is_number_greater_than(expr: &Atom, threshold: i64) -> bool {
24745    rubi_numeric_rational(expr)
24746        .map(|(numerator, denominator)| numerator > threshold * denominator)
24747        .unwrap_or(false)
24748}
24749
24750fn is_number_greater_than_atom(left: &Atom, right: &Atom) -> bool {
24751    match (rubi_numeric_rational(left), rubi_numeric_rational(right)) {
24752        (Some((left_numerator, left_denominator)), Some((right_numerator, right_denominator))) => {
24753            left_numerator * right_denominator > right_numerator * left_denominator
24754        }
24755        _ => false,
24756    }
24757}
24758
24759fn is_number_greater_or_equal(expr: &Atom, threshold: i64) -> bool {
24760    rubi_numeric_rational(expr)
24761        .map(|(numerator, denominator)| numerator >= threshold * denominator)
24762        .unwrap_or(false)
24763}
24764
24765fn is_number_greater_or_equal_atom(left: &Atom, right: &Atom) -> bool {
24766    match (rubi_numeric_rational(left), rubi_numeric_rational(right)) {
24767        (Some((left_numerator, left_denominator)), Some((right_numerator, right_denominator))) => {
24768            left_numerator * right_denominator >= right_numerator * left_denominator
24769        }
24770        _ => false,
24771    }
24772}
24773
24774fn rubi_numeric_rational(expr: &Atom) -> Option<(i64, i64)> {
24775    rational_number(expr).or_else(|| rational_number(&rubi_together_simplify(expr)))
24776}
24777
24778fn is_integer_less_than(expr: &Atom, threshold: i64) -> bool {
24779    integer_i64(expr)
24780        .map(|value| value < threshold)
24781        .unwrap_or(false)
24782}
24783
24784fn is_integer_less_or_equal(expr: &Atom, threshold: i64) -> bool {
24785    integer_i64(expr)
24786        .map(|value| value <= threshold)
24787        .unwrap_or(false)
24788}
24789
24790fn is_integer_greater_than(expr: &Atom, threshold: i64) -> bool {
24791    integer_i64(expr)
24792        .map(|value| value > threshold)
24793        .unwrap_or(false)
24794}
24795
24796/// Converts a translated Rubi bound argument to an integer when possible.
24797trait RubiIntegerBound {
24798    fn integer_bound(&self) -> Option<i64>;
24799}
24800
24801impl RubiIntegerBound for i64 {
24802    fn integer_bound(&self) -> Option<i64> {
24803        Some(*self)
24804    }
24805}
24806
24807impl RubiIntegerBound for Atom {
24808    fn integer_bound(&self) -> Option<i64> {
24809        integer_i64(self)
24810    }
24811}
24812
24813impl RubiIntegerBound for &Atom {
24814    fn integer_bound(&self) -> Option<i64> {
24815        integer_i64(self)
24816    }
24817}
24818
24819fn is_integer_greater_than_bound<T: RubiIntegerBound>(expr: &Atom, threshold: T) -> bool {
24820    threshold
24821        .integer_bound()
24822        .is_some_and(|threshold| is_integer_greater_than(expr, threshold))
24823}
24824
24825fn is_integer_less_than_bound<T: RubiIntegerBound>(expr: &Atom, threshold: T) -> bool {
24826    threshold
24827        .integer_bound()
24828        .is_some_and(|threshold| is_integer_less_than(expr, threshold))
24829}
24830
24831fn is_fraction_number(expr: &Atom) -> bool {
24832    rational_number(expr)
24833        .map(|(numerator, denominator)| denominator > 1 && numerator % denominator != 0)
24834        .unwrap_or(false)
24835}
24836
24837#[inline(never)]
24838fn integer_q(expr: &Atom) -> bool {
24839    integer_q_view(expr.as_view())
24840}
24841
24842#[inline(always)]
24843fn integer_q_view(expr: AtomView<'_>) -> bool {
24844    match expr {
24845        AtomView::Num(number) => {
24846            return number.get_coeff_view().is_integer();
24847        }
24848        AtomView::Var(_) | AtomView::Fun(_) => {
24849            return false;
24850        }
24851        _ => {}
24852    }
24853
24854    if contains_inexact_number(expr) {
24855        return false;
24856    }
24857
24858    // FIXME: very slow for complex patterns, that are almost guaranteed not to be integer
24859    integer_i64(&expr.expand().cancel()).is_some()
24860}
24861
24862fn contains_inexact_number(expr: AtomView<'_>) -> bool {
24863    match expr {
24864        AtomView::Num(number) => !matches!(
24865            number.get_coeff_view(),
24866            CoefficientView::Natural(_, _, 0, 1)
24867        ),
24868        AtomView::Add(add) => add.into_iter().any(contains_inexact_number),
24869        AtomView::Mul(mul) => mul.into_iter().any(contains_inexact_number),
24870        AtomView::Pow(power) => {
24871            contains_inexact_number(power.get_base()) || contains_inexact_number(power.get_exp())
24872        }
24873        AtomView::Fun(function) => function.into_iter().any(contains_inexact_number),
24874        AtomView::Var(_) => false,
24875    }
24876}
24877
24878fn int_binomial_q(n: &Atom, m: &Atom, p: &Atom) -> bool {
24879    is_integer_greater_than(p, 0)
24880        || rational_number(m).is_some() && integer_q(n) && integer_q(&(Atom::num(2) * p))
24881        || integer_q(&(((m + 1) / n) + p).expand().cancel())
24882        || (n == &Atom::num(2) || n == &Atom::num(4))
24883            && integer_q(&(Atom::num(2) * m))
24884            && integer_q(&(Atom::num(4) * p))
24885        || n == &Atom::num(2)
24886            && integer_q(&(Atom::num(6) * p))
24887            && (integer_q(m) || integer_q(&(m - p).expand().cancel()))
24888        || n == &Atom::num(3) && integer_q(m) && integer_q(&(((m + 1) / n) + p).expand().cancel())
24889}
24890
24891fn rubi_int_binomial_q(
24892    a: &Atom,
24893    b: &Atom,
24894    c: &Atom,
24895    n: &Atom,
24896    m: &Atom,
24897    p: &Atom,
24898    x: Symbol,
24899) -> bool {
24900    let _ = (a, b, c, x);
24901    int_binomial_q(n, m, p)
24902}
24903
24904fn integers_q(exprs: &[&Atom]) -> bool {
24905    exprs.iter().all(|expr| integer_q(expr))
24906}
24907
24908fn int_binomial_pair_q(
24909    a: &Atom,
24910    b: &Atom,
24911    c: &Atom,
24912    d: &Atom,
24913    n: &Atom,
24914    p: &Atom,
24915    q: &Atom,
24916) -> bool {
24917    integers_q(&[p, q])
24918        || igtq!(p, 0)
24919        || igtq!(q, 0)
24920        || (n == &Atom::num(2) || n == &Atom::num(4))
24921            && (integers_q(&[p, &(Atom::num(4) * q)]) || integers_q(&[&(Atom::num(4) * p), q]))
24922        || n == &Atom::num(2)
24923            && (integers_q(&[&(Atom::num(2) * p), &(Atom::num(2) * q)])
24924                || integers_q(&[&(Atom::num(3) * p), q]) && eqq!(b * c + Atom::num(3) * a * d, 0)
24925                || integers_q(&[p, &(Atom::num(3) * q)]) && eqq!(Atom::num(3) * b * c + a * d, 0))
24926        || n == &Atom::num(3)
24927            && (integers_q(&[&(p + Atom::num(1) / Atom::num(3)), q])
24928                || integers_q(&[&(q + Atom::num(1) / Atom::num(3)), p]))
24929        || n == &Atom::num(3)
24930            && (integers_q(&[&(p + Atom::num(2) / Atom::num(3)), q])
24931                || integers_q(&[&(q + Atom::num(2) / Atom::num(3)), p]))
24932            && eqq!(b * c + a * d, 0)
24933}
24934
24935fn rubi_int_binomial_pair_q(
24936    a: &Atom,
24937    b: &Atom,
24938    c: &Atom,
24939    d: &Atom,
24940    n: &Atom,
24941    p: &Atom,
24942    q: &Atom,
24943    x: Symbol,
24944) -> bool {
24945    let _ = x;
24946    int_binomial_pair_q(a, b, c, d, n, p, q)
24947}
24948
24949fn int_binomial_scaled_q(
24950    a: &Atom,
24951    b: &Atom,
24952    c: &Atom,
24953    d: &Atom,
24954    _e: &Atom,
24955    m: &Atom,
24956    n: &Atom,
24957    p: &Atom,
24958    q: &Atom,
24959) -> bool {
24960    integers_q(&[p, q])
24961        || igtq!(p, 0)
24962        || igtq!(q, 0)
24963        || n == &Atom::num(2)
24964            && (integers_q(&[m, &(Atom::num(2) * p), &(Atom::num(2) * q)])
24965                || integers_q(&[&(Atom::num(2) * m), p, &(Atom::num(2) * q)])
24966                || integers_q(&[&(Atom::num(2) * m), &(Atom::num(2) * p), q]))
24967        || n == &Atom::num(4)
24968            && (integers_q(&[m, p, &(Atom::num(2) * q)])
24969                || integers_q(&[m, &(Atom::num(2) * p), q]))
24970        || n == &Atom::num(2)
24971            && integers_q(&[&(m / Atom::num(2)), &(p + Atom::num(1) / Atom::num(3)), q])
24972            && (eqq!(b * c + Atom::num(3) * a * d, 0) || eqq!(b * c - Atom::num(9) * a * d, 0))
24973        || n == &Atom::num(2)
24974            && integers_q(&[&(m / Atom::num(2)), &(q + Atom::num(1) / Atom::num(3)), p])
24975            && (eqq!(a * d + Atom::num(3) * b * c, 0) || eqq!(a * d - Atom::num(9) * b * c, 0))
24976        || n == &Atom::num(3)
24977            && integers_q(&[
24978                &((m - Atom::num(1)) / Atom::num(3)),
24979                q,
24980                &(p - Atom::num(1) / Atom::num(2)),
24981            ])
24982            && (eqq!(b * c - Atom::num(4) * a * d, 0)
24983                || eqq!(b * c + Atom::num(8) * a * d, 0)
24984                || eqq!(
24985                    b.pow(2) * c.pow(2)
24986                        - Atom::num(20) * a * b * c * d
24987                        - Atom::num(8) * a.pow(2) * d.pow(2),
24988                    0
24989                ))
24990        || n == &Atom::num(3)
24991            && integers_q(&[
24992                &((m - Atom::num(1)) / Atom::num(3)),
24993                p,
24994                &(q - Atom::num(1) / Atom::num(2)),
24995            ])
24996            && (eqq!(Atom::num(4) * b * c - a * d, 0)
24997                || eqq!(Atom::num(8) * b * c + a * d, 0)
24998                || eqq!(
24999                    Atom::num(8) * b.pow(2) * c.pow(2) + Atom::num(20) * a * b * c * d
25000                        - a.pow(2) * d.pow(2),
25001                    0
25002                ))
25003        || n == &Atom::num(3)
25004            && (integers_q(&[m, q, &(Atom::num(3) * p)])
25005                || integers_q(&[m, p, &(Atom::num(3) * q)]))
25006            && eqq!(b * c + a * d, 0)
25007        || n == &Atom::num(3)
25008            && (integers_q(&[
25009                &((m + Atom::num(2)) / Atom::num(3)),
25010                &(p + Atom::num(2) / Atom::num(3)),
25011                q,
25012            ]) || integers_q(&[
25013                &((m + Atom::num(2)) / Atom::num(3)),
25014                &(q + Atom::num(2) / Atom::num(3)),
25015                p,
25016            ]))
25017        || n == &Atom::num(3)
25018            && (integers_q(&[&(m / Atom::num(3)), &(p + Atom::num(1) / Atom::num(3)), q])
25019                || integers_q(&[&(m / Atom::num(3)), &(q + Atom::num(1) / Atom::num(3)), p]))
25020}
25021
25022fn rubi_int_binomial_scaled_q(
25023    a: &Atom,
25024    b: &Atom,
25025    c: &Atom,
25026    d: &Atom,
25027    e: &Atom,
25028    m: &Atom,
25029    n: &Atom,
25030    p: &Atom,
25031    q: &Atom,
25032    x: Symbol,
25033) -> bool {
25034    let _ = x;
25035    int_binomial_scaled_q(a, b, c, d, e, m, n, p, q)
25036}
25037
25038fn scaled_integer_q(expr: &Atom, scale: i64) -> bool {
25039    rational_number(expr)
25040        .map(|(numerator, denominator)| numerator.saturating_mul(scale) % denominator == 0)
25041        .unwrap_or(false)
25042}
25043
25044fn integer_sum_q(left: &Atom, right: &Atom) -> bool {
25045    integer_i64(&(left + right).expand()).is_some()
25046}
25047
25048fn int_quadratic_q(a: &Atom, b: &Atom, c: &Atom, d: &Atom, e: &Atom, m: &Atom, p: &Atom) -> bool {
25049    if integer_q(p)
25050        || is_integer_greater_than(m, 0)
25051        || integer_q(&(Atom::num(2) * m)) && integer_q(&(Atom::num(2) * p))
25052        || integer_q(m) && integer_q(&(Atom::num(4) * p))
25053    {
25054        return true;
25055    }
25056
25057    let shifted_p = (p + Atom::num(1) / Atom::num(3)).expand();
25058    if !(integer_q(m) && integer_q(&shifted_p)) {
25059        return false;
25060    }
25061
25062    let eq1 = (c.pow(2) * d.pow(2) - b * c * d * e + b.pow(2) * e.pow(2)
25063        - Atom::num(3) * a * c * e.pow(2))
25064    .expand()
25065    .is_zero();
25066    let eq2 = (c.pow(2) * d.pow(2) - b * c * d * e - Atom::num(2) * b.pow(2) * e.pow(2)
25067        + Atom::num(9) * a * c * e.pow(2))
25068    .expand()
25069    .is_zero();
25070
25071    eq1 || eq2
25072}
25073
25074fn int_linear_q(first_exponent: &Atom, second_exponent: &Atom) -> bool {
25075    if is_integer_greater_than(first_exponent, 0)
25076        || is_integer_greater_than(second_exponent, 0)
25077        || scaled_integer_q(first_exponent, 3) && scaled_integer_q(second_exponent, 3)
25078        || scaled_integer_q(first_exponent, 4) && scaled_integer_q(second_exponent, 4)
25079        || scaled_integer_q(first_exponent, 2) && scaled_integer_q(second_exponent, 6)
25080        || scaled_integer_q(first_exponent, 6) && scaled_integer_q(second_exponent, 2)
25081    {
25082        return true;
25083    }
25084
25085    let exponent_sum = (first_exponent + second_exponent).expand();
25086    is_integer_less_than(&exponent_sum, -1) || integer_sum_q(first_exponent, second_exponent)
25087}
25088
25089fn rubi_sum_simpler(expr: &Atom, shift: i64) -> bool {
25090    let shift = Atom::num(shift);
25091    rubi_sum_simpler_q(expr, &shift)
25092}
25093
25094fn rubi_sum_simpler_q(expr: &Atom, shift: &Atom) -> bool {
25095    if rational_q(expr) && rational_q(shift) {
25096        return rubi_sum_simpler_rational(expr, &shift);
25097    }
25098
25099    rubi_sum_simpler_aux(&expr.expand(), &shift.expand())
25100}
25101
25102fn rubi_sum_simpler_rational(expr: &Atom, shift: &Atom) -> bool {
25103    let Some((shift_numerator, shift_denominator)) = rational_number(shift) else {
25104        return false;
25105    };
25106    if shift_numerator == 0 {
25107        return false;
25108    }
25109
25110    let Some((numerator, denominator)) = rational_number(expr) else {
25111        return false;
25112    };
25113    if shift_numerator > 0 {
25114        numerator < -denominator
25115    } else {
25116        numerator * shift_denominator >= -shift_numerator * denominator
25117    }
25118}
25119
25120#[allow(dead_code)]
25121fn rubi_sum_simpler_aux(expr: &Atom, shift: &Atom) -> bool {
25122    if matches!(shift.as_view(), AtomView::Add(_)) {
25123        return rubi_add_terms(shift)
25124            .into_iter()
25125            .all(|term| rational_q(&term) || rubi_sum_simpler_aux(expr, &term));
25126    }
25127
25128    if matches!(expr.as_view(), AtomView::Add(_)) {
25129        return rubi_add_terms(expr)
25130            .into_iter()
25131            .any(|term| rubi_sum_simpler_aux(&term, shift));
25132    }
25133
25134    if shift.is_zero() {
25135        return false;
25136    }
25137
25138    let (expr_numeric, expr_nonnumeric) = rubi_split_numeric_factor(expr);
25139    let (shift_numeric, shift_nonnumeric) = rubi_split_numeric_factor(shift);
25140    if expr_nonnumeric != shift_nonnumeric || shift_numeric == 0 {
25141        return false;
25142    }
25143
25144    let twice_ratio = &expr_numeric / &shift_numeric * Rational::from(2);
25145    twice_ratio < -1 || twice_ratio == -1 && expr_numeric < 0
25146}
25147
25148fn rubi_add_terms(expr: &Atom) -> Vec<Atom> {
25149    match expr.as_view() {
25150        AtomView::Add(add) => add.into_iter().map(|term| term.to_owned()).collect(),
25151        _ => vec![expr.to_owned()],
25152    }
25153}
25154
25155fn rubi_split_numeric_factor(expr: &Atom) -> (Rational, Atom) {
25156    if let Some(rational) = rational_number(expr) {
25157        return (Rational::from(rational), Atom::num(1));
25158    }
25159
25160    match expr.as_view() {
25161        AtomView::Mul(mul) => {
25162            let mut numeric = Rational::from(1);
25163            let mut nonnumeric = Atom::num(1);
25164            for factor in mul {
25165                let factor = factor.to_owned();
25166                if let Some(rational) = rational_number(&factor) {
25167                    numeric *= Rational::from(rational);
25168                } else {
25169                    nonnumeric *= factor;
25170                }
25171            }
25172            (numeric, nonnumeric)
25173        }
25174        AtomView::Pow(power) => {
25175            let (base, exponent) = power.get_base_exp();
25176            if let (Some((base_numerator, base_denominator)), Some((exp_numerator, _))) = (
25177                rational_number_view(base),
25178                rubi_fraction_parts(&exponent.to_owned()),
25179            ) {
25180                let numeric = if exp_numerator > 0 {
25181                    Rational::from((1, base_denominator))
25182                } else {
25183                    Rational::from((1, base_numerator.abs()))
25184                };
25185                return (numeric.to_owned(), expr / rational_atom(numeric));
25186            }
25187            (Rational::from(1), expr.to_owned())
25188        }
25189        _ => (Rational::from(1), expr.to_owned()),
25190    }
25191}
25192
25193fn gcd_i128(mut left: i128, mut right: i128) -> i128 {
25194    left = left.abs();
25195    right = right.abs();
25196    while right != 0 {
25197        let remainder = left % right;
25198        left = right;
25199        right = remainder;
25200    }
25201    left
25202}
25203
25204fn rational_atom(rational: impl Into<Rational>) -> Atom {
25205    let rational = rational.into();
25206    Atom::num(rational.numerator_ref().to_owned())
25207        / Atom::num(rational.denominator_ref().to_owned())
25208}
25209
25210fn binomial_i64(n: i64, k: i64) -> Option<i64> {
25211    if k < 0 || k > n {
25212        return None;
25213    }
25214
25215    let k = k.min(n - k);
25216    let mut result = 1_i64;
25217    for i in 1..=k {
25218        result = result.checked_mul(n - k + i)?.checked_div(i)?;
25219    }
25220    Some(result)
25221}
25222
25223#[cfg(test)]
25224mod tests {
25225    use super::*;
25226
25227    fn integrate(expr: &Atom, x: Symbol) -> Result<Atom, Atom> {
25228        super::integrate(expr.as_view(), x)
25229    }
25230
25231    fn assert_derivative_round_trip(integrand: Atom) {
25232        let x = symbol!("x");
25233        let primitive =
25234            integrate(&integrand, x).unwrap_or_else(|_| panic!("rule should apply to {integrand}"));
25235        assert!(
25236            !primitive.to_string().contains("unintegrable"),
25237            "row should not return unintegrable for {integrand}; primitive: {primitive}"
25238        );
25239        let residual = (primitive.derivative(x) - &integrand).together();
25240        let residual = rubi_normalize_product_log_exponentials(&residual);
25241        let residual = if residual_is_zero(&residual) {
25242            residual
25243        } else {
25244            residual.factor()
25245        };
25246        assert!(
25247            residual_is_zero(&residual),
25248            "derivative round trip failed for {integrand}; primitive: {primitive}; residual: {residual}"
25249        );
25250    }
25251
25252    fn assert_rubi_derivative_round_trip(integrand: Atom) {
25253        let x = symbol!("x");
25254        let primitive =
25255            integrate(&integrand, x).unwrap_or_else(|_| panic!("rule should apply to {integrand}"));
25256        let residual =
25257            (rubi_differentiate(&primitive, x) - rubi_normalize_atanh_logs(&integrand)).together();
25258        let residual = rubi_mathematica_simplify_trig_squares(&residual);
25259        assert!(
25260            residual_is_zero(&residual),
25261            "Rubi derivative round trip failed for {integrand}; primitive: {primitive}; residual: {residual}"
25262        );
25263    }
25264
25265    #[test]
25266    fn integrate_trait_supports_atom_core_types() {
25267        let x = symbol!("x");
25268        let integrand = parse!("x");
25269        let expected = super::integrate(integrand.as_view(), x);
25270
25271        assert_eq!(integrand.integrate(x), expected);
25272        assert_eq!(integrand.as_view().integrate(x), expected);
25273    }
25274
25275    #[test]
25276    fn integral_functions_extension_uses_registered_function_heads() {
25277        let x = parse!("x");
25278
25279        assert_eq!(x.fresnel_s(), parse!("symbolica_integrate::fresnel_s(x)"));
25280        assert_eq!(x.erfc(), parse!("symbolica_integrate::erfc(x)"));
25281        assert_eq!(
25282            x.exp_integral_e(parse!("n")),
25283            parse!("symbolica_integrate::exp_integral_e(n,x)")
25284        );
25285        assert_eq!(
25286            x.rubi_gamma(parse!("a")),
25287            parse!("symbolica_integrate::rubi_gamma(a,x)")
25288        );
25289        assert_eq!(
25290            x.hypergeometric_2f1(parse!("a"), parse!("b"), parse!("c")),
25291            parse!("symbolica_integrate::hypergeometric_2f1(a,b,c,x)")
25292        );
25293        assert_eq!(
25294            x.as_view().product_log(),
25295            parse!("symbolica_integrate::product_log(x)")
25296        );
25297        assert_eq!(x.factorial(), parse!("symbolica_integrate::Factorial(x)"));
25298    }
25299
25300    #[test]
25301    fn deferred_integrals_print_in_math_markup_modes() {
25302        let x = symbol!("x");
25303        let integral = rubi_symbols()
25304            .rubi_int
25305            .call((Atom::num(1) + Atom::var(x).pow(2), Atom::var(x)));
25306
25307        assert_eq!(format!("{integral}"), "∫ 1+x^2 dx");
25308        assert_eq!(
25309            format!("{}", integral.printer(PrintOptions::latex())),
25310            "\\int 1+x^{2}\\,\\mathrm{d}x"
25311        );
25312        assert_eq!(
25313            format!("{}", integral.printer(PrintOptions::typst())),
25314            "integral 1+x^2 dif x"
25315        );
25316
25317        let squared = integral.to_owned().pow(2);
25318        assert_eq!(
25319            format!("{}", squared.printer(PrintOptions::file_no_namespace())),
25320            "(∫ 1+x^2 dx)^2"
25321        );
25322        assert_eq!(
25323            format!("{}", squared.printer(PrintOptions::latex())),
25324            "\\left(\\int 1+x^{2}\\,\\mathrm{d}x\\right)^{2}"
25325        );
25326        assert_eq!(
25327            format!("{}", squared.printer(PrintOptions::typst())),
25328            "(integral 1+x^2 dif x)^2"
25329        );
25330
25331        let exponent = Atom::num(2).pow(integral);
25332        assert_eq!(
25333            format!("{}", exponent.printer(PrintOptions::file_no_namespace())),
25334            "2^(∫ 1+x^2 dx)"
25335        );
25336        assert_eq!(
25337            format!("{}", exponent.printer(PrintOptions::latex())),
25338            "2^{\\int 1+x^{2}\\,\\mathrm{d}x}"
25339        );
25340        assert_eq!(
25341            format!("{}", exponent.printer(PrintOptions::typst())),
25342            "2^(integral 1+x^2 dif x)"
25343        );
25344    }
25345
25346    #[cfg(all(feature = "steps", feature = "compressed-step-metadata"))]
25347    #[test]
25348    fn compressed_rule_text_catalog_matches_generated_literals() {
25349        let _ = symbol!("x");
25350        let mut catalog_rules = 0;
25351        for rule in rubi_rules() {
25352            let Some(order) = rule.downvalue_order else {
25353                // Extension rules retain inline text instead of catalog entries.
25354                continue;
25355            };
25356            let (source, description) =
25357                rubi_rule_text(order).expect("every main rule should have catalog text");
25358            assert_eq!(Some(source), rule.source_pattern, "source for rule {order}");
25359            assert_eq!(
25360                Some(description),
25361                rule.description,
25362                "description for rule {order}"
25363            );
25364            catalog_rules += 1;
25365        }
25366        assert_eq!(catalog_rules, RUBI_RULE_TEXT_RULE_COUNT);
25367    }
25368
25369    #[cfg(feature = "steps")]
25370    #[test]
25371    fn explanation_records_the_applied_rubi_transformation() {
25372        let x = symbol!("x");
25373        let integrand = parse!("x^2");
25374        let explanation = integrate_with_steps(integrand.as_view(), x);
25375        let primitive = explanation.result.expect("power rule should apply");
25376
25377        assert_eq!(
25378            (primitive.derivative(x) - &integrand).expand(),
25379            Atom::num(0)
25380        );
25381        let first = explanation
25382            .steps
25383            .first()
25384            .expect("an explained integration should record its rule");
25385        assert_eq!(
25386            first.input,
25387            rubi_symbols().rubi_int.call((integrand, Atom::var(x)))
25388        );
25389        assert!(first.source.contains("Int["));
25390        assert!(!first.description.is_empty());
25391        assert_ne!(first.output, Atom::num(0));
25392    }
25393
25394    #[cfg(feature = "steps")]
25395    #[test]
25396    fn deactivating_trig_reports_its_immediate_inert_integrand() {
25397        let x = symbol!("x");
25398        let integrand = parse!("x*sin(x)");
25399        let explanation = integrate_with_steps(integrand.as_view(), x);
25400        let first = explanation
25401            .steps
25402            .first()
25403            .expect("trigonometric preprocessing should be explained");
25404
25405        assert_eq!(first.rule, Some(3042));
25406        let expected_input = rubi_symbols().rubi_int.call((integrand, Atom::var(x)));
25407        let expected_inert_integral = rubi_symbols()
25408            .rubi_int
25409            .call((Atom::var(x) * i_sin(Atom::var(x)), Atom::var(x)));
25410        assert_eq!(first.depth, 0);
25411        assert_eq!(first.input, expected_input);
25412        assert_eq!(first.output, expected_inert_integral);
25413        assert_eq!(
25414            first.description,
25415            "Rewrite trigonometric functions to Rubi's inert form before integrating."
25416        );
25417
25418        let recurrence = explanation
25419            .steps
25420            .get(1)
25421            .expect("the inert sine product should use a recurrence");
25422        assert_eq!(recurrence.rule, Some(3777));
25423        assert_eq!(recurrence.depth, 1);
25424        assert_eq!(recurrence.input, first.output);
25425        assert_eq!(recurrence.output, parse!("-x*cos(x)+rubi_int(cos(x),x)"));
25426        assert_eq!(format!("{}", first.input), "∫ x*sin(x) dx");
25427        assert_eq!(format!("{}", recurrence.output), "-x*cos(x)+∫ cos(x) dx");
25428
25429        let levels: Vec<_> = explanation.steps.iter().map(|step| step.depth).collect();
25430        assert_eq!(levels, vec![0, 1, 2, 3]);
25431        let rendered = explanation.to_string();
25432        assert!(rendered.starts_with("∫ x*sin(x) dx = ∫ x*rubi_sin(x) dx\n  ∫"));
25433        assert!(rendered.ends_with("= -x*cos(x)+sin(x)"));
25434    }
25435
25436    #[cfg(feature = "steps")]
25437    #[test]
25438    fn int_sum_explanation_recurses_into_each_term() {
25439        let x = symbol!("x");
25440        let integrand = parse!("1-1/(1+x)");
25441        let explanation = integrate_with_steps(integrand.as_view(), x);
25442        let primitive = explanation
25443            .result
25444            .as_ref()
25445            .expect("the sum should be integrated");
25446
25447        assert_eq!(primitive, &parse!("x-log(1+x)"));
25448        let sum = explanation
25449            .steps
25450            .first()
25451            .expect("IntSum should produce an explanation step");
25452        assert_eq!(sum.rule, Some(2009));
25453        assert_eq!(sum.depth, 0);
25454        assert!(sum.output.to_string().contains('∫'));
25455        assert!(explanation.steps.iter().skip(1).any(|step| step.depth == 1));
25456        assert!(
25457            explanation
25458                .steps
25459                .iter()
25460                .all(|step| step.description != "Variable substitution"),
25461            "ordinary recursive integration must not report a substitution"
25462        );
25463    }
25464
25465    #[cfg(feature = "steps")]
25466    #[test]
25467    fn explanation_records_function_of_exponential_substitution() {
25468        let x = symbol!("x");
25469        let explanation = integrate_with_steps(parse!("exp(x)/(1+exp(x))").as_view(), x);
25470        let primitive = explanation
25471            .result
25472            .as_ref()
25473            .expect("the function-of-exponential substitution should integrate");
25474
25475        assert_eq!(primitive, &parse!("log(1+exp(x))"));
25476        let substitution = explanation
25477            .steps
25478            .iter()
25479            .find(|step| step.description == "Variable substitution")
25480            .expect("the explanation should state the fresh-variable substitution");
25481        assert_eq!(substitution.rule, None);
25482        assert_eq!(substitution.input, Atom::var(rubi_symbols().sub1));
25483        assert_eq!(substitution.output, parse!("exp(x)"));
25484        assert!(explanation.to_string().contains("sub1 ="));
25485        assert_eq!(explanation.steps[1].description, "Variable substitution");
25486    }
25487
25488    #[test]
25489    fn integrate_error_preserves_the_best_rubi_attempt() {
25490        let x = symbol!("x");
25491        let integrand = parse!("x+x^x");
25492        let attempt = integrate(&integrand, x).expect_err("x^x should remain unresolved");
25493
25494        assert_eq!(attempt, parse!("unintegrable(x^x,x)+1/2*x^2"));
25495    }
25496
25497    #[test]
25498    fn polynomial_q_does_not_apply_rubi_poly_q_together_fallback() {
25499        let x = symbol!("x");
25500        let disguised_polynomial = parse!("(x+x^2)/(1+x)");
25501
25502        assert!(rubi_poly_q(&disguised_polynomial, x));
25503        assert!(!rubi_polynomial_q(&disguised_polynomial, x));
25504    }
25505
25506    #[test]
25507    fn shared_section_4_through_8_predicates_follow_rubi_definitions() {
25508        let x = symbol!("x");
25509        let y = symbol!("y");
25510        let x_atom = Atom::var(x);
25511
25512        assert!(rubi_trig_q(&Atom::var(Symbol::SIN)));
25513        assert!(rubi_trig_q(&x_atom.cos()));
25514        assert!(!rubi_trig_q(&Atom::var(rubi_symbols().inert_sin)));
25515        assert!(!rubi_trig_q(&x_atom.sinh()));
25516
25517        let int_x = rubi_symbols()
25518            .rubi_int
25519            .call((x_atom.sin(), x_atom.to_owned()));
25520        let int_y = rubi_symbols().rubi_int.call((x_atom.sin(), Atom::var(y)));
25521        assert!(!rubi_calculus_free_q(&int_x, x));
25522        assert!(rubi_calculus_free_q(&int_y, x));
25523        assert!(!rubi_calculus_free_q(
25524            &symbol!("Hold").call((x_atom.to_owned(),)),
25525            x
25526        ));
25527
25528        assert!(igeq!(Atom::num(2), Atom::num(1)));
25529        assert!(!igeq!(Atom::num(1) / Atom::num(2), Atom::num(0)));
25530        assert!(rubi_independent_q(&parse!("a+b"), x));
25531        assert!(!rubi_independent_q(&parse!("a+b*x"), x));
25532    }
25533
25534    #[test]
25535    fn binomial_parts_accepts_x_free_noninteger_and_symbolic_exponents() {
25536        let x = symbol!("x");
25537
25538        let square_root = rubi_binomial_parts(parse!("sqrt(x)").as_view(), x)
25539            .expect("BinomialParts[x^(1/2),x] should return a list");
25540        assert_eq!(square_root.a, Atom::num(0));
25541        assert_eq!(square_root.b, Atom::num(1));
25542        assert_eq!(square_root.n, Atom::num(1) / Atom::num(2));
25543
25544        let symbolic = rubi_binomial_parts(parse!("a+b*x^m").as_view(), x)
25545            .expect("BinomialParts[a+b*x^m,x] should return a list");
25546        assert_eq!(symbolic.a, parse!("a"));
25547        assert_eq!(symbolic.b, parse!("b"));
25548        assert_eq!(symbolic.n, parse!("m"));
25549
25550        let product = rubi_binomial_parts(parse!("(1+x^m)*(1-x^m)").as_view(), x)
25551            .expect("the matching-exponent Product branch should combine binomials");
25552        assert_eq!(product.a, Atom::num(1));
25553        assert_eq!(product.b, Atom::num(-1));
25554        assert_eq!(product.n, Atom::num(2) * parse!("m"));
25555
25556        assert!(rubi_binomial_match_q(&parse!("a+b*x^m"), x));
25557        assert!(!rubi_binomial_match_q(&parse!("a+b*x^m+c*x^n"), x));
25558    }
25559
25560    #[test]
25561    fn inverse_function_of_linear_follows_rubi_scan_and_match_guards() {
25562        let x = symbol!("x");
25563        let witness = parse!("a^b*atan(x)");
25564
25565        assert!(rubi_has_free_base_power(witness.as_view(), x));
25566        assert!(
25567            rubi_inverse_linear_quadratic_match(
25568                &witness,
25569                &parse!("1+x^2"),
25570                x,
25571                RubiInverseKind::ArcTan,
25572            )
25573            .is_some()
25574        );
25575
25576        let earlier_other_inverse = symbol!("f").call((parse!("asin(x)"), parse!("atan(x)")));
25577        assert!(
25578            rubi_inverse_function_of_linear(&earlier_other_inverse, x, RubiInverseKind::ArcTan,)
25579                .is_none(),
25580            "Rubi returns the first inverse function and then rejects its head"
25581        );
25582
25583        let held_in_calculus = rubi_symbols()
25584            .rubi_int
25585            .call((parse!("atan(x)"), Atom::var(x)));
25586        assert!(
25587            rubi_inverse_function_of_linear(&held_in_calculus, x, RubiInverseKind::ArcTan)
25588                .is_none()
25589        );
25590    }
25591
25592    #[test]
25593    fn integrates_log_of_exponential_cosine_before_trig_deactivation() {
25594        let x = symbol!("x");
25595        let x_atom = Atom::var(x);
25596        let integrand = Atom::var(Symbol::E).pow(x_atom.cos()).log();
25597        let primitive = integrate(&integrand, x).expect("Rubi 3.5 log rule should apply first");
25598
25599        assert!(
25600            !primitive.to_string().contains("der("),
25601            "primitive should not contain a formal inert-trig derivative: {primitive}"
25602        );
25603        let residual = (primitive.derivative(x) - integrand).together();
25604        assert!(
25605            residual_is_zero(&residual),
25606            "derivative round trip failed; primitive: {primitive}; residual: {residual}"
25607        );
25608    }
25609
25610    #[test]
25611    fn smart_apart_preserves_repeated_complex_quadratic_equivalence() {
25612        let x = symbol!("x");
25613        let x_atom = Atom::var(x);
25614        let i = Atom::i();
25615        let integrand = (x_atom.to_owned() - &i).pow(-3) * (x_atom + i).pow(-3);
25616        let expanded = rubi_smart_apart(&integrand, x);
25617        let residual = (expanded.to_owned() - &integrand).together();
25618
25619        assert!(
25620            rubi_algebraic_zero_q(&residual),
25621            "SmartApart should preserve equivalence for Apostol Problems.input line 59; expanded: {expanded}; residual: {residual}"
25622        );
25623    }
25624
25625    #[test]
25626    fn smart_apart_uses_the_supplied_variable_for_symbolic_powers() {
25627        let x = symbol!("x");
25628        let integrand = parse!("(e*x)^m*(1+x^n)^2*(1+2*x^n)/(a+b*x^n)");
25629
25630        assert_eq!(
25631            rubi_smart_apart(&integrand, x),
25632            integrand,
25633            "Mathematica Apart[...,x] does not apart this expression in x^n"
25634        );
25635        assert!(
25636            rubi_sum_q(&rubi_expand_expression(&integrand, x)),
25637            "ExpandExpression should continue to its Expand[...,x] branch"
25638        );
25639    }
25640
25641    #[test]
25642    fn smart_apart_uses_mathematica_default_symbolic_power_kernel() {
25643        let x = symbol!("x");
25644        let integrand = parse!("1/((d+e*x^n)*(a+c*x^(2*n)))");
25645        let expected = parse!(
25646            "e^2/((c*d^2+a*e^2)*(d+e*x^n))\
25647             -c*(-d+e*x^n)/((c*d^2+a*e^2)*(a+c*x^(2*n)))"
25648        );
25649
25650        assert_eq!(
25651            rubi_smart_apart(&integrand, x),
25652            expected,
25653            "Mathematica Apart[] treats x^n as the rational kernel"
25654        );
25655        assert_eq!(rubi_expand_expression(&integrand, x), expected);
25656    }
25657
25658    #[test]
25659    fn symbolic_power_smart_apart_expands_polynomial_quotient_termwise() {
25660        let x = symbol!("x");
25661        let integrand = parse!("(c+d*x^n)^2*(A+B*x^n)/(a+b*x^n)");
25662        let expanded = rubi_smart_apart(&integrand, x);
25663
25664        assert_eq!(
25665            rubi_add_terms(&expanded).len(),
25666            4,
25667            "Mathematica Apart emits three polynomial-kernel terms and one proper fraction: {expanded}"
25668        );
25669        assert!(rubi_equivalent_q(&expanded, &integrand));
25670    }
25671
25672    #[test]
25673    fn integrates_general_trinomial_reciprocal_via_symbolic_power_smart_apart() {
25674        let x = symbol!("x");
25675        let primitive = integrate(&parse!("1/((d+e*x^n)*(a+c*x^(2*n)))"), x)
25676            .expect("Rubi DownValue 1755 should complete after ExpandIntegrand");
25677
25678        assert!(rubi_integral_free_q(&primitive));
25679        assert!(rubi_contains_function_symbol(
25680            &primitive,
25681            rubi_symbols().hypergeometric2f1
25682        ));
25683    }
25684
25685    #[test]
25686    fn mathematica_expand_in_variable_preserves_free_sum_coefficients() {
25687        let x = symbol!("x");
25688        let expression = parse!("(a+b)*(c+d*x)");
25689        let expected = parse!("c*(a+b)+d*(a+b)*x");
25690
25691        assert_eq!(
25692            rubi_mathematica_expand(&expression, Some(x)),
25693            expected,
25694            "Mathematica Expand[expr,x] does not expand sums that are free of x"
25695        );
25696
25697        let terms = collect_polynomial_terms(&expression, x)
25698            .expect("the expression should be polynomial in x");
25699        assert_eq!(terms.get(&0), Some(&parse!("c*(a+b)")));
25700        assert_eq!(terms.get(&1), Some(&parse!("d*(a+b)")));
25701    }
25702
25703    #[test]
25704    fn expand_integrand_defaults_bare_expand_binomial_power_to_one() {
25705        let x = symbol!("x");
25706        let integrand = parse!("x/(a+b*x^3)");
25707        let expanded = rubi_expand_integrand(&integrand, x);
25708
25709        assert!(rubi_sum_q(&expanded));
25710        assert!(rubi_equivalent_q(&expanded, &integrand));
25711    }
25712
25713    #[test]
25714    fn expand_integrand_positive_power_keeps_mathematica_denominator_shape() {
25715        let x = symbol!("x");
25716        let payload = parse!("(1/(1-x^4)+x^2/(1-x^4))^3");
25717        let expected = parse!(
25718            "1/(1-x^4)^3\
25719             +3*x^2/(1-x^4)^3\
25720             +3*x^4/(1-x^4)^3\
25721             +x^6/(1-x^4)^3"
25722        );
25723        let expanded = rubi_expand_integrand(&payload, x);
25724
25725        assert_eq!(
25726            expanded, expected,
25727            "ExpandIntegrand[u_^p,x] should follow Mathematica Expand[u^p,x]"
25728        );
25729    }
25730
25731    #[test]
25732    fn integrates_quartic_power_over_one_minus_x_squared_cubed() {
25733        let primitive = integrate(&parse!("(1+b*x^4)^p/(1-x^2)^3"), symbol!("x"))
25734            .expect("Rubi DownValues 1569, 2009, 936, and 1012 should integrate the case");
25735
25736        assert!(
25737            rubi_integral_free_q(&primitive),
25738            "Mathematica's four AppellF1 terms should contain no deferred integral: {primitive}"
25739        );
25740        assert!(
25741            rubi_contains_function_symbol(&primitive, rubi_symbols().appell_f1),
25742            "the traced Rubi result should contain AppellF1: {primitive}"
25743        );
25744    }
25745
25746    #[test]
25747    fn integrates_miscellaneous_254_via_nested_rational_function_expand() {
25748        let x = symbol!("x");
25749        let primitive = integrate(&parse!("x^4*(e+f*x)^n/(a+b*x^3)"), x)
25750            .expect("Rubi DownValue 7276 should expand the cubic rational factor");
25751
25752        assert!(rubi_integral_free_q(&primitive));
25753        assert!(rubi_contains_function_symbol(
25754            &primitive,
25755            rubi_symbols().hypergeometric2f1
25756        ));
25757    }
25758
25759    #[test]
25760    fn smart_apart_uses_dependent_logarithm_as_mathematica_default_kernel() {
25761        let x = symbol!("x");
25762        let integrand = parse!("x^2*(a+b*log(c*(d+e*x)^n))^2*(f+g*log(h*(i+j*x)^m))/(d+e*x)");
25763        let first_logarithm = parse!("a+b*log(c*(d+e*x)^n)");
25764        let second_logarithm = parse!("log(h*(i+j*x)^m)");
25765        let expected = parse!("f*x^2") * first_logarithm.pow(2) / parse!("d+e*x")
25766            + parse!("g*x^2") * first_logarithm.pow(2) * second_logarithm / parse!("d+e*x");
25767
25768        assert_eq!(rubi_smart_apart(&integrand, x), expected);
25769    }
25770
25771    #[test]
25772    fn expand_expression_retries_rational_factors_after_unchanged_logarithmic_smart_apart() {
25773        let x = symbol!("x");
25774        let integrand = parse!("x^2*(a+b*log(c*(d+e*x)^n))^2*log(h*(i+j*x)^m)/(d+e*x)");
25775        let nonrational = parse!("(a+b*log(c*(d+e*x)^n))^2*log(h*(i+j*x)^m)");
25776        let expected = -parse!("d/e^2") * &nonrational
25777            + parse!("x/e") * &nonrational
25778            + parse!("d^2/(e^2*(d+e*x))") * nonrational;
25779
25780        assert_eq!(rubi_smart_apart(&integrand, x), integrand);
25781        assert_eq!(rubi_expand_expression(&integrand, x), expected);
25782    }
25783
25784    #[test]
25785    fn smart_apart_matches_mathematica_for_dependent_trig_quotient() {
25786        let x = symbol!("x");
25787        let a = Atom::var(symbol!("a"));
25788        let b = Atom::var(symbol!("b"));
25789        let i = rubi_i();
25790        let angle = &i * Atom::var(x);
25791        let sin = i_sin(angle.to_owned());
25792        let cos = i_cos(angle);
25793        let denominator = &b * &cos - &i * &a * &sin;
25794        let integrand = &sin / (&cos * &denominator);
25795        let expected = &i / (&a * &cos) - &i * &b / (&a * denominator);
25796        let expanded = rubi_smart_apart(&integrand, x);
25797
25798        assert!(
25799            rubi_sum_q(&expanded),
25800            "Mathematica SmartApart splits the inert sine/cosine quotient: {expanded}"
25801        );
25802        assert!(
25803            eqq!(expanded, expected),
25804            "SmartApart should match Mathematica's dependent-kernel partial fractions"
25805        );
25806    }
25807
25808    #[test]
25809    fn smart_apart_does_not_apart_multiple_dependent_kernels_individually() {
25810        let x = symbol!("x");
25811        let a = Atom::var(symbol!("a"));
25812        let b = Atom::var(symbol!("b"));
25813        let i = rubi_i();
25814        let angle = &i * Atom::var(x);
25815        let sin = i_sin(angle.to_owned());
25816        let cos = i_cos(angle);
25817        let denominator = &a * &cos - &i * &b * &sin;
25818        let integrand = cos.pow(3) / denominator.pow(2);
25819
25820        assert_eq!(
25821            rubi_smart_apart(&integrand, x),
25822            integrand,
25823            "Mathematica SmartApart leaves this multi-kernel quotient unchanged"
25824        );
25825    }
25826
25827    #[test]
25828    fn integrates_apostol_59_cos_fourth_via_rubi_rules() {
25829        assert_derivative_round_trip(parse!("cos(x)^4"));
25830    }
25831
25832    fn matcher_rule_for_test(integrand: &Atom, x: Symbol, rule: &'static RubiRule) -> Option<Atom> {
25833        matcher_rule(integrand.as_view(), x, rule)
25834    }
25835
25836    #[test]
25837    fn executable_rubi_rules_are_registered_in_dispatch_order() {
25838        let _ = symbol!("x");
25839        let rules = rubi_rules();
25840        let dispatch_orders = rules
25841            .iter()
25842            .map(required_rubi_dispatch_order)
25843            .collect::<Vec<_>>();
25844        assert!(dispatch_orders.windows(2).all(|pair| pair[0] <= pair[1]));
25845
25846        let upstream_orders = rules
25847            .iter()
25848            .filter_map(|rule| rule.downvalue_order)
25849            .collect::<Vec<_>>();
25850        assert!(upstream_orders.windows(2).all(|pair| pair[0] <= pair[1]));
25851        assert_eq!(upstream_orders.first(), Some(&1));
25852        assert_eq!(upstream_orders.last(), Some(&7299));
25853    }
25854
25855    #[test]
25856    fn mathematica_evaluates_timofeev_664_trig_quotient_before_rubi() {
25857        let integrand = parse!("x*cos(x)^4/sin(x)^2");
25858        let evaluated = rubi_mathematica_evaluate_integrand(&integrand)
25859            .expect("Mathematica evaluates Cos[x]^4/Sin[x]^2 before Rubi rules see it");
25860
25861        assert_eq!(evaluated, parse!("x*cos(x)^2*cot(x)^2"));
25862    }
25863
25864    #[test]
25865    fn integrates_cancelled_quartic_constant_via_mathematica_rule_path() {
25866        let x = symbol!("x");
25867        let integrand = parse!("1/(x*sqrt(2+2*a-2*(1+a)+c*x^4))");
25868        let rule = rubi_rules()
25869            .iter()
25870            .find(|rule| rule.downvalue_order == Some(1))
25871            .expect("Rubi DownValue 1 should be ported");
25872        assert_eq!(
25873            rubi_rules().first().and_then(|rule| rule.downvalue_order),
25874            Some(1)
25875        );
25876        let primitive = integrate(&integrand, x)
25877            .expect("Rubi DownValue 1 should remove the cancelled binomial constant");
25878        assert!(
25879            rubi_algebraic_zero_q(&(primitive - parse!("-1/(2*sqrt(c*x^4))"))),
25880            "Rubi should reproduce Mathematica's primitive; first pattern: {}",
25881            rule.replacement.pat
25882        );
25883    }
25884
25885    #[test]
25886    fn integrates_misc_algebraic_root_denominators_via_rubi_2586() {
25887        for integrand in [
25888            "x^5/(a*c+b*c*x^2+d*sqrt(a+b*x^2))",
25889            "x^3/(a*c+b*c*x^2+d*sqrt(a+b*x^2))",
25890            "1/(x*(a*c+b*c*x^2+d*sqrt(a+b*x^2)))",
25891            "1/(x^3*(a*c+b*c*x^2+d*sqrt(a+b*x^2)))",
25892            "x^8/(a*c+b*c*x^3+d*sqrt(a+b*x^3))",
25893            "x^5/(a*c+b*c*x^3+d*sqrt(a+b*x^3))",
25894            "1/(x*(a*c+b*c*x^3+d*sqrt(a+b*x^3)))",
25895            "1/(x^4*(a*c+b*c*x^3+d*sqrt(a+b*x^3)))",
25896        ] {
25897            assert_derivative_round_trip(parse!(integrand));
25898        }
25899    }
25900
25901    #[test]
25902    fn integrates_timofeev_664_via_mathematica_trig_quotient() {
25903        assert_derivative_round_trip(parse!("x*cos(x)^4/sin(x)^2"));
25904    }
25905
25906    #[test]
25907    fn simp_preserves_high_integer_power_of_linear_base() {
25908        let x = symbol!("x");
25909        let expression = parse!("c*(d+e*x)^24");
25910
25911        assert_eq!(rubi_simp(&expression, x), expression);
25912    }
25913
25914    #[test]
25915    fn smart_simplify_uses_rubi_timeout_fallback_for_large_multivariate_factorization() {
25916        let expression = parse!(
25917            "(-a*d+b*c*(1+m))*(b*c*(1-m)*(B*c*d-A*d^2-C*c^2)\
25918             -2*d*(a*d-b*c)*(B*c-A*d+C*d))\
25919             +(A*(b*d^2*(1-m)-2*c*(a*d-b*c))\
25920             -(B*d-C*c)*(-m*b*c+2*a*d-b*c))\
25921             *(-m*b*d^2-c*(a*d-b*c))"
25922        );
25923
25924        assert_eq!(rubi_smart_simplify(&expression), expression);
25925    }
25926
25927    #[test]
25928    fn simp_preserves_secant_quadratic_coefficient_groups() {
25929        let x = symbol!("x");
25930        let sec = parse!("sec(c+d*x)");
25931        let expression = -3 * parse!("b*(A*b^2+a^2*C)")
25932            + parse!("a*(2*A*b^2-C*a^2+3*C*b^2)") * &sec
25933            + 3 * parse!("C*b*(a+b)*(a-b)") * sec.pow(2);
25934        let simplified = rubi_simp(&expression, x);
25935
25936        assert_eq!(
25937            rubi_add_terms(&simplified).len(),
25938            3,
25939            "Mathematica Simp keeps the free constant coefficient grouped: {simplified}"
25940        );
25941    }
25942
25943    #[test]
25944    fn factor_numeric_gcd_matches_rubi_recursive_definition() {
25945        assert_eq!(
25946            rubi_factor_numeric_gcd(&parse!("6*a+9*b")),
25947            parse!("3*(2*a+3*b)")
25948        );
25949        assert_eq!(
25950            rubi_factor_numeric_gcd(&parse!("2/3*a+4/9*b")),
25951            parse!("2/9*(3*a+2*b)")
25952        );
25953        assert_eq!(
25954            rubi_factor_numeric_gcd(&parse!("z*(6*a+9*b)")),
25955            parse!("3*z*(2*a+3*b)")
25956        );
25957        assert_eq!(
25958            rubi_factor_numeric_gcd(&parse!("(6*a+9*b)^(3/2)")),
25959            parse!("(3*(2*a+3*b))^(3/2)")
25960        );
25961    }
25962
25963    #[test]
25964    fn int_term_recovers_linear_power_from_expanded_rational_denominator() {
25965        let x = symbol!("x");
25966        let term = parse!("b^4/((a+b*x)*(a*d-b*c)*(a*g-b*f)^3)");
25967        let primitive = rubi_int_term(&term, x)
25968            .unwrap_or_else(|| panic!("Rubi IntTerm should recognize c*(a+b*x)^-1: {term}"));
25969
25970        assert!(
25971            primitive.to_string().contains("log"),
25972            "Rubi IntTerm m == -1 branch should produce a logarithm: {primitive}"
25973        );
25974        assert_derivative_round_trip(term);
25975    }
25976
25977    #[test]
25978    fn int_sum_uses_int_term_free_factors_before_additive_fraction_split() {
25979        let x = symbol!("x");
25980        let expanded_sum = parse!(
25981            "(a+b*log(c*x^n))/e^2 + d^2*(a+b*log(c*x^n))/(e^2*(d+e*x^2)^2) - 2*d*(a+b*log(c*x^n))/(e^2*(d+e*x^2))"
25982        );
25983        let primitive = rubi_int_sum(&expanded_sum, x)
25984            .unwrap_or_else(|| panic!("IntSum should integrate traced Rubi 3.1.4 payload"));
25985
25986        assert!(
25987            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
25988            "IntSum should keep denominator-square log terms source-shaped for downstream Rubi rows: {primitive}"
25989        );
25990    }
25991
25992    fn residual_is_zero(residual: &Atom) -> bool {
25993        let residual = normalize_pi_half_trig_for_verification(residual).together();
25994        if residual.is_zero() || !matches!(residual.zero_test(8, 1e-10), ConditionResult::False) {
25995            return true;
25996        }
25997
25998        let mut normalized = residual.to_owned();
25999        for _ in 0..3 {
26000            normalized = normalize_pi_half_trig_for_verification(
26001                &expand_reciprocals_for_verification(&normalized),
26002            )
26003            .together();
26004            if normalized.is_zero()
26005                || !matches!(normalized.zero_test(8, 1e-10), ConditionResult::False)
26006            {
26007                return true;
26008            }
26009        }
26010
26011        false
26012    }
26013
26014    #[test]
26015    fn expand_integrand_product_matches_rubi_moses_124_trace() {
26016        let x = symbol!("x");
26017        let exponential = parse!("e^(x^2)");
26018        let rational = parse!("(1+4*x^2+x^3+5*x^4+2*x^6)/(1+x^2)^2");
26019        let expanded = rubi_expand_integrand_product(&exponential, &rational, x);
26020        let expected = parse!("e^(x^2) + 2*x^2*e^(x^2) - x*e^(x^2)/(1+x^2)^2 + x*e^(x^2)/(1+x^2)");
26021
26022        assert_eq!(
26023            rubi_add_terms(&expanded).len(),
26024            4,
26025            "Rubi trace for Moses Problems.input:124 keeps four expanded terms; got {expanded}"
26026        );
26027        assert!(
26028            residual_is_zero(&(expanded - expected)),
26029            "ExpandIntegrand[u,v,x] should follow the Rubi trace for Moses Problems.input:124"
26030        );
26031    }
26032
26033    #[test]
26034    fn expand_integrand_protects_inverse_function_power_when_expanding_linear_multiplier() {
26035        let x = symbol!("x");
26036        let integrand = parse!("(d+c*d*x)*(a+b*asin(c*x))^2");
26037        let expanded = rubi_expand_integrand(&integrand, x);
26038        let expected = parse!("d*(a+b*asin(c*x))^2+c*d*x*(a+b*asin(c*x))^2");
26039
26040        assert_eq!(
26041            rubi_add_terms(&expanded).len(),
26042            2,
26043            "Rubi keeps the inverse-function power intact while distributing the polynomial multiplier: {expanded}"
26044        );
26045        assert!(
26046            residual_is_zero(&(expanded - expected)),
26047            "expanded inverse-function product should match Rubi's ExpandIntegrand trace"
26048        );
26049    }
26050
26051    fn normalize_pi_half_trig_for_verification(expr: &Atom) -> Atom {
26052        match expr.as_view() {
26053            AtomView::Fun(function)
26054                if function.get_nargs() == 1
26055                    && rubi_inert_or_builtin_trig_symbol_q(function.get_symbol()) =>
26056            {
26057                let argument = normalize_pi_half_trig_for_verification(&function.get(0).to_owned());
26058                if let Some((base, shift)) = pi_half_shift_base_for_verification(&argument) {
26059                    return trig_pi_half_shift_for_verification(function.get_symbol(), base, shift);
26060                }
26061                function.get_symbol().call((argument,))
26062            }
26063            AtomView::Fun(function) => {
26064                let args: Vec<_> = function
26065                    .into_iter()
26066                    .map(|argument| normalize_pi_half_trig_for_verification(&argument.to_owned()))
26067                    .collect();
26068                function.get_symbol().call_args(args)
26069            }
26070            AtomView::Add(add) => add
26071                .into_iter()
26072                .map(|term| normalize_pi_half_trig_for_verification(&term.to_owned()))
26073                .fold(Atom::num(0), |sum, term| sum + term),
26074            AtomView::Mul(mul) => mul
26075                .into_iter()
26076                .map(|factor| normalize_pi_half_trig_for_verification(&factor.to_owned()))
26077                .fold(Atom::num(1), |product, factor| product * factor),
26078            AtomView::Pow(power) => {
26079                normalize_pi_half_trig_for_verification(&power.get_base().to_owned()).pow(
26080                    normalize_pi_half_trig_for_verification(&power.get_exp().to_owned()),
26081                )
26082            }
26083            AtomView::Num(_) | AtomView::Var(_) => expr.to_owned(),
26084        }
26085    }
26086
26087    fn pi_half_shift_base_for_verification(argument: &Atom) -> Option<(Atom, i8)> {
26088        let pi = Atom::var(Symbol::PI);
26089        let pi_over_two = Atom::var(Symbol::PI) / 2;
26090        match argument.as_view() {
26091            AtomView::Add(add) => {
26092                for term in add {
26093                    let term = term.to_owned();
26094                    if eqq!(term, pi) {
26095                        return Some(((argument - &term).expand(), 2));
26096                    }
26097                    if eqq!(term, -&pi) {
26098                        return Some(((argument - &term).expand(), -2));
26099                    }
26100                    if eqq!(term, pi_over_two) {
26101                        return Some(((argument - &term).expand(), 1));
26102                    }
26103                    if eqq!(term, -&pi_over_two) {
26104                        return Some(((argument - &term).expand(), -1));
26105                    }
26106                }
26107                None
26108            }
26109            _ => None,
26110        }
26111    }
26112
26113    fn trig_pi_half_shift_for_verification(symbol: Symbol, base: Atom, shift: i8) -> Atom {
26114        match (symbol, shift) {
26115            (s, 1) if s == Symbol::SIN => base.cos(),
26116            (s, -1) if s == Symbol::SIN => -base.cos(),
26117            (s, 2 | -2) if s == Symbol::SIN => -base.sin(),
26118            (s, 1) if s == Symbol::COS => -base.sin(),
26119            (s, -1) if s == Symbol::COS => base.sin(),
26120            (s, 2 | -2) if s == Symbol::COS => -base.cos(),
26121            (s, 2 | -2) if s == symbolica::transcendental::tan() => base.tan(),
26122            (s, 2 | -2) if s == symbolica::transcendental::cot() => base.cot(),
26123            (s, _) if s == symbolica::transcendental::tan() => -base.cot(),
26124            (s, _) if s == symbolica::transcendental::cot() => -base.tan(),
26125            (s, 1) if s == symbolica::transcendental::sec() => -base.csc(),
26126            (s, -1) if s == symbolica::transcendental::sec() => base.csc(),
26127            (s, 2 | -2) if s == symbolica::transcendental::sec() => -base.sec(),
26128            (s, 1) if s == symbolica::transcendental::csc() => base.sec(),
26129            (s, -1) if s == symbolica::transcendental::csc() => -base.sec(),
26130            (s, 2 | -2) if s == symbolica::transcendental::csc() => -base.csc(),
26131            _ => symbol.call((base,)),
26132        }
26133    }
26134
26135    fn downvalue_primitive(order: u16, integrand: &Atom, x: Symbol) -> Atom {
26136        let rule = rubi_rules()
26137            .iter()
26138            .find(|rule| rule.downvalue_order == Some(order))
26139            .unwrap_or_else(|| panic!("Rubi DownValue {order} should exist"));
26140        matcher_rule_for_test(integrand, x, rule)
26141            .unwrap_or_else(|| panic!("Rubi DownValue {order} should apply to {integrand}"))
26142    }
26143
26144    fn assert_integrand_produces_primitive(integrand: &str) {
26145        let x = symbol!("x");
26146        let integrand = parse!(integrand);
26147        let primitive = integrate(&integrand, x)
26148            .unwrap_or_else(|_| panic!("Rubi rules should apply to {integrand}"));
26149        assert!(
26150            !primitive.to_string().contains("unintegrable"),
26151            "Rubi rules should not return unintegrable for {integrand}; primitive: {primitive}"
26152        );
26153    }
26154
26155    fn expand_reciprocals_for_verification(residual: &Atom) -> Atom {
26156        let argument = symbol!("verify_argument_");
26157        let argument_atom = Atom::var(argument);
26158        let tangent = argument_atom.tan().to_pattern();
26159        let cotangent = argument_atom.cot().to_pattern();
26160        let secant = argument_atom.sec().to_pattern();
26161        let cosecant = argument_atom.csc().to_pattern();
26162        let hyperbolic_tangent_square = argument_atom.tanh().pow(2).to_pattern();
26163        let hyperbolic_cotangent_square = argument_atom.coth().pow(2).to_pattern();
26164        let hyperbolic_tangent = argument_atom.tanh().to_pattern();
26165        let hyperbolic_cotangent = argument_atom.coth().to_pattern();
26166        let hyperbolic_secant = argument_atom.sech().to_pattern();
26167        let hyperbolic_cosecant = argument_atom.csch().to_pattern();
26168        let hyperbolic_cosine_square = argument_atom.cosh().pow(2).to_pattern();
26169        let hyperbolic_cosine_cube = argument_atom.cosh().pow(3).to_pattern();
26170
26171        let without_hyperbolic_tangent_square = residual
26172            .replace(&hyperbolic_tangent_square)
26173            .repeat()
26174            .with_map(move |matches| {
26175                let argument = matches
26176                    .get(argument)
26177                    .expect("hyperbolic tangent square pattern binds its argument")
26178                    .to_atom();
26179                Atom::num(1) - argument.sech().pow(2)
26180            });
26181        let without_hyperbolic_cotangent_square = without_hyperbolic_tangent_square
26182            .replace(&hyperbolic_cotangent_square)
26183            .repeat()
26184            .with_map(move |matches| {
26185                let argument = matches
26186                    .get(argument)
26187                    .expect("hyperbolic cotangent square pattern binds its argument")
26188                    .to_atom();
26189                Atom::num(1) + argument.csch().pow(2)
26190            });
26191
26192        let without_tangent = without_hyperbolic_cotangent_square
26193            .replace(&tangent)
26194            .repeat()
26195            .with_map(move |matches| {
26196                let argument = matches
26197                    .get(argument)
26198                    .expect("tangent pattern binds its argument")
26199                    .to_atom();
26200                argument.sin() / argument.cos()
26201            });
26202        let without_cotangent =
26203            without_tangent
26204                .replace(&cotangent)
26205                .repeat()
26206                .with_map(move |matches| {
26207                    let argument = matches
26208                        .get(argument)
26209                        .expect("cotangent pattern binds its argument")
26210                        .to_atom();
26211                    argument.cos() / argument.sin()
26212                });
26213        let without_secant = without_cotangent
26214            .replace(&secant)
26215            .repeat()
26216            .with_map(move |matches| {
26217                let argument = matches
26218                    .get(argument)
26219                    .expect("secant pattern binds its argument")
26220                    .to_atom();
26221                Atom::num(1) / argument.cos()
26222            });
26223
26224        let without_cosecant =
26225            without_secant
26226                .replace(&cosecant)
26227                .repeat()
26228                .with_map(move |matches| {
26229                    let argument = matches
26230                        .get(argument)
26231                        .expect("cosecant pattern binds its argument")
26232                        .to_atom();
26233                    Atom::num(1) / argument.sin()
26234                });
26235
26236        let without_hyperbolic_tangent = without_cosecant
26237            .replace(&hyperbolic_tangent)
26238            .repeat()
26239            .with_map(move |matches| {
26240                let argument = matches
26241                    .get(argument)
26242                    .expect("hyperbolic tangent pattern binds its argument")
26243                    .to_atom();
26244                argument.sinh() / argument.cosh()
26245            });
26246        let without_hyperbolic_cotangent = without_hyperbolic_tangent
26247            .replace(&hyperbolic_cotangent)
26248            .repeat()
26249            .with_map(move |matches| {
26250                let argument = matches
26251                    .get(argument)
26252                    .expect("hyperbolic cotangent pattern binds its argument")
26253                    .to_atom();
26254                argument.cosh() / argument.sinh()
26255            });
26256        let without_hyperbolic_secant = without_hyperbolic_cotangent
26257            .replace(&hyperbolic_secant)
26258            .repeat()
26259            .with_map(move |matches| {
26260                let argument = matches
26261                    .get(argument)
26262                    .expect("hyperbolic secant pattern binds its argument")
26263                    .to_atom();
26264                Atom::num(1) / argument.cosh()
26265            });
26266
26267        let without_hyperbolic_cosecant = without_hyperbolic_secant
26268            .replace(&hyperbolic_cosecant)
26269            .repeat()
26270            .with_map(move |matches| {
26271                let argument = matches
26272                    .get(argument)
26273                    .expect("hyperbolic cosecant pattern binds its argument")
26274                    .to_atom();
26275                Atom::num(1) / argument.sinh()
26276            });
26277
26278        let without_hyperbolic_cosine_square = without_hyperbolic_cosecant
26279            .replace(&hyperbolic_cosine_square)
26280            .repeat()
26281            .with_map(move |matches| {
26282                let argument = matches
26283                    .get(argument)
26284                    .expect("hyperbolic cosine square pattern binds its argument")
26285                    .to_atom();
26286                Atom::num(1) + argument.sinh().pow(2)
26287            });
26288
26289        without_hyperbolic_cosine_square
26290            .replace(&hyperbolic_cosine_cube)
26291            .repeat()
26292            .with_map(move |matches| {
26293                let argument = matches
26294                    .get(argument)
26295                    .expect("hyperbolic cosine cube pattern binds its argument")
26296                    .to_atom();
26297                argument.cosh() * (Atom::num(1) + argument.sinh().pow(2))
26298            })
26299    }
26300
26301    #[test]
26302    fn integrates_core_rules_through_matcher() {
26303        assert_derivative_round_trip(parse!("3"));
26304        assert_derivative_round_trip(parse!("x"));
26305        assert_derivative_round_trip(parse!("x^3"));
26306        assert_derivative_round_trip(parse!("x^n"));
26307        assert_derivative_round_trip(parse!("(3*x)^n"));
26308        assert_derivative_round_trip(parse!("x^-1"));
26309        assert_derivative_round_trip(parse!("1/(2*x)"));
26310        assert_derivative_round_trip(parse!("2*x^3"));
26311        assert_derivative_round_trip(parse!("b^5*x^5*(c+d*x)^(1/2)"));
26312        assert_derivative_round_trip(parse!("x + x^2"));
26313    }
26314
26315    #[test]
26316    fn integrates_rubi_4_1_11_18_normalized_linear_trig_products() {
26317        assert_derivative_round_trip(parse!("2*x*sin(x)"));
26318        assert_derivative_round_trip(parse!("2*x*cos(x)"));
26319        assert_derivative_round_trip(parse!("a*x^3*sin(c+d*x)"));
26320        assert_derivative_round_trip(parse!("a*x^2*cos(c+d*x)"));
26321    }
26322
26323    #[test]
26324    fn integrates_apostol_39_through_rubi_sine_recurrence() {
26325        assert_derivative_round_trip(parse!("x^3*cos(x)"));
26326    }
26327
26328    #[test]
26329    fn integrates_sine_square_via_rubi_inert_recurrence_path() {
26330        assert_derivative_round_trip(parse!("sin(x)^2"));
26331    }
26332
26333    #[test]
26334    fn integrates_mixed_linear_sin_cos_product_via_expand_trig_reduce() {
26335        let x = symbol!("x");
26336        let integrand = parse!("cos(x)*sin(a+x)");
26337        let reduced = rubi_expand_trig_reduce_one(&integrand, x);
26338        let expected_reduction = parse!("1/2*sin(a)+1/2*sin(a+2*x)");
26339        let reduction_difference = (reduced - expected_reduction).expand().cancel();
26340
26341        assert!(
26342            residual_is_zero(&reduction_difference),
26343            "ExpandTrigReduce should match Mathematica's product-to-sum path: {reduction_difference}"
26344        );
26345        let generated_x = Symbol::parse("x", "rubi_generated").unwrap();
26346        let generated_shape =
26347            Atom::parse("sin(x+a)*cos(x)", "rubi_generated", Default::default()).unwrap();
26348        let generated_reduced =
26349            rubi_expand_trig_reduce_one(&rubi_activate_trig(&generated_shape), generated_x);
26350        let generated_expected = Atom::parse(
26351            "1/2*sin(a)+1/2*sin(a+2*x)",
26352            "rubi_generated",
26353            Default::default(),
26354        )
26355        .unwrap();
26356        let generated_difference = (generated_reduced - generated_expected).expand().cancel();
26357        assert!(
26358            residual_is_zero(&generated_difference),
26359            "ActivateTrig should canonicalize wildcard trig heads before ExpandTrigReduce: {generated_difference}"
26360        );
26361        assert_derivative_round_trip(integrand);
26362    }
26363
26364    #[test]
26365    fn three_argument_expand_trig_expands_multiplier_before_distribution() {
26366        let x = symbol!("x");
26367        let u = parse!("cos(x)^(-2)");
26368        let v = parse!("sin(x)^(-3)/(a+b*sin(x))");
26369        let expanded = rubi_expand_trig_product(&u, &v, x);
26370
26371        assert!(
26372            rubi_sum_q(&expanded),
26373            "ExpandTrig[u,v,x] should distribute u over ExpandTrig[v,x]: {expanded}"
26374        );
26375        assert!(
26376            rubi_equivalent_q(&expanded, &(u * v)),
26377            "ExpandTrig[u,v,x] must preserve the input product: {expanded}"
26378        );
26379    }
26380
26381    #[test]
26382    fn rubi_simp_collapses_equal_power_conjugate_root_product() {
26383        let input = parse!("1/((1+sqrt(1+x^2))^2*(1-sqrt(1+x^2))^2)");
26384        let simplified = rubi_simp(&input, symbol!("x"));
26385
26386        assert_eq!(simplified, parse!("x^(-4)"), "got {simplified}");
26387    }
26388
26389    #[test]
26390    fn expand_trig_reduce_matches_mathematica_product_to_sum_family() {
26391        let x = symbol!("x");
26392        for (input, expected) in [
26393            ("sin(x+a)*sin(x)", "1/2*cos(a)-1/2*cos(a+2*x)"),
26394            ("cos(x+a)*cos(x)", "1/2*cos(a)+1/2*cos(a+2*x)"),
26395            ("sin(x+a)*cos(x+b)", "1/2*sin(a-b)+1/2*sin(a+b+2*x)"),
26396            (
26397                "sin(x+a)*cos(x)*cos(2*x)",
26398                "1/4*sin(a)+1/4*sin(a-2*x)+1/4*sin(a+2*x)+1/4*sin(a+4*x)",
26399            ),
26400            (
26401                "cosh(x)*cosh(2*x)*cosh(3*x)",
26402                "1/4+1/4*cosh(2*x)+1/4*cosh(4*x)+1/4*cosh(6*x)",
26403            ),
26404            ("sinh(x)^3", "1/4*sinh(3*x)-3/4*sinh(x)"),
26405            ("cosh(x)^3", "1/4*cosh(3*x)+3/4*cosh(x)"),
26406            ("sinh(x)^4", "3/8-1/2*cosh(2*x)+1/8*cosh(4*x)"),
26407        ] {
26408            let reduced = rubi_expand_trig_reduce_one(&parse!(input), x);
26409            let difference = (reduced - parse!(expected)).expand().cancel();
26410            assert!(
26411                residual_is_zero(&difference),
26412                "ExpandTrigReduce mismatch for {input}: {difference}"
26413            );
26414        }
26415    }
26416
26417    #[test]
26418    fn integrates_timofeev_799_hyperbolic_product_via_expand_trig_reduce() {
26419        let x = symbol!("x");
26420        let primitive = integrate(&parse!("cosh(x)*cosh(2*x)*cosh(3*x)"), x)
26421            .expect("Rubi should integrate hyperbolic products via ExpandTrigReduce");
26422        let expected = parse!("x/4+sinh(2*x)/8+sinh(4*x)/16+sinh(6*x)/24");
26423        let difference = (primitive - expected).expand().cancel();
26424
26425        assert!(
26426            residual_is_zero(&difference),
26427            "primitive should follow Rubi's hyperbolic product-to-sum path: {difference}"
26428        );
26429    }
26430
26431    #[test]
26432    fn integrates_bondarenko_42_arctangent_tangent_via_rubi_polylog_path() {
26433        assert_derivative_round_trip(parse!("atan(2*tan(x))"));
26434    }
26435
26436    #[test]
26437    fn integrates_polynomial_tangent_power_via_rubi_polylog_path() {
26438        let primitive = integrate(&parse!("x^3*tan(x)^4"), symbol!("x"))
26439            .expect("Rubi should integrate polynomial tangent powers");
26440        let text = primitive.to_string();
26441
26442        assert!(
26443            text.contains("polylog"),
26444            "expected Rubi tangent recurrence to reach the polylog path: {primitive}"
26445        );
26446        assert!(
26447            !text.contains("product_log"),
26448            "tangent recurrence should not fall through to ProductLog: {primitive}"
26449        );
26450    }
26451
26452    #[test]
26453    fn integrates_apostol_82_fractional_power_sine_like_rubi() {
26454        assert_derivative_round_trip(parse!("sin((-1+x)^(1/4))"));
26455    }
26456
26457    #[test]
26458    fn integrates_rubi_4_7_5_34_half_angle_payload_simplified() {
26459        assert_derivative_round_trip(parse!("1/(sin(x)+cos(x))"));
26460    }
26461
26462    #[test]
26463    fn deactivates_timofeev_564_like_mathematica_input_simplification() {
26464        let x = symbol!("x");
26465        let symbols = rubi_symbols();
26466        let angle = Atom::var(x);
26467        let deactivated = rubi_deactivate_trig(&parse!("sqrt(sin(x)^5/cos(x))"), x);
26468        let expected = (symbols.inert_sin.call((angle.to_owned(),)).pow(4)
26469            * symbols.inert_tan.call((angle,)))
26470        .pow(Atom::num(1) / Atom::num(2));
26471
26472        assert_eq!(
26473            deactivated, expected,
26474            "DeactivateTrig should feed Rubi the same sqrt(sin^4*tan) shape as Mathematica"
26475        );
26476    }
26477
26478    #[test]
26479    fn integrates_timofeev_564_via_tangent_substitution_path() {
26480        let x = symbol!("x");
26481        let integrand = parse!("sqrt(sin(x)^5/cos(x))");
26482        let primitive =
26483            integrate(&integrand, x).expect("Timofeev Problems.input line 564 should integrate");
26484
26485        assert!(
26486            !format!("{primitive}").contains("elliptic_f"),
26487            "Timofeev line 564 should follow Rubi's tangent substitution path, not the elliptic half-angle fallback: {primitive}"
26488        );
26489        assert!(
26490            !rubi_contains_unintegrable(&primitive),
26491            "Timofeev line 564 should not leave an internal unintegrable marker: {primitive}"
26492        );
26493    }
26494
26495    #[test]
26496    fn integrates_timofeev_595_via_rubi_trig_substitution_path() {
26497        assert_derivative_round_trip(parse!(
26498            "(3+sin(x)^2)*tan(x)^3/((-2+cos(x)^2)*(5-4*sec(x)^2)^(3/2))"
26499        ));
26500    }
26501
26502    #[test]
26503    fn integrates_quartic_x2_over_biquadratic_like_rubi_real_split() {
26504        let x = symbol!("x");
26505        let integrand = parse!("x^2/(1+x^4)");
26506        let primitive =
26507            integrate(&integrand, x).expect("Rubi 1.1.3.2.7.1.4 block 30 should integrate");
26508        let primitive_text = primitive.to_string();
26509
26510        assert!(
26511            primitive_text.contains("log") && primitive_text.contains("atan"),
26512            "Rubi should split x^2/(1+x^4) into the real atan/log branch: {primitive}"
26513        );
26514        assert!(
26515            !primitive_text.contains("𝑖"),
26516            "Rubi's traced x^2/(1+x^4) path should avoid the complex quadratic split: {primitive}"
26517        );
26518    }
26519
26520    #[test]
26521    fn integrates_cosine_half_angle_square_root_without_infinity_regression() {
26522        assert_derivative_round_trip(parse!("(1+cos(x))^(1/2)"));
26523    }
26524
26525    #[test]
26526    fn deactivates_trig_with_rubi_reduce_inert_trig_pi_shifts() {
26527        let x = symbol!("x");
26528
26529        assert_eq!(
26530            rubi_deactivate_trig(&parse!("sin(x+pi)"), x),
26531            rubi_inertize_builtin_trig_heads(&parse!("-sin(x)"))
26532        );
26533        assert_eq!(
26534            rubi_deactivate_trig(&parse!("cos(x+pi/2)"), x),
26535            rubi_inertize_builtin_trig_heads(&parse!("-sin(x)"))
26536        );
26537        assert_eq!(
26538            rubi_activate_trig(&rubi_deactivate_trig(&parse!("cos(x+pi/2)"), x)),
26539            parse!("-sin(x)")
26540        );
26541        assert_eq!(
26542            rubi_activate_trig(
26543                &(Atom::i()
26544                    * (Atom::var(Symbol::PI) / 2 + Atom::i() * Atom::var(x))
26545                        .cos()
26546                        .atanh()),
26547            ),
26548            parse!("atan(sinh(x))")
26549        );
26550    }
26551
26552    #[test]
26553    fn deactivates_linear_power_times_bare_sec_like_rubi() {
26554        let x = symbol!("x");
26555        let deactivated = rubi_deactivate_trig(&parse!("x^2*sec(x)"), x);
26556        let expected = rubi_inertize_builtin_trig_heads(&parse!("x^2*csc(x+pi/2)"));
26557
26558        assert_eq!(
26559            deactivated, expected,
26560            "DeactivateTrig should preserve Rubi's UnifyInertTrigFunction sec-to-csc path"
26561        );
26562
26563        let primitive = integrate(&parse!("x^2*sec(x)"), x)
26564            .expect("Rubi should integrate the Bondarenko 46 secant subintegral");
26565        assert!(
26566            !rubi_contains_unintegrable(&primitive),
26567            "secant subintegral should follow Rubi's csc/polylog path: {primitive}"
26568        );
26569
26570        let pure_secant = integrate(&parse!("sec(x)^4"), x)
26571            .expect("pure secant powers should use DeactivateTrig and the inert cosecant rules");
26572        assert_eq!(pure_secant.expand(), parse!("tan(x)+tan(x)^3/3").expand());
26573    }
26574
26575    #[test]
26576    fn logarithmic_rational_cases_follow_general_rubi_rules() {
26577        let x = symbol!("x");
26578        for input in ["(1+log(x))/(1+x+x^2)", "log(x^2)/(1/x-x)"] {
26579            let primitive = integrate(&parse!(input), x).unwrap_or_else(|_| {
26580                panic!("Rubi should integrate {input} through its general rules")
26581            });
26582            assert!(
26583                !rubi_contains_unintegrable(&primitive),
26584                "Rubi left an internal integral for {input}: {primitive}"
26585            );
26586        }
26587    }
26588
26589    #[test]
26590    fn generalized_current_rows_cover_removed_inverse_and_log_specializations() {
26591        let x = symbol!("x");
26592        let cases = [
26593            (6190, parse!("(1+asinh(2*x))/x")),
26594            (2842, parse!("x^2*(1+log(3*(4+5*x)^2))")),
26595        ];
26596
26597        for (order, integrand) in cases {
26598            let rule = rubi_rules()
26599                .iter()
26600                .find(|rule| rule.downvalue_order == Some(order))
26601                .unwrap_or_else(|| panic!("Rubi DownValue {order} should be ported"));
26602            let primitive = matcher_rule_for_test(&integrand, x, rule)
26603                .unwrap_or_else(|| panic!("Rubi DownValue {order} should cover {integrand}"));
26604            assert!(
26605                rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
26606                "Rubi DownValue {order} left an internal integral for {integrand}: {primitive}"
26607            );
26608        }
26609    }
26610
26611    #[test]
26612    fn hyperbolic_recurrence_rows_enforce_their_linear_exponent_relation() {
26613        let x = symbol!("x");
26614        for (order, function) in [(5855, "sinh"), (5856, "cosh")] {
26615            let matching = parse!(format!("x^3*{function}(1+2*x^2)^2"));
26616            let primitive = downvalue_primitive(order, &matching, x);
26617            assert!(
26618                !rubi_contains_unintegrable(&primitive),
26619                "Rubi DownValue {order} should handle {matching}: {primitive}"
26620            );
26621
26622            let rule = rubi_rules()
26623                .iter()
26624                .find(|rule| rule.downvalue_order == Some(order))
26625                .unwrap_or_else(|| panic!("Rubi DownValue {order} should be ported"));
26626            let nonmatching = parse!(format!("x^4*{function}(1+2*x^2)^2"));
26627            assert!(
26628                matcher_rule_for_test(&nonmatching, x, rule).is_none(),
26629                "Rubi DownValue {order} must reject {nonmatching} when m-2*n+1 != 0"
26630            );
26631        }
26632    }
26633
26634    #[test]
26635    fn unifies_secant_cosine_product_with_cosecant_of_shifted_angle() {
26636        let x = symbol!("x");
26637        let deactivated = rubi_deactivate_trig(
26638            &parse!("sqrt(sec(c+d*x))*(a+a*cos(c+d*x))^(5/2)*(A+B*cos(c+d*x))"),
26639            x,
26640        );
26641        let expected = rubi_inertize_builtin_trig_heads(&parse!(
26642            "sqrt(csc(c+d*x+pi/2))*(a+a*sin(c+d*x+pi/2))^(5/2)*(A+B*sin(c+d*x+pi/2))"
26643        ));
26644
26645        assert_eq!(deactivated, expected);
26646    }
26647
26648    #[test]
26649    fn deactivates_reciprocal_secant_cosecant_like_rubi() {
26650        let x = symbol!("x");
26651
26652        assert_eq!(
26653            rubi_deactivate_trig(&parse!("1/csc(c+d*x)"), x),
26654            rubi_inertize_builtin_trig_heads(&parse!("sin(c+d*x)"))
26655        );
26656        assert_derivative_round_trip(parse!("1/sec(c+d*x)"));
26657        assert_derivative_round_trip(parse!("1/csc(c+d*x)"));
26658    }
26659
26660    #[test]
26661    fn integrates_secant_fractional_radical_quotient_like_rubi() {
26662        assert_derivative_round_trip(parse!("sqrt(b*sec(c+d*x))/sec(c+d*x)^(3/2)"));
26663    }
26664
26665    #[test]
26666    fn rubi_simp_reduces_proportional_inverse_sqrt_product_like_mathematica() {
26667        let x = symbol!("x");
26668        let expr = parse!("(a/2+a*csc(c+d*x)/2)/(a+a*csc(c+d*x))^(1/2)");
26669
26670        let simplified = rubi_simp(&expr, x);
26671
26672        assert!(
26673            eqq!(simplified, parse!("1/2*(a+a*csc(c+d*x))^(1/2)")),
26674            "rubi_simp should reduce the proportional quotient over sqrt(base): {simplified}"
26675        );
26676    }
26677
26678    #[test]
26679    fn simp_evaluates_equivalent_shifted_imaginary_trig_calls() {
26680        let x = symbol!("x");
26681        let argument = parse!("c+d*x");
26682        let imaginary_argument = Atom::i() * &argument;
26683        let shifted_argument = Atom::var(Symbol::PI) / 2 + &imaginary_argument;
26684        let expr = (parse!("a") + parse!("b") * imaginary_argument.sec())
26685            * (parse!("A")
26686                + parse!("B") * shifted_argument.csc()
26687                + parse!("C") * shifted_argument.csc().pow(2));
26688
26689        assert_eq!(
26690            rubi_simp(&expr, x),
26691            parse!("(a+b*sech(c+d*x))*(A+B*sech(c+d*x)+C*sech(c+d*x)^2)")
26692        );
26693
26694        let integrand = parse!("(a+b*sech(c+d*x))^4");
26695        let primitive = integrate(&integrand, x)
26696            .expect("Rubi's DeactivateTrig recurrence should integrate the sech power");
26697        assert!(
26698            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
26699            "DeactivateTrig recurrence should not defer: {primitive}"
26700        );
26701        assert!(
26702            rubi_inert_trig_free_q(&primitive),
26703            "finished primitive should reactivate inert trig heads: {primitive}"
26704        );
26705        assert_rubi_derivative_round_trip(integrand);
26706    }
26707
26708    #[test]
26709    fn integrates_half_integer_secant_binomial_like_rubi() {
26710        assert_derivative_round_trip(parse!("(a+a*sec(c+d*x))^(3/2)"));
26711    }
26712
26713    #[test]
26714    fn deactivates_linear_hyperbolic_functions_like_rubi() {
26715        let x = symbol!("x");
26716        let x_atom = Atom::var(x);
26717
26718        assert_eq!(
26719            rubi_deactivate_trig_aux(&parse!("sinh(x)"), x),
26720            -Atom::i() * rubi_inertize_builtin_trig_heads(&(Atom::i() * &x_atom).sin())
26721        );
26722        assert_eq!(
26723            rubi_deactivate_trig_aux(&parse!("cosh(x)"), x),
26724            rubi_inertize_builtin_trig_heads(&(Atom::i() * x_atom.to_owned()).cos())
26725        );
26726        assert_eq!(
26727            rubi_deactivate_trig(&parse!("sinh(2*x)/cosh(2*x)"), x),
26728            -Atom::i()
26729                * rubi_symbols()
26730                    .inert_tan
26731                    .call((Atom::num(2) * Atom::i() * x_atom,))
26732        );
26733        assert_eq!(
26734            rubi_deactivate_trig(&parse!("1/cosh(x/2)^2"), x),
26735            rubi_symbols()
26736                .inert_csc
26737                .call((Atom::var(Symbol::PI) / 2 + Atom::i() * Atom::var(x) / 2,))
26738                .pow(2)
26739        );
26740        assert_eq!(
26741            rubi_reduce_builtin_trig_pi_shifts(&parse!("(x-1)/cosh(x/2)^2")),
26742            parse!("(x-1)*sech(x/2)^2")
26743        );
26744        assert_eq!(
26745            rubi_activate_trig(
26746                &rubi_symbols()
26747                    .inert_cos
26748                    .call((Atom::num(2) * Atom::i() * Atom::var(x),))
26749            ),
26750            parse!("cosh(2*x)")
26751        );
26752    }
26753
26754    #[test]
26755    fn deactivates_same_angle_trig_quotients_like_mathematica_before_rubi() {
26756        let x = symbol!("x");
26757        let inert = |expr: Atom| rubi_inertize_builtin_trig_heads(&expr);
26758
26759        assert_eq!(
26760            rubi_reduce_builtin_trig_pi_shifts(&parse!("x*sin(x)^2*cot(x)")),
26761            parse!("x*cos(x)*sin(x)")
26762        );
26763        assert_eq!(
26764            rubi_deactivate_trig(&parse!("cos(x)/sin(x)^3"), x),
26765            inert(parse!("-sec(x-pi/2)^2*tan(x-pi/2)"))
26766        );
26767
26768        let integrand = parse!("cos(x)/sin(x)^3");
26769        let primitive = integrate(&integrand, x)
26770            .expect("Apostol Problems.input line 17 should follow Rubi's Csc substitution path");
26771        let expected = parse!("-1/(2*sin(x)^2)");
26772        let primitive_difference = (primitive.to_owned() - expected).expand().cancel();
26773        let residual = (primitive.derivative(x) - integrand).together();
26774        assert!(
26775            residual_is_zero(&primitive_difference.derivative(x).together()),
26776            "primitive should differ from Rubi trace result only by a constant: {primitive_difference}"
26777        );
26778        assert!(
26779            residual_is_zero(&residual),
26780            "primitive derivative mismatch: {residual}"
26781        );
26782    }
26783
26784    #[test]
26785    fn algebraic_zero_test_fails_closed_on_function_calls() {
26786        assert!(!rubi_algebraic_zero_q(&parse!("sin(x)+1")));
26787    }
26788
26789    #[test]
26790    fn algebraic_zero_test_fails_closed_on_undefined_function_symbol() {
26791        assert!(!rubi_algebraic_zero_q(&parse!(
26792            "sinh - sin + sinh*x - sin*x"
26793        )));
26794    }
26795
26796    #[test]
26797    fn eqq_proves_rubi_23101_trig_log_derivative_condition() {
26798        let x = symbol!("x");
26799        let z = parse!("-cos(x)/(1+sin(x))");
26800        let expected = parse!("1/(1+sin(x))");
26801
26802        assert!(
26803            eqq!(rubi_d(&z, x), expected),
26804            "Rubi 2.3.101 should prove D[-cos(x)/(1+sin(x)),x] == 1/(1+sin(x))"
26805        );
26806    }
26807
26808    #[test]
26809    fn timofeev_665_does_not_panic_in_hyperbolic_head_condition() {
26810        let x = symbol!("x");
26811        let _ = integrate(&parse!("x*sin(x)^3/cos(x)^4"), x);
26812    }
26813
26814    #[test]
26815    fn integrates_products_of_symbolic_exponentials_via_rubi_23100() {
26816        assert_derivative_round_trip(parse!("a^x/b^x"));
26817        assert_derivative_round_trip(parse!("a^x*b^x"));
26818    }
26819
26820    #[test]
26821    fn integrates_hearn_exponential_trig_square_subcase_like_rubi() {
26822        assert_derivative_round_trip(parse!("x*e^(2*x)*sin(x)^2"));
26823    }
26824
26825    #[test]
26826    fn deactivates_outer_linear_trig_power_row_like_rubi() {
26827        let x = symbol!("x");
26828
26829        assert_eq!(
26830            rubi_deactivate_trig(&parse!("x^2*(1+cos(x))^(1/2)"), x),
26831            rubi_inertize_builtin_trig_heads(&parse!("x^2*(1+sin(x+1/2*pi))^(1/2)"))
26832        );
26833        assert_eq!(
26834            rubi_deactivate_trig(&parse!("cos(x)"), x),
26835            rubi_inertize_builtin_trig_heads(&parse!("sin(x+1/2*pi)"))
26836        );
26837    }
26838
26839    #[test]
26840    fn known_secant_integrand_accepts_rule_4264_power_shape() {
26841        let x = symbol!("x");
26842        let u = rubi_inertize_builtin_trig_heads(&parse!("(a+a*sec(c+d*x))^(5/2)"));
26843
26844        assert!(rubi_known_secant_integrand_q(&u, x), "rejected {u}");
26845    }
26846
26847    #[test]
26848    fn cancel_removes_common_integer_content_like_mathematica() {
26849        let perfect_square = parse!("16+32*sqrt(2)*x+32*x^2");
26850        let rule_27_payload = parse!("32/(16*sqrt(2)+32*x)^2");
26851
26852        assert_eq!(rubi_cancel(&rule_27_payload), Atom::num(1) / perfect_square);
26853    }
26854
26855    #[test]
26856    fn scaled_quadratic_radical_subintegral_terminates_as_unsupported() {
26857        let x = symbol!("x");
26858        let integrand = parse!("1/((16+32*sqrt(2)*x+32*x^2)*sqrt(1+2*x^2+4*x^3+x^4))");
26859
26860        assert!(integrate(&integrand, x).is_err());
26861    }
26862
26863    #[test]
26864    fn integrates_secant_radical_via_rubi_4264_path() {
26865        let x = symbol!("x");
26866        let integrand = parse!("(a+a*sec(c+d*x))^(5/2)*sqrt(cos(c+d*x))");
26867        assert!(
26868            rubi_function_of_trig_of_linear_q(&integrand, x),
26869            "FunctionOfTrigOfLinearQ rejected {integrand}"
26870        );
26871        assert_derivative_round_trip(integrand);
26872    }
26873
26874    #[test]
26875    fn remove_content_evaluates_linear_pi_half_trig_shifts_like_mathematica() {
26876        let x = symbol!("x");
26877
26878        assert_eq!(
26879            rubi_remove_content(&parse!("cos(x+1/2*pi)"), x),
26880            parse!("sin(x)")
26881        );
26882        assert_eq!(
26883            rubi_remove_content(&parse!("tan(x+1/2*pi)"), x),
26884            parse!("cot(x)")
26885        );
26886    }
26887
26888    #[test]
26889    fn remove_content_canonicalizes_numeric_minus_one_powers_like_mathematica() {
26890        let x = symbol!("x");
26891        let first = parse!("-(-(2-x^6)^(1/3)/(-1)^(1/3)+x^2)");
26892        let second = parse!("-(-(-1)^(1/3)*x^2+(2-x^6)^(1/3))");
26893        let expected = parse!("x^2+(-1)^(2/3)*(2-x^6)^(1/3)");
26894
26895        assert_eq!(
26896            rubi_normalize_numeric_minus_one_powers(parse!("(-1)^(-1/3)").as_view()),
26897            parse!("-(-1)^(2/3)")
26898        );
26899        assert_eq!(rubi_remove_content(&first, x), expected);
26900        assert_eq!(rubi_remove_content(&second, x), expected);
26901    }
26902
26903    #[test]
26904    fn remove_content_uses_mathematica_term_order_for_fractional_powers() {
26905        let x = symbol!("x");
26906        let input = parse!("(-1)^(1/3)*(1-x)^(1/3)-(1+x)^(1/3)");
26907        let expected = parse!("(1-x)^(1/3)+(-1)^(2/3)*(1+x)^(1/3)");
26908
26909        assert_eq!(
26910            rubi_mathematica_first_sum_term_in(&expected, x),
26911            Some(parse!("(1-x)^(1/3)"))
26912        );
26913        assert_eq!(rubi_remove_content(&input, x), expected);
26914        assert_eq!(rubi_remove_content(&expected, x), expected);
26915    }
26916
26917    #[test]
26918    fn remove_content_reaches_mathematica_csch_three_fixed_form() {
26919        let x = symbol!("x");
26920        let two_term_input = parse!("(-1)^(1/3)+exp(2*x)");
26921        let two_term_fixed = parse!("1-(-1)^(2/3)*exp(2*x)");
26922        let forms = [
26923            parse!("(-1)^(2/3)-(-1)^(1/3)*exp(2*x)+exp(4*x)"),
26924            parse!("-(-1)^(2/3)+(-1)^(1/3)*exp(2*x)-exp(4*x)"),
26925            parse!("(-1)^(1/3)-exp(2*x)-(-1)^(2/3)*exp(4*x)"),
26926            parse!("1+(-1)^(2/3)*exp(2*x)-(-1)^(1/3)*exp(4*x)"),
26927        ];
26928
26929        assert_eq!(rubi_remove_content(&two_term_input, x), two_term_fixed);
26930        assert_eq!(rubi_remove_content(&two_term_fixed, x), two_term_fixed);
26931        assert_eq!(rubi_remove_content(&forms[0], x), forms[1]);
26932        assert_eq!(rubi_remove_content(&forms[1], x), forms[2]);
26933        assert_eq!(rubi_remove_content(&forms[2], x), forms[3]);
26934        assert_eq!(rubi_remove_content(&forms[3], x), forms[3]);
26935    }
26936
26937    #[test]
26938    fn integrates_cotangent_like_rubi_stewart_21_trace() {
26939        let x = symbol!("x");
26940        let integrand = parse!("cot(x)");
26941        let primitive = integrate(&integrand, x).expect("Rubi rules should integrate cot(x)");
26942
26943        assert_eq!(primitive, parse!("log(sin(x))"));
26944        assert!(residual_is_zero(&(primitive.derivative(x) - integrand)));
26945    }
26946
26947    #[test]
26948    fn integrates_secant_tangent_like_rubi_stewart_98_trace() {
26949        let x = symbol!("x");
26950        let integrand = parse!("sec(x)^3*tan(x)^3");
26951        let primitive =
26952            integrate(&integrand, x).expect("Rubi rules should integrate Stewart line 98");
26953        let expected = parse!("-1/3*sec(x)^3 + 1/5*sec(x)^5");
26954        let primitive_difference = (primitive.to_owned() - expected).expand().cancel();
26955        let residual = (primitive.derivative(x) - integrand).together();
26956
26957        assert!(
26958            residual_is_zero(&primitive_difference),
26959            "primitive should match Rubi trace result up to simplification: {primitive_difference}"
26960        );
26961        assert!(
26962            residual_is_zero(&residual),
26963            "primitive derivative mismatch: {residual}"
26964        );
26965    }
26966
26967    #[test]
26968    fn integrates_secant_tangent_like_rubi_stewart_97_trace() {
26969        let x = symbol!("x");
26970        let integrand = parse!("sec(x)^3*tan(x)");
26971        let primitive =
26972            integrate(&integrand, x).expect("Rubi rules should integrate Stewart line 97");
26973        let expected = parse!("sec(x)^3/3");
26974        let primitive_difference = (primitive.to_owned() - expected).expand().cancel();
26975        let residual = (primitive.derivative(x) - integrand).together();
26976
26977        assert!(
26978            residual_is_zero(&primitive_difference),
26979            "primitive should match Rubi trace result up to simplification: {primitive_difference}"
26980        );
26981        assert!(
26982            residual_is_zero(&residual),
26983            "primitive derivative mismatch: {residual}"
26984        );
26985    }
26986
26987    #[test]
26988    fn integrates_apostol_84_like_rubi_trig_substfor_trace() {
26989        let x = symbol!("x");
26990        let integrand = parse!("sin(2*x)*sqrt(1+3*cos(x)^2)");
26991        let primitive =
26992            integrate(&integrand, x).expect("Rubi rules should integrate Apostol line 84");
26993        let expected = parse!("-2/9*(4-3*sin(x)^2)^(3/2)");
26994        let primitive_difference = (primitive.to_owned() - expected).expand().cancel();
26995        let residual = (primitive.derivative(x) - integrand).together();
26996
26997        assert!(
26998            residual_is_zero(&primitive_difference),
26999            "primitive should match Rubi trace result up to simplification: {primitive_difference}"
27000        );
27001        assert!(
27002            residual_is_zero(&residual),
27003            "primitive derivative mismatch: {residual}"
27004        );
27005    }
27006
27007    #[test]
27008    fn subst_for_factor_normalizes_tangent_payload_like_rubi_charlwood_20_trace() {
27009        let t = symbol!("t");
27010        let x = symbol!("x");
27011        let integrand = parse!("cos(x)^2/sqrt(1+cos(x)^2+cos(x)^4)");
27012        let reciprocal_sum = parse!("1+1/(1+t^2)+1/(1+t^2)^2");
27013        let together = rubi_together_simplify(&reciprocal_sum);
27014        let expected_together = parse!("(3+3*t^2+t^4)/(1+t^2)^2");
27015        assert_eq!(
27016            together, expected_together,
27017            "TogetherSimplify should match IntegrationUtilityFunctions.m NormalizeIntegrandFactorBase"
27018        );
27019        let normalized_base = rubi_normalize_integrand_factor_base(&reciprocal_sum, t);
27020        assert_eq!(
27021            normalized_base,
27022            expected_together,
27023            "NormalizeIntegrandFactorBase should accept TogetherSimplify (source leaf counts: 16 -> 18; Rust leaf counts: {} -> {})",
27024            rubi_leaf_count(reciprocal_sum.as_view()),
27025            rubi_leaf_count(together.as_view()),
27026        );
27027        let transformed =
27028            rubi_subst_for_factor(&parse!("1/(1+t^2)"), &parse!("tan(x)"), &integrand, t);
27029        let expected = parse!("1/((1+t^2)^2*((3+3*t^2+t^4)/(1+t^2)^2)^(1/2))");
27030        let difference = (transformed.to_owned() - expected.to_owned()).together();
27031
27032        assert!(
27033            transformed == expected,
27034            "SubstFor should preserve Mathematica's rule-7270 payload shape; got {transformed}; algebraic difference: {difference}"
27035        );
27036
27037        let primitive =
27038            integrate(&integrand, x).expect("Rubi elliptic rules should integrate Charlwood 20");
27039        assert!(
27040            rubi_integral_free_q(&primitive),
27041            "Charlwood 20 should reach Rubi elliptic rows instead of a deferred Int: {primitive}"
27042        );
27043    }
27044
27045    #[test]
27046    fn subst_for_factor_keeps_timofeev_566_tangent_power_compact() {
27047        let t = symbol!("t");
27048        let integrand = parse!("1/(cos(x)^11*sin(x)^13)^(1/4)");
27049        let substituted = rubi_subst_for(&integrand, &parse!("tan(x)"), t);
27050        assert_eq!(substituted, parse!("1/(t^13/(1+t^2)^12)^(1/4)"));
27051        let weighted = parse!("1/(1+t^2)") * &substituted;
27052        let expected = parse!("1/((t^13/(1+t^2)^12)^(1/4)*(1+t^2))");
27053        assert_eq!(weighted, expected);
27054        assert_eq!(
27055            rubi_simplify_rational_subexpressions(&weighted, t),
27056            expected
27057        );
27058        assert_eq!(rubi_normalize_integrand_aux(&weighted, t), expected);
27059        assert_eq!(rubi_mathematica_simplify(&weighted), expected);
27060        assert_eq!(
27061            rubi_simplify_integrand_mathematica_simplify_candidate(&weighted, t),
27062            None
27063        );
27064        assert_eq!(
27065            rubi_simplify_integrand_normalized_candidate(&weighted, t),
27066            None
27067        );
27068
27069        let transformed =
27070            rubi_subst_for_factor(&parse!("1/(1+t^2)"), &parse!("tan(x)"), &integrand, t);
27071        assert_eq!(transformed, expected);
27072    }
27073
27074    #[test]
27075    fn subst_for_factor_matches_timofeev_606_numeric_radical_content() {
27076        let t = symbol!("t");
27077        let x = symbol!("x");
27078        let simplified_trig = parse!("sec(x)^2*(-cos(2*x)+2*tan(x)^2)/(-1+sec(2*x))^(3/2)");
27079        let deactivated = rubi_deactivate_trig(&simplified_trig, x);
27080        let transformed =
27081            rubi_subst_for_factor(&parse!("1/(1+t^2)"), &parse!("tan(x)"), &deactivated, t);
27082        let expected = parse!("sqrt(1/8)*(-1+3*t^2+2*t^4)/((t^2/(1-t^2))^(3/2)*(1+t^2))");
27083
27084        assert_eq!(
27085            transformed, expected,
27086            "Mathematica SubstFor pulls positive numeric content out of the fractional power"
27087        );
27088        let rule_2058 = rubi_rules()
27089            .iter()
27090            .find(|rule| rule.downvalue_order == Some(2058))
27091            .expect("Rubi rule 2058 is loaded");
27092        let free_factor = rubi_free_factors(&transformed, t);
27093        assert_eq!(free_factor, parse!("sqrt(1/8)"));
27094        let without_free_factor = transformed / free_factor;
27095        assert!(
27096            matcher_rule_for_test(&without_free_factor, t, rule_2058).is_some(),
27097            "the normalized Timofeev 606 payload must dispatch to source rule 2058"
27098        );
27099    }
27100
27101    #[test]
27102    fn expand_integrand_groups_timofeev_568_expanded_radical_coefficients() {
27103        let x = symbol!("x");
27104        assert_eq!(
27105            parse!("-4/(x^2*(2+x^2))").apart(x),
27106            parse!("-2/x^2+2/(2+x^2)")
27107        );
27108        let integrand = parse!("4*x/((1+x^2)^2*(-sqrt(x)+sqrt(x/(1+x^2)^2)))");
27109        let expected = parse!(
27110            "-2/x^(3/2)-2*sqrt(x/(1+x^2)^2)/x^2+\
27111             2*sqrt(x)/(2+x^2)+2*sqrt(x/(1+x^2)^2)/(2+x^2)"
27112        );
27113
27114        let expanded = rubi_expand_integrand(&integrand, x);
27115        assert!(
27116            rubi_sum_q(&expanded),
27117            "ExpandIntegrand should expose Mathematica's partial-fraction sum: {expanded}"
27118        );
27119        assert_eq!(expanded, expected);
27120    }
27121
27122    #[test]
27123    fn latest_quartic_reciprocal_rule_integrates_charlwood_20_payload() {
27124        let t = symbol!("t");
27125        let integrand = parse!("1/((1+t^2)*sqrt(3+3*t^2+t^4))");
27126        let primitive = integrate(&integrand, t)
27127            .expect("latest Rubi rule 1540 should integrate the normalized payload");
27128        assert!(rubi_integral_free_q(&primitive));
27129    }
27130
27131    #[test]
27132    fn algebraic_eq_recognizes_quartic_block_16_square_root_guard() {
27133        let guard = parse!("1 - 3*(1/3*3^(1/2))^2");
27134
27135        assert!(
27136            eqq!(guard, 0),
27137            "EqQ should recognize the Rubi 1.2.2.7 block 16 generated guard"
27138        );
27139    }
27140
27141    #[test]
27142    fn integrates_quartic_block_17_generated_payload_via_block_16() {
27143        let x = symbol!("x");
27144        let integrand = parse!("(1+1/3*3^(1/2)*x^2)/((1+x^2)*(3+3*x^2+x^4)^(1/2))");
27145        assert_eq!(
27146            rubi_deactivate_trig(&integrand, x),
27147            integrand,
27148            "generated quartic payload should not enter trig deactivation"
27149        );
27150        let primitive = integrate(&integrand, x)
27151            .expect("Rubi 1.2.2.7 block 16 should integrate the generated payload");
27152
27153        assert!(
27154            !rubi_contains_unintegrable(&primitive),
27155            "generated quartic payload should not be left unintegrable: {primitive}"
27156        );
27157    }
27158
27159    #[test]
27160    fn integrates_charlwood_20_without_unintegrable() {
27161        let x = symbol!("x");
27162        let integrand = parse!("cos(x)^2/(1+cos(x)^2+cos(x)^4)^(1/2)");
27163        let primitive =
27164            integrate(&integrand, x).expect("Charlwood Problems.input line 20 should integrate");
27165
27166        assert!(
27167            !rubi_contains_unintegrable(&primitive),
27168            "Charlwood Problems.input line 20 should follow the Rubi trace path: {primitive}"
27169        );
27170    }
27171
27172    #[test]
27173    fn integrates_charlwood_35_via_rubi_inverse_sine_exponential_substitution() {
27174        let x = symbol!("x");
27175        let x_atom = Atom::var(x);
27176        let integrand = Atom::var(Symbol::E).pow(x_atom.asin()) * x_atom.pow(3)
27177            / (Atom::num(1) - x_atom.pow(2)).sqrt();
27178        let primitive =
27179            integrate(&integrand, x).expect("Charlwood Problems.input line 35 should integrate");
27180
27181        assert!(
27182            !rubi_contains_unintegrable(&primitive),
27183            "Charlwood Problems.input line 35 should follow Rubi 5.1.6 block 25: {primitive}"
27184        );
27185        assert!(
27186            rubi_inert_trig_free_q(&primitive),
27187            "inverse-trig substitution result should not be re-inertized: {primitive}"
27188        );
27189        assert!(
27190            rubi_integral_free_q(&primitive),
27191            "Charlwood line 35 should not leave a deferred Rubi integral: {primitive}"
27192        );
27193    }
27194
27195    #[test]
27196    fn integrates_charlwood_38_log_product_via_rubi_simplify_integrand() {
27197        assert_derivative_round_trip(parse!("x*log(1+x^2)*log(x+sqrt(1+x^2))/sqrt(1+x^2)"));
27198    }
27199
27200    #[test]
27201    fn integrates_charlwood_74_atan_log_product_via_rubi_simplify_integrand() {
27202        assert_derivative_round_trip(parse!("x*atan(x)*log(x+sqrt(1+x^2))/sqrt(1+x^2)"));
27203    }
27204
27205    #[test]
27206    fn integrates_charlwood_74_generated_log_derivative_payload() {
27207        assert_derivative_round_trip(parse!("log(x+sqrt(1+x^2))/sqrt(1+x^2)"));
27208    }
27209
27210    #[test]
27211    fn integrates_stewart_262_via_rubi_trig_simplify() {
27212        let x = symbol!("x");
27213        let deactivated = rubi_deactivate_trig(&parse!("1/(sin(x)+tan(x))"), x);
27214        assert_eq!(
27215            rubi_trig_simplify(&deactivated),
27216            parse!("cot(x)/(1+cos(x))"),
27217            "Stewart Problems.input line 262 follows Rubi TrigSimplifyAux tan/sin branch"
27218        );
27219
27220        assert_derivative_round_trip(parse!("1/(sin(x)+tan(x))"));
27221    }
27222
27223    #[test]
27224    fn integrates_stewart_263_via_rubi_trig_simplify() {
27225        assert_derivative_round_trip(parse!("1/(2*sin(x)+sin(2*x))"));
27226    }
27227
27228    #[test]
27229    fn trig_simplify_matches_timofeev_606_double_angle_tangent_product() {
27230        let x = symbol!("x");
27231        let input = rubi_deactivate_trig(
27232            &parse!("sec(x)^2*(-cos(2*x)+2*tan(x)^2)/(tan(x)*tan(2*x))^(3/2)"),
27233            x,
27234        );
27235        let expected = parse!("sec(x)^2*(-cos(2*x)+2*tan(x)^2)/(-1+sec(2*x))^(3/2)");
27236
27237        assert!(
27238            rubi_trig_simplify_q(&input),
27239            "Rubi TrigSimplifyQ accepts the Timofeev 606 double-angle identity"
27240        );
27241        assert_eq!(rubi_trig_simplify(&input), expected);
27242
27243        let tangent_substitution = rubi_rules()
27244            .iter()
27245            .find(|rule| rule.downvalue_order == Some(4889))
27246            .expect("Rubi rule 4889 is loaded");
27247        assert!(
27248            matcher_rule_for_test(&input, x, tangent_substitution).is_none(),
27249            "rule 4889 must honor Rubi's double-angle-tangent MatchQ exclusion"
27250        );
27251        let trig_simplification = rubi_rules()
27252            .iter()
27253            .find(|rule| rule.downvalue_order == Some(4897))
27254            .expect("Rubi rule 4897 is loaded");
27255        assert!(
27256            matcher_rule_for_test(&input, x, trig_simplification).is_some(),
27257            "Timofeev 606 must continue through source rule 4897"
27258        );
27259    }
27260
27261    #[test]
27262    fn simplifies_hyperbolic_cosecant_quotient_via_rubi_trig_simplify() {
27263        let x = symbol!("x");
27264        let x_atom = Atom::var(x);
27265        let deactivated = rubi_deactivate_trig(&parse!("csch(x)^2/(a+b*coth(x)+c*csch(x))"), x);
27266        let input = -deactivated;
27267        let i = Atom::i();
27268        let expected = -&i * x_atom.csch()
27269            / (i.to_owned() * parse!("c")
27270                + i.to_owned() * parse!("b") * x_atom.cosh()
27271                + i * parse!("a") * x_atom.sinh());
27272
27273        assert!(
27274            rubi_trig_simplify_q(&input),
27275            "Rubi TrigSimplifyAux should recognize its csc/cot three-term branch"
27276        );
27277        assert_eq!(rubi_trig_simplify(&input), expected);
27278    }
27279
27280    #[test]
27281    fn integrates_stewart_328_via_nested_function_of_trig_substitution() {
27282        let x = symbol!("x");
27283        let integrand = parse!("cos(cos(x))*sin(x)");
27284        assert_eq!(
27285            rubi_function_of_trig(&integrand, x),
27286            Some(Atom::var(x)),
27287            "Rubi FunctionOfTrig scans through non-linear trig heads before block 15 substitution"
27288        );
27289        assert_derivative_round_trip(integrand);
27290    }
27291
27292    #[test]
27293    fn integrates_improper_integer_binomial_via_rubi_2027_normalization() {
27294        assert_derivative_round_trip(parse!("1/(b/x+a*x)"));
27295    }
27296
27297    #[test]
27298    fn integrates_generalized_trinomial_power_after_expand_to_sum_like_rubi() {
27299        assert_derivative_round_trip(parse!("1/sqrt(1-(1-x^2)^3)"));
27300    }
27301
27302    #[test]
27303    fn returns_charlwood_14_deferred_primitive_like_rubi() {
27304        let x = symbol!("x");
27305        let integrand = parse!("asin(-sqrt(x)+sqrt(1+x))");
27306        let primitive = integrate(&integrand, x);
27307
27308        assert!(
27309            primitive.is_err(),
27310            "Mathematica Rubi leaves this case with deferred Int terms, so the public API should not leak rubi_int: {primitive:?}"
27311        );
27312    }
27313
27314    #[test]
27315    fn integrates_timofeev_315_via_fractional_power_of_linear_substitution() {
27316        let x = symbol!("x");
27317        let integrand =
27318            parse!("x*(1+x)^(2/3)*sqrt(1-x)/(-(1-x)^(5/6)*(1+x)^(1/3)+(1-x)^(2/3)*sqrt(1+x))");
27319        let primitive = integrate(&integrand, x)
27320            .expect("Timofeev Problems.input line 315 should integrate like Rubi 4.17.3");
27321
27322        assert!(
27323            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
27324            "Timofeev Problems.input line 315 should not retain deferred terms: {primitive}"
27325        );
27326    }
27327
27328    #[test]
27329    fn timofeev_801_function_of_trig_guard_matches_mathematica() {
27330        let x = symbol!("x");
27331        let x_atom = Atom::var(x);
27332        let i = Atom::i();
27333        let ix = &i * &x_atom;
27334        let v = Atom::num(2) * &ix;
27335        let u = (-i_cos(v.to_owned()) - &i * i_tan(ix.to_owned())) * i_cos(ix.to_owned())
27336            / (-&i * i_sin(v.to_owned()) - i_sin(ix.to_owned()).pow(2));
27337        let m = -Atom::num(1) / Atom::num(2);
27338        let c = -i;
27339        let seed = u * (&v / 2).sin().pow(2 * &m) / (c * (&v / 2).tan()).pow(&m);
27340        let w = rubi_function_of_trig(&seed, x)
27341            .expect("Mathematica FunctionOfTrig returns I*x for the DownValue 4890 seed");
27342        let nonfree = rubi_nonfree_factors(&rubi_activate_trig(&w.tan()), x);
27343
27344        assert_eq!(w, Atom::i() * x_atom);
27345        assert_eq!(nonfree, parse!("tanh(x)"));
27346        assert!(
27347            rubi_function_of_q(&nonfree, &seed, x),
27348            "Mathematica FunctionOfQ[Tanh[x], seed, x] is true"
27349        );
27350    }
27351
27352    #[test]
27353    fn integrates_apostol_233_via_rubi_sine_square_quotient_decomposition() {
27354        let x = symbol!("x");
27355        let integrand = parse!("sin(x)^2/(1+sin(x)^2)");
27356        let primitive =
27357            integrate(&integrand, x).expect("Apostol Problems.input line 233 should integrate");
27358        let expected = parse!("x - sqrt(1/2)*atan(sqrt(2)*tan(x))");
27359        let primitive_difference = (primitive.to_owned() - expected).expand().cancel();
27360        let residual = (primitive.derivative(x) - integrand).together();
27361
27362        assert!(
27363            residual_is_zero(&primitive_difference),
27364            "primitive should follow Rubi 4.1.7.3 and 4.1.7.13 path: {primitive_difference}"
27365        );
27366        assert!(
27367            residual_is_zero(&residual),
27368            "primitive derivative mismatch: {residual}"
27369        );
27370    }
27371
27372    #[test]
27373    fn function_of_sin_trig_matches_rubi_odd_cos_rejection_and_double_angle_reduction() {
27374        let x = symbol!("x");
27375        let v = Atom::var(x);
27376        let apostol_19_payload = parse!("sin(x)/(cos(x)*(3+cos(x))^2)");
27377        let apostol_84_payload = parse!("sqrt(1+3*cos(x)^2)*sin(2*x)/cos(x)");
27378
27379        assert!(
27380            !rubi_function_of_sin_trig_recur(&apostol_19_payload, &v, x),
27381            "Rubi FunctionOfSinQ rejects the odd Cos[x] dependence in Apostol Problems.input line 19"
27382        );
27383        assert!(
27384            rubi_function_of_sin_trig_recur(&apostol_84_payload, &v, x),
27385            "Rubi FunctionOfSinQ accepts Sin[2*x]/Cos[x] via FindTrigFactor reduction"
27386        );
27387    }
27388
27389    #[test]
27390    fn timofeev_580_function_of_sin_guard_matches_mathematica() {
27391        let x = symbol!("x");
27392        let u = parse!("cos(3*x)/(-sqrt(-1+8*cos(x)^2)+sqrt(3*cos(x)^2-sin(x)^2))");
27393        let v = rubi_function_of_trig(&u, x)
27394            .expect("Mathematica FunctionOfTrig returns x for Timofeev line 580");
27395        let payload = &u / v.cos();
27396
27397        assert_eq!(v, Atom::var(x));
27398        assert_eq!(rubi_nonfree_factors(&v.sin(), x), v.sin());
27399        assert!(
27400            rubi_function_of_q(&v.sin(), &payload, x),
27401            "Mathematica FunctionOfQ[Sin[x], u/Cos[x], x] is true"
27402        );
27403
27404        let inert_u = rubi_deactivate_trig(&u, x);
27405        let inert_v = rubi_function_of_trig(&inert_u, x)
27406            .expect("FunctionOfTrig activates its inert input like Mathematica");
27407        let inert_payload = &inert_u / inert_v.cos();
27408        assert!(
27409            rubi_function_of_q(&inert_v.sin(), &inert_payload, x),
27410            "FunctionOfQ must activate the inert Timofeev payload before its sine test"
27411        );
27412    }
27413
27414    #[test]
27415    fn deactivated_hyperbolic_products_pass_rubi_sine_substitution_guard() {
27416        let x = symbol!("x");
27417
27418        for (integrand, sine_substitution) in [
27419            (parse!("sinh(x)*tanh(6*x)"), true),
27420            (parse!("cosh(x)*tanh(6*x)"), false),
27421            (parse!("sinh(x)*coth(6*x)"), true),
27422            (parse!("cosh(x)*coth(6*x)"), false),
27423        ] {
27424            let inactive = rubi_deactivate_trig(&integrand, x);
27425            let payload = rubi_nonfree_factors(&inactive, x);
27426            let v = rubi_function_of_trig(&payload, x)
27427                .expect("FunctionOfTrig should find the common imaginary-linear argument");
27428            let sin = rubi_mathematica_evaluate_active_trig_call(Symbol::SIN, v.to_owned());
27429            let cos = rubi_mathematica_evaluate_active_trig_call(Symbol::COS, v.to_owned());
27430            let (base, quotient) = if sine_substitution {
27431                (rubi_nonfree_factors(&sin, x), &payload / cos)
27432            } else {
27433                (rubi_nonfree_factors(&cos, x), &payload / sin)
27434            };
27435
27436            assert!(
27437                rubi_function_of_q(&base, &quotient, x),
27438                "Rubi DownValue 4878/4879 accepts {integrand}; inactive={inactive}, payload={payload}, v={v}, base={base}, quotient={quotient}"
27439            );
27440        }
27441    }
27442
27443    #[test]
27444    fn subst_for_hyperbolic_products_matches_mathematica_multiple_angle_payloads() {
27445        let x = symbol!("x");
27446        let z = symbol!("z");
27447
27448        for (integrand, sine_substitution, expected) in [
27449            (
27450                parse!("sinh(x)*tanh(6*x)"),
27451                true,
27452                parse!("2*z^2*(-3-16*z^2-16*z^4)/(1+18*z^2+48*z^4+32*z^6)"),
27453            ),
27454            (
27455                parse!("cosh(x)*tanh(6*x)"),
27456                false,
27457                parse!("2*z^2*(-3+16*z^2-16*z^4)/(1-18*z^2+48*z^4-32*z^6)"),
27458            ),
27459            (
27460                parse!("sinh(x)*coth(6*x)"),
27461                true,
27462                parse!("(1+18*z^2+48*z^4+32*z^6)/(2*(3+19*z^2+32*z^4+16*z^6))"),
27463            ),
27464            (
27465                parse!("cosh(x)*coth(6*x)"),
27466                false,
27467                parse!("(-1+18*z^2-48*z^4+32*z^6)/(2*(3-19*z^2+32*z^4-16*z^6))"),
27468            ),
27469        ] {
27470            let payload = rubi_nonfree_factors(&rubi_deactivate_trig(&integrand, x), x);
27471            let v = rubi_function_of_trig(&payload, x)
27472                .expect("FunctionOfTrig should find the common imaginary-linear argument");
27473            let sin = rubi_mathematica_evaluate_active_trig_call(Symbol::SIN, v.to_owned());
27474            let cos = rubi_mathematica_evaluate_active_trig_call(Symbol::COS, v);
27475            let (base, quotient) = if sine_substitution {
27476                (rubi_nonfree_factors(&sin, x), &payload / cos)
27477            } else {
27478                (rubi_nonfree_factors(&cos, x), &payload / sin)
27479            };
27480            let transformed = rubi_subst_for_factor(&Atom::num(1), &base, &quotient, z);
27481
27482            assert_eq!(
27483                transformed, expected,
27484                "SubstFor should match Mathematica for {integrand}"
27485            );
27486        }
27487    }
27488
27489    #[test]
27490    fn integrates_timofeev_580_via_function_of_sine_substitution() {
27491        let x = symbol!("x");
27492        let integrand = parse!("cos(3*x)/(-sqrt(-1+8*cos(x)^2)+sqrt(3*cos(x)^2-sin(x)^2))");
27493        let primitive =
27494            integrate(&integrand, x).expect("Timofeev line 580 should follow Rubi DownValue 4878");
27495
27496        assert!(
27497            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
27498            "Rubi's sine substitution should complete Timofeev line 580: {primitive}"
27499        );
27500    }
27501
27502    #[test]
27503    fn integrates_formal_derivative_64_via_rubi_simp_cancellation() {
27504        let x = symbol!("x");
27505        let b = parse!("b");
27506        let angle = parse!("a+b*x");
27507        let f = symbol!("f");
27508        let f_x = f.call(Atom::var(x));
27509        let derivative_1 = rubi_derivative(Atom::num(1), Atom::var(f), x);
27510        let derivative_2 = rubi_derivative(Atom::num(2), Atom::var(f), x);
27511        let derivative_3 = rubi_derivative(Atom::num(3), Atom::var(f), x);
27512        assert_eq!(derivative_1.derivative(x), derivative_2);
27513        let deferred = rubi_unintegrable(angle.cos() * &f_x, x);
27514        let traced_int_sum = angle.sin() * &derivative_2
27515            - (&b * angle.cos() * &derivative_1 + b.pow(2) * angle.sin() * &f_x
27516                - b.pow(3) * &deferred)
27517            - b.pow(3) * deferred;
27518        let expected = -b.pow(2) * &f_x * angle.sin() - &b * angle.cos() * derivative_1
27519            + angle.sin() * derivative_2;
27520        assert_eq!(rubi_simp(&traced_int_sum, x), expected);
27521
27522        let integrand = -b.pow(3) * angle.cos() * f_x + angle.sin() * derivative_3;
27523        let primitive = integrate(&integrand, x)
27524            .expect("formal derivative line 64 should follow Rubi DownValues 2009/7213/7214");
27525
27526        assert_eq!(primitive, expected);
27527    }
27528
27529    #[test]
27530    fn function_of_q_handles_symbolic_order_derivatives_structurally() {
27531        let x = symbol!("x");
27532        let f = symbol!("f");
27533        let g = symbol!("g");
27534        let m = symbol!("m");
27535        let base = rubi_derivative(Atom::var(m), Atom::var(f), x) * g.call(Atom::var(x));
27536
27537        assert!(rubi_function_of_q(&base, &base.cos(), x));
27538        assert!(rubi_function_of_q(
27539            &base,
27540            &Symbol::DERIVATIVE.call((Atom::num(1), Atom::var(symbol!("F")), base.to_owned())),
27541            x,
27542        ));
27543    }
27544
27545    #[test]
27546    fn function_of_q_uses_shared_function_of_expn_q_like_rubi() {
27547        let x = symbol!("x");
27548
27549        assert!(
27550            !rubi_function_of_q(&parse!("1/x"), &parse!("sqrt(x+sqrt(1+x))"), x),
27551            "Rubi FunctionOfQ[1/x, Sqrt[x+Sqrt[1+x]], x] is False"
27552        );
27553        assert!(
27554            rubi_function_of_q(&parse!("1/x"), &parse!("sqrt(1/x+sqrt(1+1/x))"), x),
27555            "Rubi FunctionOfQ[x^-1, Sqrt[x^-1+Sqrt[1+x^-1]], x] is True"
27556        );
27557        assert!(
27558            !rubi_function_of_q(&parse!("x^2"), &parse!("sqrt(1/x+sqrt(1+1/x))"), x),
27559            "Rubi FunctionOfQ[x^2, Sqrt[x^-1+Sqrt[1+x^-1]], x] is False"
27560        );
27561        assert!(
27562            !rubi_function_of_q(&rubi_product_log(Atom::var(x)), &parse!("exp(exp(x)+x)"), x),
27563            "Rubi FunctionOfQ[ProductLog[x], E^(E^x+x), x] is False"
27564        );
27565        assert!(
27566            !rubi_function_of_q(
27567                &rubi_product_log(Atom::var(x)),
27568                &parse!("(a^(k*x)+a^(l*x))^2"),
27569                x,
27570            ),
27571            "Rubi FunctionOfQ[ProductLog[x], (a^(k*x)+a^(l*x))^2, x] is False"
27572        );
27573        assert!(
27574            rubi_function_of_q(&parse!("x^2"), &parse!("asin(x^2)"), x),
27575            "Rubi FunctionOfQ[x^2, ArcSin[x^2], x] is True"
27576        );
27577        assert!(
27578            rubi_function_of_q(&parse!("x^2"), &parse!("1/sqrt(-1+exp(2*x^2))"), x),
27579            "Rubi FunctionOfQ[x^2, 1/Sqrt[-1+E^(2*x^2)], x] is True"
27580        );
27581        assert!(
27582            rubi_function_of_q(
27583                &parse!("tanh(x)"),
27584                &parse!("sinh(x)*cosh(x)+cosh(2*x)^2"),
27585                x,
27586            ),
27587            "Rubi FunctionOfTanhQ accepts paired odd hyperbolic factors and even multiples"
27588        );
27589        assert!(
27590            rubi_function_of_q(
27591                &parse!("tan(a+b*x)"),
27592                &parse!("(cos(a+b*x)^5-sin(a+b*x)^5)/(cos(a+b*x)^5+sin(a+b*x)^5)"),
27593                x,
27594            ),
27595            "Rubi FunctionOfTanQ accepts paired odd trig-power sums"
27596        );
27597        assert!(
27598            !rubi_function_of_q(
27599                &parse!("tanh(x)"),
27600                &parse!("cosh(x)*(-cosh(2*x)+tanh(x))/(sqrt(sinh(2*x))*(sinh(x)^2+sinh(2*x)))"),
27601                x,
27602            ),
27603            "Rubi FunctionOfTanhQ rejects Timofeev 801 before fractional-power normalization"
27604        );
27605        assert!(
27606            !rubi_calculus_function_symbol(symbol!("asin"))
27607                && !rubi_calculus_function_symbol(symbol!("sech"))
27608                && !rubi_calculus_function_symbol(symbol!("log")),
27609            "Rubi CalculusQ excludes elementary and inverse functions"
27610        );
27611    }
27612
27613    #[test]
27614    fn integrates_exp_exp_plus_linear_by_rubi_function_of_exponential_substitution() {
27615        assert_derivative_round_trip(parse!("exp(exp(x)+x)"));
27616    }
27617
27618    #[test]
27619    fn integrates_exponential_binomial_by_power_substitution_like_rubi() {
27620        assert_derivative_round_trip(parse!("x/sqrt(-1+exp(2*x^2))"));
27621    }
27622
27623    #[test]
27624    fn integrates_symbolic_base_exponential_sum_without_productlog_substitution() {
27625        let x = symbol!("x");
27626        let integrand = parse!("(a^(k*x)+a^(l*x))^2");
27627        let primitive =
27628            integrate(&integrand, x).unwrap_or_else(|_| panic!("rule should apply to {integrand}"));
27629        let primitive_text = primitive.to_string();
27630        let residual = (primitive.derivative(x) - integrand).together();
27631
27632        assert!(
27633            !primitive_text.contains("product_log"),
27634            "Timofeev 686 should follow Rubi's exponential expansion path, not ProductLog substitution: {primitive}"
27635        );
27636        assert!(
27637            residual_is_zero(&residual),
27638            "derivative round trip failed; primitive: {primitive}; residual: {residual}"
27639        );
27640    }
27641
27642    #[test]
27643    fn integrates_linear_over_linear_exponential_denominator_like_rubi() {
27644        assert_derivative_round_trip(parse!("x/(a+b*exp(x))"));
27645    }
27646
27647    #[test]
27648    fn integrates_quadratic_over_linear_exponential_denominator_like_rubi() {
27649        assert_derivative_round_trip(parse!("x^2/(a+b*exp(x))"));
27650    }
27651
27652    #[test]
27653    fn integrates_exponential_quadratic_denominator_by_rubi_decomposition() {
27654        assert_derivative_round_trip(parse!("x/(a+b*exp(x)+c*exp(2*x))"));
27655    }
27656
27657    #[test]
27658    fn differentiates_rubi_inverse_trig_polylog_path_with_atanh_logs() {
27659        let x = symbol!("x");
27660        let integrand = parse!("asin(x)/(x*(1-x^2)^(3/2))");
27661        let primitive =
27662            integrate(&integrand, x).unwrap_or_else(|_| panic!("rule should apply to {integrand}"));
27663        let residual = (rubi_differentiate(&primitive, x) - integrand).together();
27664
27665        assert!(
27666            residual_is_zero(&residual),
27667            "derivative round trip failed; primitive: {primitive}; residual: {residual}"
27668        );
27669    }
27670
27671    #[test]
27672    fn normalizes_shifted_inverse_trig_exponentials() {
27673        let x = symbol!("x");
27674        let x_atom = Atom::var(x);
27675        let expression = Atom::var(Symbol::E)
27676            .pow(Atom::i() * (Atom::num(2) * x_atom.acos() + Atom::var(Symbol::PI)));
27677        let expanded_expression = Atom::var(Symbol::E)
27678            .pow(Atom::num(2) * Atom::i() * x_atom.acos() + Atom::i() * Atom::var(Symbol::PI));
27679        let normalized = rubi_normalize_inverse_trig_exponentials(expression.as_view());
27680        let expanded_normalized =
27681            rubi_normalize_inverse_trig_exponentials(expanded_expression.as_view());
27682
27683        assert!(
27684            !normalized.to_string().contains('𝑒'),
27685            "shifted inverse-trig exponential should normalize: {normalized}"
27686        );
27687        assert!(
27688            !expanded_normalized.to_string().contains('𝑒'),
27689            "expanded shifted inverse-trig exponential should normalize: {expanded_normalized}"
27690        );
27691    }
27692
27693    #[test]
27694    fn integrates_lowercase_e_exp_exp_plus_linear() {
27695        let x = symbol!("x");
27696        let integrand = parse!("e^(e^x+x)");
27697        let primitive =
27698            integrate(&integrand, x).unwrap_or_else(|_| panic!("rule should apply to {integrand}"));
27699
27700        let residual = primitive.derivative(x) - integrand;
27701        let residual = rubi_normalize_euler_logs(residual.as_view()).together();
27702        let residual = rubi_normalize_product_log_exponentials(&residual);
27703        assert!(
27704            residual_is_zero(&residual),
27705            "derivative round trip failed; primitive: {primitive}; residual: {residual}"
27706        );
27707    }
27708
27709    #[test]
27710    fn integrates_productlog_denominator_with_productlog_derivative() {
27711        assert_derivative_round_trip(parse!("1/(1+ProductLog(x))"));
27712    }
27713
27714    #[test]
27715    fn integrates_charlwood_26_secant_power_substitution_like_rubi() {
27716        let x = symbol!("x");
27717        let integrand = parse!("tan(x)/sqrt(1+sec(x)^3)");
27718        let primitive = integrate(&integrand, x).expect("Rubi should integrate Charlwood line 26");
27719        let expected =
27720            -Atom::num(2) * (Atom::num(1) + parse!("sec(x)^3")).sqrt().atanh() / Atom::num(3);
27721        let primitive_difference = (primitive.to_owned() - expected).together();
27722        let residual = (rubi_differentiate(&primitive, x) - integrand).together();
27723
27724        assert!(
27725            residual_is_zero(&primitive_difference),
27726            "primitive should match the Charlwood 26 Rubi trace: {primitive_difference}"
27727        );
27728        assert!(
27729            residual_is_zero(&residual),
27730            "primitive derivative mismatch: {residual}"
27731        );
27732    }
27733
27734    #[test]
27735    fn product_log_has_custom_derivative() {
27736        let x = symbol!("x");
27737        let product_log = parse!("ProductLog(x)");
27738        let derivative = product_log.derivative(x);
27739        let expected = product_log.to_owned() / (Atom::var(x) * (Atom::num(1) + product_log));
27740        let difference = (derivative - expected).together();
27741
27742        assert!(
27743            residual_is_zero(&difference),
27744            "Rubi derivative should know D[ProductLog[x], x]: {difference}"
27745        );
27746    }
27747
27748    #[test]
27749    fn rubi_result_function_heads_are_initialized_before_rule_parsing() {
27750        let _ = parse!("x");
27751        let symbols = rubi_symbols();
27752        let cases = [
27753            (parse!("Erfc(x)"), symbols.erfc),
27754            (parse!("ExpIntegralE(1,x)"), symbols.exp_integral_e),
27755            (parse!("zeta(2,x)"), symbolica::transcendental::zeta()),
27756            (parse!("SinIntegral(x)"), symbols.sin_integral),
27757            (parse!("CosIntegral(x)"), symbols.cos_integral),
27758            (parse!("SinhIntegral(x)"), symbols.sinh_integral),
27759            (parse!("CoshIntegral(x)"), symbols.cosh_integral),
27760            (parse!("Gamma(2,x)"), symbols.gamma),
27761            (
27762                parse!("HypergeometricPFQ(1,2,3,4,x)"),
27763                symbols.hypergeometric_pfq,
27764            ),
27765        ];
27766
27767        for (expression, expected) in cases {
27768            let function = expression
27769                .as_fun_view()
27770                .expect("result function should parse as a function");
27771            assert_eq!(function.get_symbol(), expected, "{expression}");
27772        }
27773    }
27774
27775    #[test]
27776    fn rubi_differentiate_simplifies_nested_unit_log_arguments() {
27777        let x = symbol!("x");
27778        let input = parse!("log(1-(1-x))");
27779        let normalized = rubi_normalize_euler_logs(input.as_view());
27780
27781        assert_eq!(normalized, parse!("log(x)"));
27782        let difference = (rubi_differentiate(&parse!("polylog(2, 1-(1-x))"), x)
27783            - parse!("-log(1-x)/x"))
27784        .expand()
27785        .cancel();
27786        assert!(residual_is_zero(&difference), "{difference}");
27787    }
27788
27789    #[test]
27790    fn trig_integral_heads_have_custom_derivatives() {
27791        let x = symbol!("x");
27792        let sin_difference =
27793            (parse!("SinIntegral(3*x)").derivative(x) - parse!("sin(3*x)/x")).together();
27794        let cos_difference =
27795            (parse!("CosIntegral(3*x)").derivative(x) - parse!("cos(3*x)/x")).together();
27796        let sinh_difference =
27797            (parse!("SinhIntegral(3*x)").derivative(x) - parse!("sinh(3*x)/x")).together();
27798        let cosh_difference =
27799            (parse!("CoshIntegral(3*x)").derivative(x) - parse!("cosh(3*x)/x")).together();
27800
27801        assert!(residual_is_zero(&sin_difference), "{sin_difference}");
27802        assert!(residual_is_zero(&cos_difference), "{cos_difference}");
27803        assert!(residual_is_zero(&sinh_difference), "{sinh_difference}");
27804        assert!(residual_is_zero(&cosh_difference), "{cosh_difference}");
27805    }
27806
27807    #[test]
27808    fn integrates_arcsin_power_case_with_sin_integral_terms() {
27809        let x = symbol!("x");
27810        let integrand = parse!("(c-a^2*c*x^2)^3/asin(a*x)^2");
27811        let primitive = integrate(&integrand, x).expect("Rubi should integrate corpus line 443");
27812        let residual = (rubi_differentiate(&primitive, x) - integrand).together();
27813
27814        assert!(
27815            residual_is_zero(&residual),
27816            "primitive derivative mismatch for inverse sine corpus line 443: {residual}"
27817        );
27818    }
27819
27820    #[test]
27821    fn subst_for_sin_trig_expands_integer_multiple_like_rubi() {
27822        let x = symbol!("x");
27823        let sub = symbol!("sub_test");
27824        let payload = parse!("sqrt(1+3*cos(x)^2)*sin(2*x)/cos(x)");
27825        let transformed =
27826            rubi_subst_for_sin_trig(&payload, &Atom::var(x), &Atom::num(1), sub).together();
27827        let expected = parse!("2*sub_test*sqrt(4-3*sub_test^2)");
27828        let difference = (transformed - expected).expand().cancel();
27829
27830        assert!(
27831            residual_is_zero(&difference),
27832            "SubstFor[Sin[x], ...] should follow Rubi's SubstForTrig path: {difference}"
27833        );
27834    }
27835
27836    #[test]
27837    fn subst_for_sinh_hyperbolic_expands_cosh_square_like_rubi() {
27838        let sub = symbol!("sub_test");
27839        let payload = parse!("log(1+cosh(x)^2)^2");
27840        let transformed = rubi_subst_for(&payload, &parse!("sinh(x)"), sub).together();
27841        let expected = parse!("log(2+sub_test^2)^2");
27842        let difference = (transformed - expected).expand().cancel();
27843
27844        assert!(
27845            residual_is_zero(&difference),
27846            "SubstFor[Sinh[x], ...] should follow Rubi's SubstForHyperbolic path: {difference}"
27847        );
27848    }
27849
27850    #[test]
27851    fn apostol_19_follows_rubi_downvalue_3147_after_deactivate_trig() {
27852        let x = symbol!("x");
27853        let active_integrand = parse!("sin(x)/(3+cos(x))^2");
27854        let deactivated = rubi_deactivate_trig(&active_integrand, x);
27855        let expected_deactivated =
27856            rubi_inertize_builtin_trig_heads(&parse!("cos(x-pi/2)/(3-sin(x-pi/2))^2"));
27857        assert_eq!(
27858            deactivated, expected_deactivated,
27859            "Rubi DeactivateTrig should apply its UnifyInertTrigFunction phase shift"
27860        );
27861
27862        let primitive = rubi_rules()
27863            .iter()
27864            .find(|rule| rule.downvalue_order == Some(3147))
27865            .and_then(|rule| matcher_rule_for_test(&deactivated, x, rule))
27866            .expect("Rubi DownValue 3147 should match Apostol Problems.input line 19");
27867        let primitive = rubi_activate_trig(&primitive);
27868        let expected = parse!("1/(3+cos(x))");
27869        let primitive_difference = (primitive.to_owned() - expected.to_owned()).together();
27870        let residual = (primitive.derivative(x) - active_integrand.to_owned()).together();
27871
27872        assert!(
27873            residual_is_zero(&primitive_difference),
27874            "primitive should match Rubi trace result up to simplification: {primitive_difference}"
27875        );
27876        assert!(
27877            residual_is_zero(&residual),
27878            "primitive derivative mismatch: {residual}"
27879        );
27880
27881        let full_primitive = integrate(&active_integrand, x)
27882            .expect("Apostol line 19 should integrate through Rubi's DeactivateTrig path");
27883        let full_difference = (full_primitive.to_owned() - expected).together();
27884        let full_residual = (full_primitive.derivative(x) - active_integrand).together();
27885        assert!(
27886            residual_is_zero(&full_difference),
27887            "full integration primitive should match Rubi trace result up to simplification: {full_difference}"
27888        );
27889        assert!(
27890            residual_is_zero(&full_residual),
27891            "full integration derivative mismatch: {full_residual}"
27892        );
27893    }
27894
27895    #[test]
27896    fn integrates_bondarenko_27_fractional_power_quotient_substitution_like_rubi() {
27897        assert_derivative_round_trip(parse!("sqrt(1/x+sqrt(1+1/x))"));
27898    }
27899
27900    #[test]
27901    fn simplify_integrand_preserves_bondarenko_27_radical_sum_like_rubi() {
27902        let x = symbol!("x");
27903        let integrand = parse!("sqrt(1/x+sqrt(1+1/x))");
27904        let simplified = rubi_simplify_integrand(&integrand, x);
27905
27906        assert_eq!(
27907            simplified, integrand,
27908            "Rubi SimplifyIntegrand leaves this quotient-of-linears radical unchanged"
27909        );
27910    }
27911
27912    #[test]
27913    fn integrates_bondarenko_26_fractional_linear_substitution_like_rubi() {
27914        assert_derivative_round_trip(parse!("sqrt(x+sqrt(1+x))/x^2"));
27915    }
27916
27917    #[test]
27918    fn activates_trig_without_pi_shift_rewrites_like_rubi() {
27919        assert_eq!(
27920            rubi_activate_trig(&parse!("sin(x+pi/2)")),
27921            parse!("sin(x+1/2*pi)")
27922        );
27923        assert_eq!(
27924            rubi_activate_trig(&parse!("cos(x-pi/2)")),
27925            parse!("cos(x-1/2*pi)")
27926        );
27927    }
27928
27929    #[test]
27930    fn activates_inert_trig_with_rubi_pi_shift_reduction() {
27931        let inert = |expr: Atom| rubi_inertize_builtin_trig_heads(&expr);
27932
27933        assert_eq!(
27934            rubi_activate_trig(&inert(parse!("csc(3*x+3/4*pi)"))),
27935            parse!("sec(3*x+1/4*pi)")
27936        );
27937        assert_eq!(
27938            rubi_activate_trig(&inert(parse!("-tan(1/3*x+3/4*pi)"))),
27939            parse!("cot(1/3*x+1/4*pi)")
27940        );
27941    }
27942
27943    #[test]
27944    fn reduces_rule_built_active_trig_pi_shifts() {
27945        assert_eq!(
27946            rubi_reduce_builtin_trig_pi_shifts(&parse!("csc(3*x+3/4*pi)")),
27947            parse!("sec(3*x+1/4*pi)")
27948        );
27949        assert_eq!(
27950            rubi_reduce_builtin_trig_pi_shifts(&parse!("cos(3*x+3/4*pi)")),
27951            parse!("-sin(3*x+1/4*pi)")
27952        );
27953    }
27954
27955    #[test]
27956    fn evaluates_rule_built_active_trig_parity_like_mathematica() {
27957        assert_eq!(
27958            rubi_reduce_builtin_trig_pi_shifts(&parse!("sin(-c-d*x)")),
27959            parse!("-sin(c+d*x)")
27960        );
27961        assert_eq!(
27962            rubi_reduce_builtin_trig_pi_shifts(&parse!("cos(-c-d*x)")),
27963            parse!("cos(c+d*x)")
27964        );
27965        assert_eq!(
27966            rubi_reduce_builtin_trig_pi_shifts(&parse!("sec(-c-d*x)")),
27967            parse!("sec(c+d*x)")
27968        );
27969    }
27970
27971    #[test]
27972    fn integrates_secant_tangent_radical_rows_via_mathematica_parity_evaluation() {
27973        assert_integrand_produces_primitive("(e*tan(c+d*x))^(3/2)/(a+b*sec(c+d*x))");
27974        assert_integrand_produces_primitive("1/((a+b*sec(c+d*x))*(e*tan(c+d*x))^(1/2))");
27975        assert_integrand_produces_primitive("1/((a+b*sec(c+d*x))*(e*tan(c+d*x))^(5/2))");
27976    }
27977
27978    #[test]
27979    fn fixes_inert_trig_reciprocal_product_rows() {
27980        let x = symbol!("x");
27981        let inert = |expr: Atom| rubi_inertize_builtin_trig_heads(&expr);
27982        assert_eq!(
27983            rubi_fix_inert_trig_function(&inert(parse!("csc(x)^2*sin(x)^3")), x),
27984            inert(parse!("sin(x)"))
27985        );
27986        assert_eq!(
27987            rubi_fix_inert_trig_function(&inert(parse!("sec(x)^2*cos(x)^3")), x),
27988            inert(parse!("cos(x)"))
27989        );
27990        assert_eq!(
27991            rubi_fix_inert_trig_function(&inert(parse!("x*tan(x)^2*(1+sin(x))")), x),
27992            inert(parse!("x*sin(x)^2*cos(x)^(-2)*(1+sin(x))"))
27993        );
27994        assert_eq!(
27995            rubi_fix_inert_trig_function(&inert(parse!("sec(x)^2*(1+cos(x))")), x),
27996            inert(parse!("cos(x)^(-2)*(1+cos(x))"))
27997        );
27998        assert_eq!(
27999            rubi_fix_inert_trig_function(&inert(parse!("cos(x)^2*(1+2*sec(x)+3*sec(x)^2)")), x),
28000            inert(parse!("sec(x)^(-2)*(1+2*sec(x)+3*sec(x)^2)"))
28001        );
28002        assert_eq!(
28003            rubi_fix_inert_trig_function(&inert(parse!("sec(x)^2*(1+2*cos(x)+3*cos(x)^2)^3")), x),
28004            inert(parse!("cos(x)^(-2)*(1+2*cos(x)+3*cos(x)^2)^3"))
28005        );
28006    }
28007
28008    #[test]
28009    fn unifies_inert_secant_to_cosecant_rows() {
28010        let x = symbol!("x");
28011        let inert = |expr: Atom| rubi_inertize_builtin_trig_heads(&expr);
28012        assert_eq!(
28013            rubi_unify_inert_trig_function(&inert(parse!("(1+sec(x))^2")), x),
28014            inert(parse!("(1+csc(x+1/2*pi))^2"))
28015        );
28016        assert_eq!(
28017            rubi_unify_inert_trig_function(
28018                &inert(parse!("(b*sec(c+d*x))^(1/3)*(A+C*sec(c+d*x)^2)")),
28019                x,
28020            ),
28021            inert(parse!(
28022                "(b*csc(c+1/2*pi+d*x))^(1/3)*(A+C*csc(c+1/2*pi+d*x)^2)"
28023            ))
28024        );
28025        assert_eq!(
28026            rubi_unify_inert_trig_function(
28027                &inert(parse!(
28028                    "(a*cos(x)+b)^(3/2)*(c*cos(x)+d)^(-7/2)*(A+B*cos(x)+C*cos(x)^2)"
28029                )),
28030                x,
28031            ),
28032            inert(parse!(
28033                "(a*sin(x+1/2*pi)+b)^(3/2)*(c*sin(x+1/2*pi)+d)^(-7/2)*(A+B*sin(x+1/2*pi)+C*sin(x+1/2*pi)^2)"
28034            ))
28035        );
28036    }
28037
28038    #[test]
28039    fn integrates_half_integer_equal_secant_binomial_like_rubi() {
28040        assert_derivative_round_trip(parse!("(a+a*sec(c+d*x))^(3/2)"));
28041    }
28042
28043    #[test]
28044    fn unifies_additional_inert_trig_rubi_rules() {
28045        let x = symbol!("x");
28046        let inert = |expr: Atom| rubi_inertize_builtin_trig_heads(&expr);
28047        assert_eq!(
28048            rubi_unify_inert_trig_function(&inert(parse!("(1+cot(x))^2")), x),
28049            inert(parse!("(1-tan(x+1/2*pi))^2"))
28050        );
28051        assert_eq!(
28052            rubi_unify_inert_trig_function(&inert(parse!("(1+(2*csc(x))^3)^4")), x),
28053            inert(parse!("(1+(-2*sec(x+1/2*pi))^3)^4"))
28054        );
28055    }
28056
28057    #[test]
28058    fn unifies_inert_sin_times_cos_binomial_like_rubi_rule_6769() {
28059        let x = symbol!("x");
28060        let inert = |expr: Atom| rubi_inertize_builtin_trig_heads(&expr);
28061        assert_eq!(
28062            rubi_unify_inert_trig_function(&inert(parse!("sin(x)/(3+cos(x))^2")), x),
28063            inert(parse!("cos(x-pi/2)/(3-sin(x-pi/2))^2"))
28064        );
28065    }
28066
28067    #[test]
28068    fn expand_integrand_3635_handles_defaulted_log_linear_product() {
28069        let x = symbol!("x");
28070        let integrand = parse!("(g+h*x)*(a+b*log(c*d^q*(e+f*x)^(p*q)))^3");
28071        let expanded = rubi_expand_integrand(&integrand, x);
28072        let expected = parse!(
28073            "h*(a+b*log(c*d^q*(x*f+e)^(q*p)))^3*(x*f+e)/f+(g-h*e/f)*(a+b*log(c*d^q*(x*f+e)^(q*p)))^3"
28074        );
28075
28076        assert!(
28077            residual_is_zero(&(expanded.to_owned() - expected).expand().cancel()),
28078            "ExpandIntegrand 3635 should use ExpandLinearProduct, got {expanded}"
28079        );
28080    }
28081
28082    #[test]
28083    fn integrates_shifted_affine_quotients_through_pdf_rows() {
28084        assert_derivative_round_trip(parse!("x^(-2+n)/(1 + 2*x)^n"));
28085        assert_derivative_round_trip(parse!("x^(-3+n)/(1 + 2*x)^n"));
28086        assert_derivative_round_trip(parse!("x^(-4+n)/(1 + 2*x)^n"));
28087        assert_derivative_round_trip(parse!("x^(-1+n)*(1 + 2*x)^(-1-n)"));
28088        assert_derivative_round_trip(parse!("x^(-3-n)*(1 + 2*x)^n"));
28089        assert_derivative_round_trip(parse!("x^(2*n-3*(1+n))*(1 + 2*x)^n"));
28090    }
28091
28092    #[test]
28093    fn non_pdf_quadratic_monomial_shortcuts_are_absent() {
28094        for rule in rubi_rules() {
28095            assert!(
28096                !rule.id.contains("quadratic monomial"),
28097                "{} should not preserve non-PDF quadratic monomial shortcut coverage",
28098                rule.id
28099            );
28100        }
28101    }
28102
28103    #[test]
28104    fn non_pdf_monomial_affine_shortcuts_are_absent_in_1112() {
28105        let removed_ids = [
28106            "Rubi 1.1.1.2 monomial multiplier affine power",
28107            "Rubi 1.1.1.2 affine power monomial multiplier",
28108            "Rubi 1.1.1.2 monomial affine power",
28109            "Rubi 1.1.1.2 monomial affine factor",
28110            "Rubi 1.1.1.2 x affine power",
28111            "Rubi 1.1.1.2 monomial multiplier negative-slope affine power",
28112            "Rubi 1.1.1.2 negative-slope affine power monomial multiplier",
28113            "Rubi 1.1.1.2 monomial negative-slope affine power",
28114            "Rubi 1.1.1.2 monomial negative-slope affine factor",
28115            "Rubi 1.1.1.2 x negative-slope affine power",
28116            "Rubi 1.1.1.2 derivative of x power over affine square root",
28117            "Rubi 1.1.1.2 expanded derivative of x power over affine square root",
28118        ];
28119
28120        for id in removed_ids {
28121            assert!(
28122                rubi_rules().iter().all(|rule| rule.id != id),
28123                "{id} should not preserve later-section monomial-affine shortcut coverage in 1.1.1.2",
28124            );
28125        }
28126    }
28127
28128    #[test]
28129    fn integrates_powered_four_affine_product_normalization() {
28130        assert_derivative_round_trip(parse!(
28131            "(5*(1 + 2*x)^2*(3 + 4*x)^2*(5 + 6*x)^2*(7 + 8*x)^2)^(3/2)"
28132        ));
28133    }
28134
28135    #[test]
28136    fn rubi_downvalue_173_uses_expand_to_sum() {
28137        let integrand = parse!("(3+4*x)^2*(5+6*x)/((1+2*x)*(7+8*x))");
28138        let x = symbol!("x");
28139        let rule = rubi_rules()
28140            .iter()
28141            .find(|rule| rule.downvalue_order == Some(173))
28142            .expect("Rubi DownValue 173 should be registered");
28143        let primitive = matcher_rule_for_test(&integrand, x, rule)
28144            .expect("Rubi DownValue 173 should match the affine quotient");
28145        let residual = (primitive.derivative(x) - integrand).together();
28146        assert!(
28147            residual_is_zero(&residual),
28148            "Rubi DownValue 173 derivative mismatch: {residual}"
28149        );
28150    }
28151
28152    #[test]
28153    fn rubi_downvalue_200_is_four_affine_terminal() {
28154        let integrand = parse!("(a+b*x)^m*(c+d*x)^n*(e+f*x)^p*(g+h*x)^q");
28155        let x = symbol!("x");
28156        let rule = rubi_rules()
28157            .iter()
28158            .find(|rule| rule.downvalue_order == Some(200))
28159            .expect("Rubi DownValue 200 should be registered");
28160        let result = matcher_rule_for_test(&integrand, x, rule)
28161            .expect("Rubi DownValue 200 should match the unresolved four-affine product");
28162        assert!(
28163            rubi_contains_unintegrable(&result),
28164            "terminal result: {result}"
28165        );
28166    }
28167
28168    #[test]
28169    fn welz_95_preserves_rubi_partial_four_affine_split() {
28170        let x = symbol!("x");
28171        let integrand = parse!("(2-(1+k)*x)/(((1-x)*x*(1-k*x))^(1/3)*(1-(1+k)*x))");
28172        let partial = integrate_deferred(integrand.as_view(), x)
28173            .expect("Rubi should preserve its partial block-22 result");
28174        let partial_text = partial.to_string();
28175
28176        assert!(
28177            partial_text.contains("appell_f1"),
28178            "the quotient branch should follow Rubi rule 133: {partial}"
28179        );
28180        assert!(
28181            partial_text.contains("unintegrable"),
28182            "the unresolved four-factor remainder should stay deferred: {partial}"
28183        );
28184    }
28185
28186    #[test]
28187    fn integrates_linear_power_expand_to_sum_normalization() {
28188        assert_derivative_round_trip(parse!("(2*(1 + x))^(3/2)"));
28189        assert_derivative_round_trip(parse!("(2*(1 + x))^m"));
28190    }
28191
28192    #[test]
28193    fn integrates_multi_linear_power_expand_to_sum_normalization() {
28194        assert_derivative_round_trip(parse!("(2*(1 - x))^(1/2)*(3*(1 + x))^(1/2)"));
28195    }
28196
28197    #[test]
28198    fn integrates_polynomial_two_opposite_affine_equal_powers_to_quadratic() {
28199        assert_derivative_round_trip(parse!("x*(1 + 2*x)^2*(1 - 2*x)^2"));
28200    }
28201
28202    #[test]
28203    fn integrates_polynomial_two_opposite_affine_equal_noninteger_powers_to_quadratic() {
28204        assert_derivative_round_trip(parse!("x*(1 + 2*x)^(1/2)*(-1 + 2*x)^(1/2)"));
28205    }
28206
28207    #[test]
28208    fn divides_polynomial_by_linear_affine() {
28209        let x = symbol!("x");
28210        let (quotient, remainder) = polynomial_quotient_remainder_linear(
28211            &parse!("7 + 25*x + 22*x^2"),
28212            Atom::num(1),
28213            Atom::num(2),
28214            x,
28215        )
28216        .expect("polynomial division should apply");
28217
28218        assert_eq!(quotient.expand(), parse!("7 + 11*x"));
28219        assert!(remainder.expand().is_zero());
28220    }
28221
28222    #[test]
28223    fn polynomial_division_removes_algebraic_zero_leading_terms() {
28224        let x = symbol!("x");
28225        let numerator = parse!("sqrt(3) - 2*x - 2*x^3 - sqrt(3)*x^4");
28226        let denominator = parse!("2 - sqrt(3) + 2*(1 + sqrt(3))*x + sqrt(3)*x^2");
28227        let (quotient, remainder) = polynomial_quotient_remainder(&numerator, &denominator, x)
28228            .expect("polynomial division with algebraic coefficients should apply");
28229        let residual = (&quotient * &denominator + &remainder - &numerator).expand();
28230
28231        assert!(
28232            rubi_algebraic_zero_q(&residual),
28233            "quotient/remainder should reconstruct the numerator; residual: {residual}"
28234        );
28235        assert!(
28236            polynomial_degree(&remainder, x)
28237                .zip(polynomial_degree(&denominator, x))
28238                .is_some_and(|(remainder_degree, denominator_degree)| {
28239                    remainder_degree < denominator_degree
28240                }),
28241            "remainder degree should be lower than denominator degree; remainder: {remainder}"
28242        );
28243    }
28244
28245    #[test]
28246    fn polynomial_division_handles_rational_dividends_like_mathematica() {
28247        let x = symbol!("x");
28248        let numerator = parse!("(d+e*x)^3");
28249        let rational_denominator = parse!("(f+g*x)^2");
28250        let polynomial_divisor = parse!("d^2-e^2*x^2");
28251        let (quotient, remainder) = polynomial_quotient_remainder_rational_dividend(
28252            &numerator,
28253            &rational_denominator,
28254            &polynomial_divisor,
28255            x,
28256        )
28257        .expect("Mathematica PolynomialQuotient/PolynomialRemainder semantics should apply");
28258        let residual =
28259            (&numerator / &rational_denominator - &quotient * &polynomial_divisor - &remainder)
28260                .together();
28261
28262        assert!(
28263            rubi_algebraic_zero_q(&residual),
28264            "rational quotient/remainder should reconstruct the dividend: {residual}"
28265        );
28266        assert_eq!(polynomial_degree(&remainder, x), Some(1));
28267    }
28268
28269    #[test]
28270    fn polynomial_quotient_wrappers_accept_laurent_dividends_like_mathematica() {
28271        let x = symbol!("x");
28272        let dividend = parse!("(-3*A+3*A*b*x^2/a-3*B*x+2*B*b*x^3/a)/x^3");
28273        let divisor = parse!("a+b*x^2");
28274
28275        assert_eq!(
28276            rubi_polynomial_quotient(&dividend, &divisor, x)
28277                .expect("Mathematica accepts the Laurent dividend")
28278                .together(),
28279            parse!("(-3*A-3*B*x+6*A*b*x^2/a)/(a*x^3)").together()
28280        );
28281        assert_eq!(
28282            rubi_polynomial_remainder(&dividend, &divisor, x)
28283                .expect("Mathematica returns a polynomial remainder")
28284                .together(),
28285            parse!("5*b*B/a-6*A*b^2*x/a^2").together()
28286        );
28287    }
28288
28289    #[test]
28290    fn polynomial_division_cancels_rational_polynomial_factors_like_mathematica() {
28291        let x = symbol!("x");
28292        let dividend = parse!("(1+x^2)*(-4*a-3*b+2*b/(1+x^2))");
28293        let divisor = parse!("a+b+a*x^2");
28294
28295        assert_eq!(
28296            rubi_polynomial_quotient(&dividend, &divisor, x)
28297                .expect("Mathematica cancels the rational factor before polynomial division")
28298                .together(),
28299            parse!("-4-3*b/a").together()
28300        );
28301        assert_eq!(
28302            rubi_polynomial_remainder(&dividend, &divisor, x)
28303                .expect("Mathematica returns the polynomial remainder after cancellation")
28304                .together(),
28305            parse!("6*b+3*b^2/a").together()
28306        );
28307    }
28308
28309    #[test]
28310    fn laurent_division_matches_mathematica_polynomial_quotient() {
28311        let x = symbol!("x");
28312        let (quotient, remainder) =
28313            laurent_quotient_remainder_by_polynomial(&parse!("(1+x^2)/x"), &parse!("1+x^3"), x)
28314                .expect("Mathematica accepts this Laurent dividend");
28315
28316        assert_eq!(quotient, parse!("1/x"));
28317        assert_eq!(remainder, parse!("x-x^2"));
28318    }
28319
28320    #[test]
28321    fn quadratic_negative_power_recurrence_follows_repeated_rubi_path() {
28322        assert_derivative_round_trip(parse!("(d+e*x)^3/((f+g*x)^2*(d^2-e^2*x^2)^(7/2))"));
28323    }
28324
28325    #[test]
28326    fn integrates_polynomial_multiplier_divisible_by_first_affine() {
28327        assert_derivative_round_trip(parse!("(7 + 25*x + 22*x^2)*(1 + 2*x)^2*(3 + 5*x)^2"));
28328    }
28329
28330    #[test]
28331    fn rubi_downvalue_2123_matches_factored_polynomial_multiplier() {
28332        let x = symbol!("x");
28333        let integrand = parse!("x*(1+x)*(1+2*x)^2*(3+5*x)");
28334        let rule = rubi_rules()
28335            .iter()
28336            .find(|rule| rule.downvalue_order == Some(2123))
28337            .expect("Rubi DownValue 2123 should be registered");
28338        let primitive = matcher_rule_for_test(&integrand, x, rule)
28339            .expect("Px__ should bind the factored polynomial multiplier");
28340        let residual = (primitive.derivative(x) - integrand).together();
28341        assert!(
28342            residual_is_zero(&residual),
28343            "Rubi DownValue 2123 derivative mismatch: {residual}"
28344        );
28345    }
28346
28347    #[test]
28348    fn rubi_downvalue_2120_preserves_star_multiplier() {
28349        let x = symbol!("x");
28350        let integrand = parse!("x*sqrt(1+2*x)*sqrt(1-2*x)");
28351        let rule = rubi_rules()
28352            .iter()
28353            .find(|rule| rule.downvalue_order == Some(2120))
28354            .expect("Rubi DownValue 2120 should be registered");
28355        let primitive = matcher_rule_for_test(&integrand, x, rule)
28356            .expect("Rubi DownValue 2120 should match equal noninteger affine powers");
28357        let residual = (primitive.derivative(x) - integrand).together();
28358        assert!(
28359            residual_is_zero(&residual),
28360            "Rubi DownValue 2120 derivative mismatch: {residual}"
28361        );
28362    }
28363
28364    #[test]
28365    fn integrates_polynomial_two_affine_integer_powers_expand_integrand() {
28366        assert_derivative_round_trip(parse!("x^3*(1 + 2*x)^2*(3 + 5*x)"));
28367    }
28368
28369    #[test]
28370    fn matches_single_affine_linear_argument_substitution_row() {
28371        let x = symbol!("x");
28372        let integrand = parse!("(1+2*(3+x))^2");
28373        let primitive = rubi_rules()
28374            .iter()
28375            .filter(|rule| rule.downvalue_order == Some(18))
28376            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
28377            .expect("linear-argument single-affine substitution row should apply");
28378        let residual = (primitive.derivative(x) - integrand).together();
28379        assert!(
28380            residual_is_zero(&residual),
28381            "primitive derivative mismatch: {residual}"
28382        );
28383    }
28384
28385    #[test]
28386    fn integrates_polynomial_three_affine_opposite_equal_powers_to_quadratic() {
28387        assert_derivative_round_trip(parse!("x*(1 + 2*x)^2*(1 - 2*x)^2*(3 + 5*x)"));
28388    }
28389
28390    #[test]
28391    fn rubi_downvalue_208_integrates_negative_three_halves_quadratic() {
28392        let x = symbol!("x");
28393        let integrand = parse!("1/(2+3*x^2)^(3/2)");
28394        let rule = rubi_rules()
28395            .iter()
28396            .find(|rule| rule.downvalue_order == Some(208))
28397            .expect("Rubi DownValue 208 should be registered");
28398        let primitive = matcher_rule_for_test(&integrand, x, rule)
28399            .expect("Rubi DownValue 208 should match the fixed quadratic power");
28400        let residual = (primitive.derivative(x) - integrand).together();
28401        assert!(
28402            residual_is_zero(&residual),
28403            "Rubi DownValue 208 derivative mismatch: {residual}; primitive: {primitive}"
28404        );
28405    }
28406
28407    #[test]
28408    fn rubi_downvalue_240_integrates_quadratic_log_derivative() {
28409        let x = symbol!("x");
28410        let integrand = parse!("x/(2+3*x^2)");
28411        let rule = rubi_rules()
28412            .iter()
28413            .find(|rule| rule.downvalue_order == Some(240))
28414            .expect("Rubi DownValue 240 should be registered");
28415        let primitive = matcher_rule_for_test(&integrand, x, rule)
28416            .expect("Rubi DownValue 240 should match the quadratic log derivative");
28417        let residual = (primitive.derivative(x) - integrand).together();
28418        assert!(
28419            residual_is_zero(&residual),
28420            "Rubi DownValue 240 derivative mismatch: {residual}; primitive: {primitive}"
28421        );
28422    }
28423
28424    #[test]
28425    fn rubi_downvalue_243_preserves_star_substitution() {
28426        let x = symbol!("x");
28427        let integrand = parse!("x/(1+x^2)^2");
28428        let rule = rubi_rules()
28429            .iter()
28430            .find(|rule| rule.downvalue_order == Some(243))
28431            .expect("Rubi DownValue 243 should be registered");
28432        let primitive = matcher_rule_for_test(&integrand, x, rule)
28433            .expect("Rubi DownValue 243 should perform the x^2 substitution");
28434        let residual = (primitive.derivative(x) - integrand).together();
28435        assert!(
28436            residual_is_zero(&residual),
28437            "Rubi DownValue 243 derivative mismatch: {residual}; primitive: {primitive}"
28438        );
28439    }
28440
28441    #[test]
28442    fn rubi_downvalue_291_preserves_quadratic_substitution() {
28443        let x = symbol!("x");
28444        let integrand = parse!("1/(sqrt(1+x^2)*(2+3*x^2))");
28445        let rule = rubi_rules()
28446            .iter()
28447            .find(|rule| rule.downvalue_order == Some(291))
28448            .expect("Rubi DownValue 291 should be registered");
28449        let primitive = matcher_rule_for_test(&integrand, x, rule)
28450            .expect("Rubi DownValue 291 should perform the quadratic substitution");
28451        let residual = (primitive.derivative(x) - integrand).together();
28452        assert!(
28453            residual_is_zero(&residual),
28454            "Rubi DownValue 291 derivative mismatch: {residual}; primitive: {primitive}"
28455        );
28456    }
28457
28458    #[test]
28459    fn rubi_downvalue_303_preserves_partial_fraction_stars() {
28460        let x = symbol!("x");
28461        let integrand = parse!("1/((1+x^2)*(2+3*x^2))");
28462        let rule = rubi_rules()
28463            .iter()
28464            .find(|rule| rule.downvalue_order == Some(303))
28465            .expect("Rubi DownValue 303 should be registered");
28466        let primitive = matcher_rule_for_test(&integrand, x, rule)
28467            .expect("Rubi DownValue 303 should split the quadratic factors");
28468        let residual = (primitive.derivative(x) - integrand).together();
28469        assert!(
28470            residual_is_zero(&residual),
28471            "Rubi DownValue 303 derivative mismatch: {residual}; primitive: {primitive}"
28472        );
28473    }
28474
28475    #[test]
28476    fn rubi_downvalue_327_matches_normalized_symbolic_quadratic_ratio() {
28477        let x = symbol!("sub1");
28478        let integrand = parse!(
28479            "sqrt(1+sub1^2*sqrt(-1/d^2)/sqrt(4*c*a-b^2))\
28480             /sqrt(1+sub1^2/(d^2*sqrt(-1/d^2)*sqrt(4*c*a-b^2)))"
28481        );
28482        let rule = rubi_rules()
28483            .iter()
28484            .find(|rule| rule.downvalue_order == Some(327))
28485            .expect("Rubi DownValue 327 should be registered");
28486        assert!(
28487            matcher_rule_for_test(&integrand, x, rule).is_some(),
28488            "Rubi DownValue 327 should match the normalized quadratic ratio"
28489        );
28490    }
28491
28492    #[test]
28493    fn rubi_downvalue_333_returns_appell_terminal_form() {
28494        let x = symbol!("x");
28495        let integrand = parse!("(1+x^2)^(1/3)*(2+3*x^2)^(1/5)");
28496        let rule = rubi_rules()
28497            .iter()
28498            .find(|rule| rule.downvalue_order == Some(333))
28499            .expect("Rubi DownValue 333 should be registered");
28500        let primitive = matcher_rule_for_test(&integrand, x, rule)
28501            .expect("Rubi DownValue 333 should return an AppellF1 form");
28502        assert!(
28503            rubi_contains_function_symbol(&primitive, rubi_symbols().appell_f1),
28504            "Rubi DownValue 333 should contain AppellF1: {primitive}"
28505        );
28506        assert!(
28507            rubi_integral_free_q(&primitive),
28508            "Rubi DownValue 333 should be terminal: {primitive}"
28509        );
28510    }
28511
28512    #[test]
28513    fn rubi_downvalue_338_preserves_quadratic_substitution() {
28514        let x = symbol!("x");
28515        let integrand = parse!("x^5*(1+x^2)^2*(1-x^2)^2");
28516        let rule = rubi_rules()
28517            .iter()
28518            .find(|rule| rule.downvalue_order == Some(338))
28519            .expect("Rubi DownValue 338 should be registered");
28520        let primitive = matcher_rule_for_test(&integrand, x, rule)
28521            .expect("Rubi DownValue 338 should perform the x^2 substitution");
28522        let residual = (primitive.derivative(x) - integrand).together();
28523        assert!(
28524            residual_is_zero(&residual),
28525            "Rubi DownValue 338 derivative mismatch: {residual}; primitive: {primitive}"
28526        );
28527    }
28528
28529    #[test]
28530    fn rubi_downvalue_363_preserves_recurrence_identity() {
28531        let x = symbol!("x");
28532        let integrand = parse!("x^2*(1+x^2)^2*(2+3*x^2)");
28533        let rule = rubi_rules()
28534            .iter()
28535            .find(|rule| rule.downvalue_order == Some(363))
28536            .expect("Rubi DownValue 363 should be registered");
28537        let primitive = matcher_rule_for_test(&integrand, x, rule)
28538            .expect("Rubi DownValue 363 should apply its recurrence");
28539        let residual = (primitive.derivative(x) - integrand).together();
28540        assert!(
28541            residual_is_zero(&residual),
28542            "Rubi DownValue 363 derivative mismatch: {residual}; primitive: {primitive}"
28543        );
28544    }
28545
28546    #[test]
28547    fn rubi_downvalue_394_returns_appell_terminal_form() {
28548        let x = symbol!("x");
28549        let integrand = parse!("x^2*(1+x^2)^(1/3)*(2+3*x^2)^(1/5)");
28550        let rule = rubi_rules()
28551            .iter()
28552            .find(|rule| rule.downvalue_order == Some(394))
28553            .expect("Rubi DownValue 394 should be registered");
28554        let primitive = matcher_rule_for_test(&integrand, x, rule)
28555            .expect("Rubi DownValue 394 should return an AppellF1 form");
28556        assert!(
28557            rubi_contains_function_symbol(&primitive, rubi_symbols().appell_f1),
28558            "Rubi DownValue 394 should contain AppellF1: {primitive}"
28559        );
28560        assert!(
28561            rubi_integral_free_q(&primitive),
28562            "Rubi DownValue 394 should be terminal: {primitive}"
28563        );
28564    }
28565
28566    #[test]
28567    fn rubi_1_1_2_5_has_exact_4_17_3_downvalue_orders() {
28568        let _ = parse!("x");
28569        let mut orders: Vec<_> = rubi_rules()
28570            .iter()
28571            .filter_map(|rule| {
28572                rule.downvalue_order
28573                    .filter(|order| (396..=434).contains(order))
28574            })
28575            .collect();
28576        orders.sort_unstable();
28577        assert_eq!(orders, (396..=434).collect::<Vec<_>>());
28578    }
28579
28580    #[test]
28581    fn rubi_downvalue_397_preserves_partial_fraction_identity() {
28582        let x = symbol!("x");
28583        let integrand = parse!("(5+7*x^2)/((1+2*x^2)*(3+4*x^2))");
28584        let rule = rubi_rules()
28585            .iter()
28586            .find(|rule| rule.downvalue_order == Some(397))
28587            .expect("Rubi DownValue 397 should be registered");
28588        let primitive = matcher_rule_for_test(&integrand, x, rule)
28589            .expect("Rubi DownValue 397 should split the quadratic factors");
28590        let residual = (primitive.derivative(x) - integrand).together();
28591        assert!(
28592            residual_is_zero(&residual),
28593            "Rubi DownValue 397 derivative mismatch: {residual}; primitive: {primitive}"
28594        );
28595    }
28596
28597    #[test]
28598    fn rubi_downvalue_401_preserves_quadratic_recurrence_identity() {
28599        let x = symbol!("x");
28600        let integrand = parse!("(3+5*x^2)*(1+x^2)^-2*(2+3*x^2)");
28601        let rule = rubi_rules()
28602            .iter()
28603            .find(|rule| rule.downvalue_order == Some(401))
28604            .expect("Rubi DownValue 401 should be registered");
28605        let primitive = matcher_rule_for_test(&integrand, x, rule)
28606            .expect("Rubi DownValue 401 should apply its recurrence");
28607        let residual = (primitive.derivative(x) - integrand).together();
28608        assert!(
28609            residual_is_zero(&residual),
28610            "Rubi DownValue 401 derivative mismatch: {residual}; primitive: {primitive}"
28611        );
28612    }
28613
28614    #[test]
28615    fn rubi_downvalue_434_returns_unintegrable_terminal_form() {
28616        let x = symbol!("x");
28617        let integrand = parse!("(1+x^2)^(1/3)*(2+3*x^2)^(1/5)*(4+5*x^2)^(1/7)");
28618        let rule = rubi_rules()
28619            .iter()
28620            .find(|rule| rule.downvalue_order == Some(434))
28621            .expect("Rubi DownValue 434 should be registered");
28622        let primitive = matcher_rule_for_test(&integrand, x, rule)
28623            .expect("Rubi DownValue 434 should return unintegrable");
28624        assert!(
28625            rubi_contains_function_symbol(&primitive, rubi_symbols().unintegrable),
28626            "Rubi DownValue 434 should contain unintegrable: {primitive}"
28627        );
28628    }
28629
28630    #[test]
28631    fn rubi_1_1_2_6_has_exact_4_17_3_downvalue_orders() {
28632        let _ = parse!("x");
28633        let mut orders: Vec<_> = rubi_rules()
28634            .iter()
28635            .filter_map(|rule| {
28636                rule.downvalue_order
28637                    .filter(|order| (435..=450).contains(order))
28638            })
28639            .collect();
28640        orders.sort_unstable();
28641        assert_eq!(orders, (435..=450).collect::<Vec<_>>());
28642    }
28643
28644    #[test]
28645    fn rubi_downvalue_435_preserves_quadratic_substitution() {
28646        let x = symbol!("x");
28647        let integrand = parse!("x^3*(1+x^2)*(2+3*x^2)*(4+5*x^2)");
28648        let rule = rubi_rules()
28649            .iter()
28650            .find(|rule| rule.downvalue_order == Some(435))
28651            .expect("Rubi DownValue 435 should be registered");
28652        let primitive = matcher_rule_for_test(&integrand, x, rule)
28653            .expect("Rubi DownValue 435 should perform the x^2 substitution");
28654        let residual = (primitive.derivative(x) - integrand).together();
28655        assert!(
28656            residual_is_zero(&residual),
28657            "Rubi DownValue 435 derivative mismatch: {residual}; primitive: {primitive}"
28658        );
28659    }
28660
28661    #[test]
28662    fn rubi_downvalue_450_returns_unintegrable_terminal_form() {
28663        let x = symbol!("x");
28664        let integrand = parse!("x^(1/5)*(1+x^2)^(1/3)*(2+3*x^2)^(1/7)*(4+5*x^2)^(1/11)");
28665        let rule = rubi_rules()
28666            .iter()
28667            .find(|rule| rule.downvalue_order == Some(450))
28668            .expect("Rubi DownValue 450 should be registered");
28669        let primitive = matcher_rule_for_test(&integrand, x, rule)
28670            .expect("Rubi DownValue 450 should return unintegrable");
28671        assert!(
28672            rubi_contains_function_symbol(&primitive, rubi_symbols().unintegrable),
28673            "Rubi DownValue 450 should contain unintegrable: {primitive}"
28674        );
28675    }
28676
28677    #[test]
28678    fn conditional_match_q_supports_rubi_nested_optional_polynomial_factor() {
28679        let x = symbol!("x");
28680        let symbols = rubi_symbols();
28681        let pattern = Atom::var(symbols.qx__)
28682            * (Atom::var(symbols.c__)
28683                + Atom::var(symbols.d__) * Atom::var(x).pow(Atom::var(symbols.m_)))
28684            .pow(Atom::var(symbols.q_));
28685        let expression = parse!("(1+x)*(3+5*x^3)^2");
28686
28687        assert!(rubi_conditional_match_q(
28688            &expression,
28689            pattern,
28690            &[symbols.qx__, symbols.d__],
28691            |matches| {
28692                wildcard_atom(matches, symbols.qx__) == Some(parse!("1+x"))
28693                    && wildcard_atom(matches, symbols.c__) == Some(Atom::num(3))
28694                    && wildcard_atom(matches, symbols.d__) == Some(Atom::num(5))
28695                    && wildcard_atom(matches, symbols.m_) == Some(Atom::num(3))
28696                    && wildcard_atom(matches, symbols.q_) == Some(Atom::num(2))
28697            },
28698        ));
28699    }
28700
28701    #[test]
28702    fn rubi_downvalue_2024_preserves_star_substitution() {
28703        let x = symbol!("x");
28704        let integrand = parse!("2*x/(2+x^2)");
28705        let rule = rubi_rules()
28706            .iter()
28707            .find(|rule| rule.downvalue_order == Some(2024))
28708            .expect("Rubi DownValue 2024 should be registered");
28709        let primitive = matcher_rule_for_test(&integrand, x, rule)
28710            .expect("Rubi DownValue 2024 should perform the polynomial substitution");
28711        let residual = (primitive.derivative(x) - integrand).together();
28712        assert!(
28713            residual_is_zero(&residual),
28714            "Rubi DownValue 2024 derivative mismatch: {residual}; primitive: {primitive}"
28715        );
28716    }
28717
28718    #[test]
28719    fn rubi_downvalue_2025_preserves_star_substitution() {
28720        let x = symbol!("x");
28721        let integrand = parse!("2*x/(3+3*(1+x^2)+(1+x^2)^2)");
28722        let rule = rubi_rules()
28723            .iter()
28724            .find(|rule| rule.downvalue_order == Some(2025))
28725            .expect("Rubi DownValue 2025 should be registered");
28726        let primitive = matcher_rule_for_test(&integrand, x, rule)
28727            .expect("Rubi DownValue 2025 should perform the polynomial substitution");
28728        let residual = (primitive.derivative(x) - integrand).together();
28729        assert!(
28730            residual_is_zero(&residual),
28731            "Rubi DownValue 2025 derivative mismatch: {residual}; primitive: {primitive}"
28732        );
28733    }
28734
28735    #[test]
28736    fn rubi_downvalue_2236_keeps_mathematica_degenerate_parameter_domain() {
28737        let x = symbol!("x");
28738        let integrand = parse!("x^5/((1+x^2)*sqrt(1+3*x^2+2*x^4))");
28739        let rule = rubi_rules()
28740            .iter()
28741            .find(|rule| rule.downvalue_order == Some(2236))
28742            .expect("Rubi DownValue 2236 should be registered");
28743
28744        assert!(
28745            matcher_rule_for_test(&integrand, x, rule).is_some(),
28746            "Rubi DownValue 2236 has no nonzero condition on c*d^2-b*d*e+a*e^2"
28747        );
28748    }
28749
28750    #[test]
28751    fn rubi_downvalue_2237_keeps_mathematica_degenerate_parameter_domain() {
28752        let x = symbol!("x");
28753        let integrand = parse!("x^5/((1+x^2)*sqrt(1-x^4))");
28754        let rule = rubi_rules()
28755            .iter()
28756            .find(|rule| rule.downvalue_order == Some(2237))
28757            .expect("Rubi DownValue 2237 should be registered");
28758
28759        assert!(
28760            matcher_rule_for_test(&integrand, x, rule).is_some(),
28761            "Rubi DownValue 2237 has no nonzero condition on c*d^2+a*e^2"
28762        );
28763    }
28764
28765    #[test]
28766    fn rubi_downvalue_2113_preserves_star_multiplier() {
28767        let x = symbol!("x");
28768        let integrand = parse!("2*x*sqrt(1-2*x)*sqrt(1+2*x)");
28769        let rule = rubi_rules()
28770            .iter()
28771            .find(|rule| rule.downvalue_order == Some(2113))
28772            .expect("Rubi DownValue 2113 should be registered");
28773        let primitive = matcher_rule_for_test(&integrand, x, rule)
28774            .expect("Rubi DownValue 2113 should match equal noninteger affine powers");
28775        let residual = (primitive.derivative(x) - integrand).together();
28776        assert!(
28777            residual_is_zero(&residual),
28778            "Rubi DownValue 2113 derivative mismatch: {residual}"
28779        );
28780    }
28781
28782    #[test]
28783    fn rubi_downvalue_2115_matches_factored_polynomial_multiplier() {
28784        let x = symbol!("x");
28785        let integrand = parse!("x*(1+x)*(1+2*x)^2*(3+5*x)*(7+11*x)");
28786        let rule = rubi_rules()
28787            .iter()
28788            .find(|rule| rule.downvalue_order == Some(2115))
28789            .expect("Rubi DownValue 2115 should be registered");
28790        let primitive = matcher_rule_for_test(&integrand, x, rule)
28791            .expect("Px__ should bind the factored polynomial multiplier");
28792        let residual = (primitive.derivative(x) - integrand).together();
28793        assert!(
28794            residual_is_zero(&residual),
28795            "Rubi DownValue 2115 derivative mismatch: {residual}"
28796        );
28797    }
28798
28799    #[test]
28800    fn rubi_1_1_1_7_has_exact_4_17_3_downvalue_orders() {
28801        let _ = parse!("x");
28802        let orders: Vec<_> = rubi_rules()
28803            .iter()
28804            .filter_map(|rule| {
28805                rule.downvalue_order
28806                    .filter(|order| (2097..=2111).contains(order))
28807            })
28808            .collect();
28809        assert_eq!(
28810            orders,
28811            (2097..=2111).collect::<Vec<_>>(),
28812            "section 1.1.1.7 must contain exactly the fifteen Rubi 4.17.3 DownValues"
28813        );
28814    }
28815
28816    #[test]
28817    fn rubi_downvalue_2097_matches_linear_polynomial_multiplier() {
28818        let x = symbol!("x");
28819        let integrand = parse!("x*(14/9+x)/(sqrt(1+x)*sqrt(2+x)*sqrt(-2/3+x))");
28820        let rule = rubi_rules()
28821            .iter()
28822            .find(|rule| rule.downvalue_order == Some(2097))
28823            .expect("Rubi DownValue 2097 should be registered");
28824        let primitive = matcher_rule_for_test(&integrand, x, rule)
28825            .expect("Rubi DownValue 2097 should match its linear polynomial multiplier");
28826        let residual = (primitive.derivative(x) - integrand).together();
28827        assert!(
28828            residual_is_zero(&residual),
28829            "Rubi DownValue 2097 derivative mismatch: {residual}"
28830        );
28831    }
28832
28833    #[test]
28834    fn integrates_polynomial_three_affine_opposite_equal_noninteger_powers_to_quadratic() {
28835        assert_derivative_round_trip(parse!("x*(1 + 2*x)^(1/2)*(1 - 2*x)^(1/2)*(3 + 5*x)"));
28836    }
28837
28838    #[test]
28839    fn integrates_polynomial_three_affine_multiplier_divisible_by_first_affine() {
28840        assert_derivative_round_trip(parse!("(x + 2*x^2)*(1 + 2*x)^2*(3 + 5*x)^2*(7 + 11*x)^2"));
28841    }
28842
28843    #[test]
28844    fn integrates_polynomial_three_affine_integer_first_second_expand_integrand() {
28845        assert_derivative_round_trip(parse!("x^3*(1 + 2*x)^2*(3 + 5*x)^2*(7 + 11*x)^2"));
28846    }
28847
28848    #[test]
28849    fn integrates_polynomial_three_affine_negative_first_power_recurrence() {
28850        assert_derivative_round_trip(parse!(
28851            "(-20 - 106*x - 120*x^2)*(1 + 2*x)^(-2)*(1 + 5*x)^(1/2)*(1 + 3*x)^(1/2)"
28852        ));
28853    }
28854
28855    #[test]
28856    fn integrates_polynomial_monomial_binomial_positive_power_reduction() {
28857        assert_derivative_round_trip(parse!("(1 + x^2)*(1 + 2*x^3)^2"));
28858    }
28859
28860    #[test]
28861    fn rejects_nondivisible_radical_polynomial_power_product_without_zero_test_hang() {
28862        let x = symbol!("x");
28863        let integrand = parse!("(1+2^(1/3)*x)/(1-2^(1/3)*x+4^(1/3)*x^2)");
28864        let primitive = rubi_rules()
28865            .iter()
28866            .filter(|rule| {
28867                rule.id == "Rubi 1.1.1.7.2"
28868                    && rule.block == Some(4)
28869                    && rule.source_pattern == Some("Int[u_.*Px_^p_.*Qx_^q_.,x_Symbol]")
28870            })
28871            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule));
28872
28873        assert!(
28874            primitive.is_none(),
28875            "Rubi block 4 should reject because PolynomialRemainder[Px,Qx,x] is nonzero"
28876        );
28877    }
28878
28879    #[test]
28880    fn rejects_nondivisible_symbolic_biquadratic_power_product_quickly() {
28881        let x = symbol!("sub2");
28882        let integrand = parse!(
28883            "(1/2*a*sub2^2*(16*a^2*b^2-3*a^4+127*b^4)-1/4*(258*a^2*b^4-67*a^4*b^2+12*a^6+77*b^6)-1/2*a^2*(16*a^2*b^2-3*a^4+127*b^4))/(2*a*sub2^2-a^2+b^2-sub2^4)"
28884        );
28885        let primitive = rubi_rules()
28886            .iter()
28887            .filter(|rule| {
28888                rule.id == "Rubi 1.1.1.7.2"
28889                    && rule.block == Some(4)
28890                    && rule.source_pattern == Some("Int[u_.*Px_^p_.*Qx_^q_.,x_Symbol]")
28891            })
28892            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule));
28893
28894        assert!(
28895            primitive.is_none(),
28896            "Rubi block 4 should reject the nonzero symbolic PolynomialRemainder"
28897        );
28898    }
28899
28900    #[test]
28901    fn integrates_radical_linear_over_quadratic_via_rubi_quadratic_split() {
28902        assert_derivative_round_trip(parse!("(1+2^(1/3)*x)/(1-2^(1/3)*x+4^(1/3)*x^2)"));
28903    }
28904
28905    #[test]
28906    fn block4_rejects_constant_polynomial_qx_candidates() {
28907        let x = symbol!("x");
28908        let integrand = parse!("(1 + x)^(-1)*2");
28909        let primitive = rubi_rules()
28910            .iter()
28911            .filter(|rule| {
28912                rule.id == "Rubi 1.1.1.7.2"
28913                    && rule.block == Some(4)
28914                    && rule.source_pattern == Some("Int[u_.*Px_^p_.*Qx_^q_.,x_Symbol]")
28915            })
28916            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule));
28917
28918        assert!(
28919            primitive.is_none(),
28920            "Rubi block 4 should not use constant-polynomial Qx candidates"
28921        );
28922    }
28923
28924    #[test]
28925    fn normalizes_divisible_polynomial_power_product_after_zero_coefficient_cleanup() {
28926        let x = symbol!("x");
28927        let integrand = parse!("x^4/(a+x^4*(2+2*c-2*(1+c)))^(1/2)");
28928        let primitive = integrate(&integrand, x).expect("Rubi block 4 normalization should apply");
28929        let expected_integrand = parse!("x^4/a^(1/2)");
28930        let residual = (primitive.derivative(x) - expected_integrand).together();
28931        assert!(
28932            residual_is_zero(&residual),
28933            "primitive derivative mismatch: {residual}"
28934        );
28935    }
28936
28937    #[test]
28938    fn applies_positive_affine_power_quadratic_numerator_over_three_square_roots() {
28939        let x = symbol!("x");
28940        let integrand = parse!("(1 + x)*(2 + 5*x + 3*x^2)/(sqrt(x)*sqrt(x)*sqrt(x))");
28941        let primitive = integrate(&integrand, x).expect("block 18 full quadratic row should apply");
28942        let residual = (primitive.derivative(x) - integrand).together();
28943        assert!(
28944            residual_is_zero(&residual),
28945            "primitive derivative mismatch: {residual}"
28946        );
28947    }
28948
28949    #[test]
28950    fn applies_positive_affine_power_quadratic_numerator_without_linear_term() {
28951        let x = symbol!("x");
28952        let integrand = parse!("(1 + x)*(2 + 3*x^2)/(sqrt(x)*sqrt(x)*sqrt(x))");
28953        let primitive = integrate(&integrand, x).expect("block 18 omitted-linear row should apply");
28954        let residual = (primitive.derivative(x) - integrand).together();
28955        assert!(
28956            residual_is_zero(&residual),
28957            "primitive derivative mismatch: {residual}"
28958        );
28959    }
28960
28961    #[test]
28962    fn applies_quadratic_numerator_over_four_square_roots_split() {
28963        let x = symbol!("x");
28964        let integrand = parse!("(2 + 5*x + 3*x^2)/(sqrt(1+x)*sqrt(x)*sqrt(x)*sqrt(x))");
28965        let primitive = integrate(&integrand, x).expect("block 19 full quadratic row should apply");
28966        let residual = (primitive.derivative(x) - integrand).together();
28967        assert!(
28968            residual_is_zero(&residual),
28969            "primitive derivative mismatch: {residual}"
28970        );
28971    }
28972
28973    #[test]
28974    fn applies_quadratic_numerator_without_linear_term_over_four_square_roots_split() {
28975        let x = symbol!("x");
28976        let integrand = parse!("(2 + 3*x^2)/(sqrt(1+x)*sqrt(x)*sqrt(x)*sqrt(x))");
28977        let primitive = integrate(&integrand, x).expect("block 19 omitted-linear row should apply");
28978        let residual = (primitive.derivative(x) - integrand).together();
28979        assert!(
28980            residual_is_zero(&residual),
28981            "primitive derivative mismatch: {residual}"
28982        );
28983    }
28984
28985    #[test]
28986    fn applies_negative_affine_power_linear_numerator_over_three_square_roots() {
28987        let x = symbol!("x");
28988        let integrand = parse!("x*(1 + x)^(-2)/(sqrt(x)*sqrt(x)*sqrt(x))");
28989        let primitive =
28990            integrate(&integrand, x).expect("block 17 negative affine-power row should apply");
28991        let residual = (primitive.derivative(x) - integrand).together();
28992        assert!(
28993            residual_is_zero(&residual),
28994            "primitive derivative mismatch: {residual}"
28995        );
28996    }
28997
28998    #[test]
28999    fn rejects_visible_x_factor_quadratic_binomial_zero_constant_term_reduction() {
29000        let x = symbol!("x");
29001        assert!(visible_integer_power_of_variable_factor(
29002            parse!("x*(1 + x)").as_view(),
29003            x
29004        ));
29005        assert!(visible_integer_power_of_variable_factor(
29006            parse!("2*x^3").as_view(),
29007            x
29008        ));
29009        assert!(!visible_integer_power_of_variable_factor(
29010            parse!("x + x^2").as_view(),
29011            x
29012        ));
29013
29014        let integrand = parse!("x*(1 + x)*(2 + 3*x^2)^2");
29015        let primitive = rubi_rules()
29016            .iter()
29017            .filter(|rule| rule.id == "Rubi 1.1.2.x.2")
29018            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule));
29019        assert!(
29020            primitive.is_none(),
29021            "Rubi guard should reject an already visible x^m*u multiplier"
29022        );
29023    }
29024
29025    #[test]
29026    fn rejects_constant_quadratic_binomial_divisor() {
29027        let x = symbol!("x");
29028        assert_eq!(
29029            polynomial_degree(&(Atom::num(2) + Atom::num(0) * Atom::var(x).pow(2)), x),
29030            Some(0),
29031            "zero quadratic coefficient should be treated as a__ constant divisor"
29032        );
29033    }
29034
29035    #[test]
29036    fn rejects_odd_polynomial_quadratic_binomial_negative_half_integer_recurrence() {
29037        let x = symbol!("x");
29038        let integrand = parse!("(1 + x)*(1 + x^2)^(-3/2)");
29039        let primitive = rubi_rules()
29040            .iter()
29041            .filter(|rule| rule.id == "Rubi 1.1.2.x.4.1")
29042            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule));
29043        assert!(
29044            primitive.is_none(),
29045            "PolyQ[Pq,x^2] should reject odd-degree polynomial terms"
29046        );
29047    }
29048
29049    #[test]
29050    fn integrates_even_monomial_negative_half_integer_quadratic_binomial_regression() {
29051        assert_derivative_round_trip(parse!("x^4/(10^(1/2)-x^2)^(9/2)"));
29052    }
29053
29054    #[test]
29055    fn matches_rubi_8_6_affine_incomplete_gamma() {
29056        let x = symbol!("x");
29057        let x_atom = Atom::var(x);
29058        let a = Atom::var(symbol!("a"));
29059        let b = Atom::var(symbol!("b"));
29060        let m = Atom::var(symbol!("m"));
29061        let n = Atom::var(symbol!("n"));
29062        let p = Atom::var(symbol!("p"));
29063        let integrand = rubi_gamma(1 + p, -&a * (1 + &m) / (&b * &n) - x_atom * (1 + m) / n);
29064        let rule = rubi_rules()
29065            .iter()
29066            .find(|rule| rule.downvalue_order == Some(7111))
29067            .expect("latest Rubi incomplete-Gamma affine rule should be registered");
29068
29069        assert!(
29070            matcher_rule_for_test(&integrand, x, rule).is_some(),
29071            "latest Rubi rule 7111 should match an affine incomplete-Gamma argument"
29072        );
29073        assert!(
29074            integrate(&integrand, x).is_ok(),
29075            "the full rule scan should reach latest Rubi rule 7111"
29076        );
29077    }
29078
29079    #[test]
29080    fn integrates_symbolic_power_sum_without_normalization_recursion() {
29081        let x = symbol!("x");
29082        for integrand in [
29083            parse!("x^m*(d-c^2*d*x^2)^3*(a+b*asin(c*x))"),
29084            parse!("cot(x)*(1+(1-8*tan(x)^2)^(1/3))/(cos(x)^2*(1-8*tan(x)^2)^(2/3))"),
29085        ] {
29086            assert!(
29087                integrate(&integrand, x).is_ok(),
29088                "latest Rubi path should terminate for {integrand}"
29089            );
29090        }
29091    }
29092
29093    #[test]
29094    fn matches_general_binomial_negative_balance_recurrence() {
29095        let x = symbol!("x");
29096        let integrand = parse!("(1 + x^2)^(-5/2)");
29097        let primitive = rubi_rules()
29098            .iter()
29099            .filter(|rule| rule.downvalue_order == Some(777))
29100            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29101            .expect("general binomial negative-balance recurrence should apply");
29102        let residual = (primitive.derivative(x) - integrand).together();
29103        assert!(
29104            residual_is_zero(&residual),
29105            "primitive derivative mismatch: {residual}"
29106        );
29107    }
29108
29109    #[test]
29110    fn matches_general_binomial_negative_monomial_power_integer_expansion() {
29111        let x = symbol!("x");
29112        let integrand = parse!("(1 + x^(-1))^2");
29113        let primitive = rubi_rules()
29114            .iter()
29115            .filter(|rule| rule.downvalue_order == Some(772))
29116            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29117            .expect("general binomial negative monomial power expansion should apply");
29118        let residual = (primitive.derivative(x) - integrand).together();
29119        assert!(
29120            residual_is_zero(&residual),
29121            "primitive derivative mismatch: {residual}"
29122        );
29123    }
29124
29125    #[test]
29126    fn matches_general_binomial_positive_exponent_recurrence() {
29127        let x = symbol!("x");
29128        let integrand = parse!("(1 + x^2)^(1/2)");
29129        let primitive = rubi_rules()
29130            .iter()
29131            .filter(|rule| rule.downvalue_order == Some(748))
29132            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29133            .expect("general binomial positive exponent recurrence should apply");
29134        let residual = (primitive.derivative(x) - integrand).together();
29135        assert!(
29136            residual_is_zero(&residual),
29137            "primitive derivative mismatch: {residual}"
29138        );
29139    }
29140
29141    #[test]
29142    fn matches_general_binomial_negative_power_recurrence() {
29143        let x = symbol!("x");
29144        let integrand = parse!("(1 + x^3)^(-2)");
29145        let primitive = rubi_rules()
29146            .iter()
29147            .filter(|rule| rule.downvalue_order == Some(749))
29148            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29149            .expect("general binomial negative-power recurrence should apply");
29150        let residual = (primitive.derivative(x) - integrand).together();
29151        assert!(
29152            residual_is_zero(&residual),
29153            "primitive derivative mismatch: {residual}"
29154        );
29155    }
29156
29157    #[test]
29158    fn matches_cubic_binomial_reciprocal_decomposition() {
29159        let x = symbol!("x");
29160        let integrand = parse!("1/(1 + x^3)");
29161        let primitive = rubi_rules()
29162            .iter()
29163            .filter(|rule| rule.downvalue_order == Some(750))
29164            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29165            .expect("cubic binomial reciprocal decomposition should apply");
29166        let residual = (primitive.derivative(x) - integrand).together();
29167        assert!(
29168            residual_is_zero(&residual),
29169            "primitive derivative mismatch: {residual}"
29170        );
29171    }
29172
29173    #[test]
29174    fn cubic_binomial_reciprocal_uses_rubi_rt_for_negative_rational_root() {
29175        let x = symbol!("x");
29176        let integrand = parse!("1/(-4/3 + 8/3*x^3)");
29177        let primitive = rubi_rules()
29178            .iter()
29179            .filter(|rule| rule.downvalue_order == Some(750))
29180            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29181            .expect("cubic binomial reciprocal decomposition should apply");
29182
29183        assert!(
29184            !primitive.to_string().contains("(-4/3)^(1/3)"),
29185            "Rubi Rt[-4/3,3] should not be emitted as a plain fractional power: {primitive}"
29186        );
29187        let residual = (primitive.derivative(x) - integrand).together();
29188        assert!(
29189            residual_is_zero(&residual),
29190            "primitive derivative mismatch: {residual}"
29191        );
29192    }
29193
29194    #[test]
29195    fn matches_positive_odd_binomial_reciprocal_decomposition() {
29196        let x = symbol!("x");
29197        let integrand = parse!("1/(1 + x^5)");
29198        let primitive = rubi_rules()
29199            .iter()
29200            .filter(|rule| rule.downvalue_order == Some(751))
29201            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29202            .expect("positive odd binomial reciprocal decomposition should apply");
29203        let residual = (primitive.derivative(x) - integrand).together();
29204        assert!(
29205            residual_is_zero(&residual),
29206            "primitive derivative mismatch: {residual}"
29207        );
29208    }
29209
29210    #[test]
29211    fn matches_negative_odd_binomial_reciprocal_decomposition() {
29212        let x = symbol!("x");
29213        let integrand = parse!("1/(-1 + x^5)");
29214        let primitive = rubi_rules()
29215            .iter()
29216            .filter(|rule| rule.downvalue_order == Some(752))
29217            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29218            .expect("negative odd binomial reciprocal decomposition should apply");
29219        let residual = (primitive.derivative(x) - integrand).together();
29220        assert!(
29221            residual_is_zero(&residual),
29222            "primitive derivative mismatch: {residual}"
29223        );
29224    }
29225
29226    #[test]
29227    fn matches_positive_even_binomial_reciprocal_decomposition() {
29228        let x = symbol!("x");
29229        let integrand = parse!("1/(1 + x^6)");
29230        let primitive = rubi_rules()
29231            .iter()
29232            .filter(|rule| rule.downvalue_order == Some(753))
29233            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29234            .expect("positive even binomial reciprocal decomposition should apply");
29235        let residual = (primitive.derivative(x) - integrand).together();
29236        assert!(
29237            residual_is_zero(&residual),
29238            "primitive derivative mismatch: {residual}"
29239        );
29240    }
29241
29242    #[test]
29243    fn matches_negative_even_binomial_reciprocal_decomposition() {
29244        let x = symbol!("x");
29245        let integrand = parse!("1/(1 - x^6)");
29246        let primitive = rubi_rules()
29247            .iter()
29248            .filter(|rule| rule.downvalue_order == Some(754))
29249            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29250            .expect("negative even binomial reciprocal decomposition should apply");
29251        let residual = (primitive.derivative(x) - integrand).together();
29252        assert!(
29253            residual_is_zero(&residual),
29254            "primitive derivative mismatch: {residual}"
29255        );
29256    }
29257
29258    #[test]
29259    fn matches_positive_quartic_binomial_reciprocal_split() {
29260        let x = symbol!("x");
29261        let integrand = parse!("1/(1 + x^4)");
29262        let primitive = rubi_rules()
29263            .iter()
29264            .filter(|rule| rule.downvalue_order == Some(755))
29265            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29266            .expect("positive quartic reciprocal split should apply");
29267        let residual = (primitive.derivative(x) - integrand).together();
29268        assert!(
29269            residual_is_zero(&residual),
29270            "primitive derivative mismatch: {residual}"
29271        );
29272    }
29273
29274    #[test]
29275    fn matches_nonpositive_quartic_binomial_reciprocal_split() {
29276        let x = symbol!("x");
29277        let integrand = parse!("1/(1 - x^4)");
29278        let primitive = rubi_rules()
29279            .iter()
29280            .filter(|rule| rule.downvalue_order == Some(756))
29281            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29282            .expect("nonpositive quartic reciprocal split should apply");
29283        let residual = (primitive.derivative(x) - integrand).together();
29284        assert!(
29285            residual_is_zero(&residual),
29286            "primitive derivative mismatch: {residual}"
29287        );
29288    }
29289
29290    #[test]
29291    fn matches_positive_multiple_of_four_binomial_reciprocal_split() {
29292        let x = symbol!("x");
29293        let integrand = parse!("1/(1 + x^8)");
29294        let primitive = rubi_rules()
29295            .iter()
29296            .filter(|rule| rule.downvalue_order == Some(757))
29297            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29298            .expect("positive multiple-of-four reciprocal split should apply");
29299        let residual = (primitive.derivative(x) - integrand).together();
29300        assert!(
29301            residual_is_zero(&residual),
29302            "primitive derivative mismatch: {residual}"
29303        );
29304    }
29305
29306    #[test]
29307    fn matches_nonpositive_multiple_of_four_binomial_reciprocal_split() {
29308        let x = symbol!("x");
29309        let integrand = parse!("1/(1 - x^8)");
29310        let primitive = rubi_rules()
29311            .iter()
29312            .filter(|rule| rule.downvalue_order == Some(758))
29313            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29314            .expect("nonpositive multiple-of-four reciprocal split should apply");
29315        let residual = (primitive.derivative(x) - integrand).together();
29316        assert!(
29317            residual_is_zero(&residual),
29318            "primitive derivative mismatch: {residual}"
29319        );
29320    }
29321
29322    #[test]
29323    fn matches_positive_cubic_inverse_sqrt_elliptic_f() {
29324        let x = symbol!("x");
29325        let integrand = parse!("1/sqrt(1 + x^3)");
29326        let primitive = rubi_rules()
29327            .iter()
29328            .filter(|rule| rule.downvalue_order == Some(759))
29329            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29330            .expect("positive cubic inverse square-root EllipticF row should apply");
29331
29332        assert!(format!("{primitive}").contains("elliptic_f"));
29333    }
29334
29335    #[test]
29336    fn matches_negative_cubic_inverse_sqrt_elliptic_f() {
29337        let x = symbol!("x");
29338        let integrand = parse!("1/sqrt(-1 + x^3)");
29339        let primitive = rubi_rules()
29340            .iter()
29341            .filter(|rule| rule.downvalue_order == Some(760))
29342            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29343            .expect("negative cubic inverse square-root EllipticF row should apply");
29344
29345        assert!(format!("{primitive}").contains("elliptic_f"));
29346    }
29347
29348    #[test]
29349    fn matches_positive_quartic_inverse_sqrt_elliptic_f() {
29350        let x = symbol!("x");
29351        let integrand = parse!("1/sqrt(1 + x^4)");
29352        let primitive = rubi_rules()
29353            .iter()
29354            .filter(|rule| rule.downvalue_order == Some(761))
29355            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29356            .expect("positive quartic inverse square-root EllipticF row should apply");
29357
29358        assert!(format!("{primitive}").contains("elliptic_f"));
29359    }
29360
29361    #[test]
29362    fn matches_negative_quartic_inverse_sqrt_positive_a_elliptic_f() {
29363        let x = symbol!("x");
29364        let integrand = parse!("1/sqrt(1 - x^4)");
29365        let primitive = rubi_rules()
29366            .iter()
29367            .filter(|rule| rule.downvalue_order == Some(762))
29368            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29369            .expect("negative quartic inverse square-root positive-a EllipticF row should apply");
29370
29371        assert!(format!("{primitive}").contains("elliptic_f"));
29372    }
29373
29374    #[test]
29375    fn matches_negative_quartic_inverse_sqrt_negative_a_elliptic_f_rows() {
29376        let x = symbol!("x");
29377        let integrand = parse!("1/sqrt(-1 + x^4)");
29378        let mut matching_rows = rubi_rules()
29379            .iter()
29380            .filter(|rule| matches!(rule.downvalue_order, Some(763 | 764)));
29381        let first_rule = matching_rows
29382            .next()
29383            .expect("block 33 integer-q EllipticF row should apply");
29384        let second_rule = matching_rows
29385            .next()
29386            .expect("block 33 general EllipticF row should apply");
29387
29388        let first = matcher_rule_for_test(&integrand, x, first_rule)
29389            .expect("block 33 integer-q EllipticF row should apply");
29390        let second = matcher_rule_for_test(&integrand, x, second_rule)
29391            .expect("block 33 general EllipticF row should apply");
29392
29393        assert!(format!("{first}").contains("elliptic_f"));
29394        assert!(format!("{second}").contains("elliptic_f"));
29395    }
29396
29397    #[test]
29398    fn matches_negative_quartic_inverse_sqrt_normalization_elliptic_f() {
29399        let x = symbol!("x");
29400        let integrand = parse!("1/sqrt(-1 + x^4)");
29401        let primitive = rubi_rules()
29402            .iter()
29403            .filter(|rule| rule.downvalue_order == Some(765))
29404            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29405            .expect("negative quartic inverse square-root normalization row should apply");
29406
29407        assert!(format!("{primitive}").contains("elliptic_f"));
29408    }
29409
29410    #[test]
29411    fn matches_sextic_inverse_sqrt_elliptic_f() {
29412        let x = symbol!("x");
29413        let integrand = parse!("1/sqrt(1 + x^6)");
29414        let primitive = rubi_rules()
29415            .iter()
29416            .filter(|rule| rule.downvalue_order == Some(766))
29417            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29418            .expect("sextic inverse square-root EllipticF row should apply");
29419
29420        assert!(format!("{primitive}").contains("elliptic_f"));
29421    }
29422
29423    #[test]
29424    fn matches_downvalue_767_octic_inverse_sqrt_split() {
29425        let x = symbol!("x");
29426        let integrand = parse!("1/sqrt(1 + x^8)");
29427        let primitive = rubi_rules()
29428            .iter()
29429            .filter(|rule| rule.downvalue_order == Some(767))
29430            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29431            .expect("DownValue 767 should split the octic inverse square root");
29432        assert!(
29433            rubi_finished_primitive_q(&primitive),
29434            "DownValue 767 left a deferred or unintegrable result: {primitive}"
29435        );
29436    }
29437
29438    #[test]
29439    fn matches_downvalue_768_quartic_three_quarter_normalization() {
29440        let x = symbol!("x");
29441        let integrand = parse!("1/(1 + x^4)^(3/4)");
29442        let primitive = rubi_rules()
29443            .iter()
29444            .filter(|rule| rule.downvalue_order == Some(768))
29445            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29446            .expect("DownValue 768 should normalize the quartic three-quarter power");
29447        assert!(
29448            rubi_finished_primitive_q(&primitive),
29449            "DownValue 768 left a deferred or unintegrable result: {primitive}"
29450        );
29451    }
29452
29453    #[test]
29454    fn matches_cubic_binomial_inverse_cube_root() {
29455        let x = symbol!("x");
29456        let integrand = parse!("1/(1 + x^3)^(1/3)");
29457        let primitive = rubi_rules()
29458            .iter()
29459            .filter(|rule| rule.downvalue_order == Some(769))
29460            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29461            .expect("cubic inverse cube-root rule should apply");
29462        let residual = (primitive.derivative(x) - integrand).together();
29463        assert!(
29464            residual_is_zero(&residual),
29465            "primitive derivative mismatch: {residual}"
29466        );
29467    }
29468
29469    #[test]
29470    fn matches_general_binomial_negative_fractional_substitution_integer_sum() {
29471        let x = symbol!("x");
29472        let integrand = parse!("1/(1 + x^3)^(1/3)");
29473        let primitive = rubi_rules()
29474            .iter()
29475            .filter(|rule| rule.downvalue_order == Some(770))
29476            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29477            .expect("negative fractional binomial substitution rule should apply");
29478        let residual = (primitive.derivative(x) - integrand).together();
29479        assert!(
29480            residual_is_zero(&residual),
29481            "primitive derivative mismatch: {residual}"
29482        );
29483    }
29484
29485    #[test]
29486    fn matches_general_binomial_negative_monomial_exponent_substitution() {
29487        let x = symbol!("x");
29488        let integrand = parse!("sqrt(1 + 1/x^2)");
29489        let primitive = rubi_rules()
29490            .iter()
29491            .filter(|rule| rule.downvalue_order == Some(773))
29492            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29493            .expect("negative monomial exponent substitution rule should apply");
29494        let residual = (primitive.derivative(x) - integrand).together();
29495        assert!(
29496            residual_is_zero(&residual),
29497            "primitive derivative mismatch: {residual}"
29498        );
29499    }
29500
29501    #[test]
29502    fn matches_general_binomial_fractional_monomial_exponent_substitution() {
29503        let x = symbol!("x");
29504        let integrand = parse!("(1 + x^(3/2))^2");
29505        let primitive = rubi_rules()
29506            .iter()
29507            .filter(|rule| rule.downvalue_order == Some(774))
29508            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29509            .expect("fractional monomial exponent substitution rule should apply");
29510        let residual = (primitive.derivative(x) - integrand).together();
29511        assert!(
29512            residual_is_zero(&residual),
29513            "primitive derivative mismatch: {residual}"
29514        );
29515    }
29516
29517    #[test]
29518    fn matches_general_binomial_positive_integer_expand_integrand_late_rule() {
29519        let x = symbol!("x");
29520        let integrand = parse!("(1 + x^3)^2");
29521        let primitive = rubi_rules()
29522            .iter()
29523            .filter(|rule| rule.downvalue_order == Some(775))
29524            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29525            .expect("late positive integer ExpandIntegrand rule should apply");
29526        let residual = (primitive.derivative(x) - integrand).together();
29527        assert!(
29528            residual_is_zero(&residual),
29529            "primitive derivative mismatch: {residual}"
29530        );
29531    }
29532
29533    #[test]
29534    fn matches_general_binomial_hypergeometric_terminal() {
29535        let x = symbol!("x");
29536        let integrand = parse!("1/(1 + x^2)^(1/3)");
29537        let primitive = rubi_rules()
29538            .iter()
29539            .filter(|rule| rule.downvalue_order == Some(778))
29540            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29541            .expect("general binomial Hypergeometric2F1 terminal should apply");
29542
29543        assert!(format!("{primitive}").contains("hypergeometric_2f1"));
29544    }
29545
29546    #[test]
29547    fn matches_downvalue_771_reduced_shifted_denominator_substitution() {
29548        let x = symbol!("x");
29549        let integrand = parse!("1/(1 + x^2)^(5/6)");
29550        let _ = rubi_rules()
29551            .iter()
29552            .filter(|rule| rule.downvalue_order == Some(771))
29553            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29554            .expect("DownValue 771 reduced-denominator substitution should apply");
29555    }
29556
29557    #[test]
29558    fn matches_downvalue_776_balanced_substitution() {
29559        let x = symbol!("x");
29560        let integrand = parse!("1/(1 + x^5)^(1/5)");
29561        let _ = rubi_rules()
29562            .iter()
29563            .filter(|rule| rule.downvalue_order == Some(776))
29564            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29565            .expect("DownValue 776 balanced substitution should apply");
29566    }
29567
29568    #[test]
29569    fn matches_opposite_binomial_pair_power_normalization() {
29570        let x = symbol!("x");
29571        let integrand = parse!("(1 + x^2)^2*(1 - x^2)^2");
29572        let primitive = rubi_rules()
29573            .iter()
29574            .filter(|rule| rule.downvalue_order == Some(780))
29575            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29576            .expect("opposite binomial pair normalization should apply");
29577        let residual = (primitive.derivative(x) - integrand).together();
29578        assert!(
29579            residual_is_zero(&residual),
29580            "primitive derivative mismatch: {residual}"
29581        );
29582    }
29583
29584    #[test]
29585    fn matches_opposite_binomial_pair_positive_recurrence() {
29586        let x = symbol!("x");
29587        let integrand = parse!("(1 + x^2)^2*(1 - x^2)^2");
29588        let primitive = rubi_rules()
29589            .iter()
29590            .filter(|rule| rule.downvalue_order == Some(781))
29591            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29592            .expect("opposite binomial pair positive recurrence should apply");
29593        let residual = (primitive.derivative(x) - integrand).together();
29594        assert!(
29595            residual_is_zero(&residual),
29596            "primitive derivative mismatch: {residual}"
29597        );
29598    }
29599
29600    #[test]
29601    fn matches_opposite_binomial_pair_negative_recurrence() {
29602        let x = symbol!("x");
29603        let integrand = parse!("(1 + x^2)^-2*(1 - x^2)^-2");
29604        let primitive = rubi_rules()
29605            .iter()
29606            .filter(|rule| rule.downvalue_order == Some(782))
29607            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29608            .expect("opposite binomial pair negative recurrence should apply");
29609        let residual = (primitive.derivative(x) - integrand).together();
29610        assert!(
29611            residual_is_zero(&residual),
29612            "primitive derivative mismatch: {residual}"
29613        );
29614    }
29615
29616    #[test]
29617    fn matches_opposite_binomial_pair_negative_monomial_exponent_substitution() {
29618        let x = symbol!("x");
29619        let integrand = parse!("(1 + 1/x^2)^2*(1 - 1/x^2)^2");
29620        let primitive = rubi_rules()
29621            .iter()
29622            .filter(|rule| rule.downvalue_order == Some(783))
29623            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29624            .expect("opposite binomial pair negative monomial exponent substitution should apply");
29625        let residual = (primitive.derivative(x) - integrand).together();
29626        assert!(
29627            residual_is_zero(&residual),
29628            "primitive derivative mismatch: {residual}"
29629        );
29630    }
29631
29632    #[test]
29633    fn matches_opposite_binomial_pair_fractional_monomial_exponent_substitution() {
29634        let x = symbol!("x");
29635        let integrand = parse!("(1 + x^(1/4))^2*(1 - x^(1/4))^2");
29636        let primitive = rubi_rules()
29637            .iter()
29638            .filter(|rule| rule.downvalue_order == Some(784))
29639            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29640            .expect(
29641                "opposite binomial pair fractional monomial exponent substitution should apply",
29642            );
29643        let residual = (primitive.derivative(x) - integrand).together();
29644        assert!(
29645            residual_is_zero(&residual),
29646            "primitive derivative mismatch: {residual}"
29647        );
29648    }
29649
29650    #[test]
29651    fn matches_opposite_binomial_pair_fractional_power_normalization() {
29652        let x = symbol!("x");
29653        let integrand = parse!("(1 + x^(1/2))^(3/2)*(1 - x^(1/2))^(3/2)");
29654        let primitive = rubi_rules()
29655            .iter()
29656            .filter(|rule| rule.downvalue_order == Some(785))
29657            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29658            .expect("opposite binomial pair fractional power normalization should apply");
29659        let residual = (primitive.derivative(x) - integrand).together();
29660        assert!(
29661            residual_is_zero(&residual),
29662            "primitive derivative mismatch: {residual}"
29663        );
29664    }
29665
29666    #[test]
29667    fn applies_scaled_monomial_inside_general_binomial_substitution() {
29668        let x = symbol!("x");
29669        let integrand = parse!("(1 + 3*(2*x)^2)^2");
29670        let primitive = scaled_monomial_inside_general_binomial_substitution_primitive(
29671            Atom::num(1),
29672            Atom::num(3),
29673            Atom::num(2),
29674            Atom::num(2),
29675            Atom::num(2),
29676            Atom::num(1),
29677            x,
29678        )
29679        .expect("scaled monomial inside general binomial substitution should apply");
29680        let residual = (primitive.derivative(x) - integrand).together();
29681        assert!(
29682            residual_is_zero(&residual),
29683            "primitive derivative mismatch: {residual}"
29684        );
29685    }
29686
29687    #[test]
29688    fn matches_fractional_power_scaled_linear_inside_general_binomial_substitution() {
29689        let x = symbol!("x");
29690        let integrand = parse!("(1 + x^(1/2))^2");
29691        let primitive = rubi_rules()
29692            .iter()
29693            .filter(|rule| rule.downvalue_order == Some(787))
29694            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29695            .expect("fractional power scaled linear substitution should apply");
29696        let residual = (primitive.derivative(x) - integrand).together();
29697        assert!(
29698            residual_is_zero(&residual),
29699            "primitive derivative mismatch: {residual}; primitive: {primitive}"
29700        );
29701    }
29702
29703    #[test]
29704    fn matches_downvalue_786_integer_nested_monomial_power_substitution() {
29705        let x = symbol!("x");
29706        let integrand = parse!("(1 + (2*x^2)^(3/2))^2");
29707        let _ = rubi_rules()
29708            .iter()
29709            .filter(|rule| rule.downvalue_order == Some(786))
29710            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29711            .expect("DownValue 786 nested monomial substitution should apply");
29712    }
29713
29714    #[test]
29715    fn matches_downvalue_788_nonrational_nested_power_substitution() {
29716        let x = symbol!("x");
29717        let integrand = parse!("(1 + (2*x^2)^n)^2");
29718        let _ = rubi_rules()
29719            .iter()
29720            .filter(|rule| rule.downvalue_order == Some(788))
29721            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29722            .expect("DownValue 788 nonrational nested-power substitution should apply");
29723    }
29724
29725    #[test]
29726    fn matches_downvalue_789_negative_nested_monomial_power_substitution() {
29727        let x = symbol!("x");
29728        let integrand = parse!("(1 + (2/x^2)^(1/2))^2");
29729        let _ = rubi_rules()
29730            .iter()
29731            .filter(|rule| rule.downvalue_order == Some(789))
29732            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29733            .expect("DownValue 789 negative nested-monomial substitution should apply");
29734    }
29735
29736    #[test]
29737    fn matches_downvalue_790_fractional_nested_monomial_power_substitution() {
29738        let x = symbol!("x");
29739        let integrand = parse!("(1 + (2*x^(1/2))^(1/3))^2");
29740        let _ = rubi_rules()
29741            .iter()
29742            .filter(|rule| rule.downvalue_order == Some(790))
29743            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29744            .expect("DownValue 790 fractional nested-monomial substitution should apply");
29745    }
29746
29747    #[test]
29748    fn matches_scaled_monomial_opposite_binomial_pair_power_normalization() {
29749        let x = symbol!("x");
29750        let integrand = parse!("x^2*(1 + x^2)^2*(1 - x^2)^2");
29751        let primitive = rubi_rules()
29752            .iter()
29753            .filter(|rule| rule.downvalue_order == Some(791))
29754            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29755            .expect("scaled monomial opposite-binomial pair normalization should apply");
29756        let residual = (primitive.derivative(x) - integrand).together();
29757        assert!(
29758            residual_is_zero(&residual),
29759            "primitive derivative mismatch: {residual}"
29760        );
29761    }
29762
29763    #[test]
29764    fn matches_monomial_over_binomial_log_derivative() {
29765        let x = symbol!("x");
29766        let integrand = parse!("x^2/(1 + x^3)");
29767        let primitive = rubi_rules()
29768            .iter()
29769            .filter(|rule| rule.downvalue_order == Some(792))
29770            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29771            .expect("monomial over binomial logarithmic derivative should apply");
29772        let residual = (primitive.derivative(x) - integrand).together();
29773        assert!(
29774            residual_is_zero(&residual),
29775            "primitive derivative mismatch: {residual}"
29776        );
29777    }
29778
29779    #[test]
29780    fn matches_monomial_binomial_direct_power() {
29781        let x = symbol!("x");
29782        let integrand = parse!("x^2*(1 + x^3)^2");
29783        let primitive = rubi_rules()
29784            .iter()
29785            .filter(|rule| rule.downvalue_order == Some(793))
29786            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29787            .expect("monomial binomial direct power should apply");
29788        let residual = (primitive.derivative(x) - integrand).together();
29789        assert!(
29790            residual_is_zero(&residual),
29791            "primitive derivative mismatch: {residual}"
29792        );
29793    }
29794
29795    #[test]
29796    fn matches_monomial_opposite_binomial_pair_direct_power() {
29797        let x = symbol!("x");
29798        let integrand = parse!("x^3*(1 + x^2)^2*(1 - x^2)^2");
29799        let primitive = rubi_rules()
29800            .iter()
29801            .filter(|rule| rule.downvalue_order == Some(794))
29802            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29803            .expect("monomial opposite-binomial pair direct power should apply");
29804        let residual = (primitive.derivative(x) - integrand).together();
29805        assert!(
29806            residual_is_zero(&residual),
29807            "primitive derivative mismatch: {residual}"
29808        );
29809    }
29810
29811    #[test]
29812    fn matches_monomial_opposite_binomial_pair_direct_power_with_optional_n() {
29813        let x = symbol!("x");
29814        let integrand = parse!("x*(1 + x)^2*(1 - x)^2");
29815        let primitive = rubi_rules()
29816            .iter()
29817            .filter(|rule| rule.downvalue_order == Some(794))
29818            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29819            .expect("monomial opposite-binomial pair direct power should apply with omitted n");
29820        let residual = (primitive.derivative(x) - integrand).together();
29821        assert!(
29822            residual_is_zero(&residual),
29823            "primitive derivative mismatch: {residual}"
29824        );
29825    }
29826
29827    #[test]
29828    fn matches_monomial_general_binomial_negative_power_integer_normalization() {
29829        let x = symbol!("x");
29830        let integrand = parse!("x^2*(1 + 1/x^2)^2");
29831        let primitive = rubi_rules()
29832            .iter()
29833            .filter(|rule| rule.downvalue_order == Some(795))
29834            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29835            .expect("monomial negative-power binomial normalization should apply");
29836        let residual = (primitive.derivative(x) - integrand).together();
29837        assert!(
29838            residual_is_zero(&residual),
29839            "primitive derivative mismatch: {residual}"
29840        );
29841    }
29842
29843    #[test]
29844    fn matches_scaled_monomial_general_binomial_balance_direct() {
29845        let x = symbol!("x");
29846        let integrand = parse!("x*(1 + x^2)^-2");
29847        let primitive = rubi_rules()
29848            .iter()
29849            .filter(|rule| rule.downvalue_order == Some(796))
29850            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29851            .expect("scaled monomial binomial balance direct rule should apply");
29852        let residual = (primitive.derivative(x) - integrand).together();
29853        assert!(
29854            residual_is_zero(&residual),
29855            "primitive derivative mismatch: {residual}"
29856        );
29857    }
29858
29859    #[test]
29860    fn matches_scaled_monomial_opposite_binomial_pair_balance_direct() {
29861        let x = symbol!("x");
29862        let integrand = parse!("x^3*(1 + x^2)^-2*(1 - x^2)^-2");
29863        let primitive = rubi_rules()
29864            .iter()
29865            .filter(|rule| rule.downvalue_order == Some(797))
29866            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29867            .expect("scaled monomial opposite-binomial pair balance direct rule should apply");
29868        let residual = (primitive.derivative(x) - integrand).together();
29869        assert!(
29870            residual_is_zero(&residual),
29871            "primitive derivative mismatch: {residual}"
29872        );
29873    }
29874
29875    #[test]
29876    fn matches_monomial_general_binomial_integer_ratio_substitution() {
29877        let x = symbol!("x");
29878        let integrand = parse!("x^3*(1 + x^2)^2");
29879        let primitive = rubi_rules()
29880            .iter()
29881            .filter(|rule| rule.downvalue_order == Some(798))
29882            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29883            .expect("monomial binomial integer-ratio substitution should apply");
29884        let residual = (primitive.derivative(x) - integrand).together();
29885        assert!(
29886            residual_is_zero(&residual),
29887            "primitive derivative mismatch: {residual}"
29888        );
29889    }
29890
29891    #[test]
29892    fn matches_monomial_general_binomial_integer_ratio_substitution_default_m() {
29893        let x = symbol!("x");
29894        let integrand = parse!("x*(1 + x^2)^2");
29895        let primitive = rubi_rules()
29896            .iter()
29897            .filter(|rule| rule.downvalue_order == Some(798))
29898            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29899            .expect("default-m monomial binomial integer-ratio substitution should apply");
29900        let residual = (primitive.derivative(x) - integrand).together();
29901        assert!(
29902            residual_is_zero(&residual),
29903            "primitive derivative mismatch: {residual}"
29904        );
29905    }
29906
29907    #[test]
29908    fn matches_monomial_opposite_binomial_pair_integer_ratio_substitution() {
29909        let x = symbol!("x");
29910        let integrand = parse!("x^7*(1 + x^2)^2*(1 - x^2)^2");
29911        let primitive = rubi_rules()
29912            .iter()
29913            .filter(|rule| rule.downvalue_order == Some(799))
29914            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29915            .expect("monomial opposite-binomial pair integer-ratio substitution should apply");
29916        let residual = (primitive.derivative(x) - integrand).together();
29917        assert!(
29918            residual_is_zero(&residual),
29919            "primitive derivative mismatch: {residual}"
29920        );
29921    }
29922
29923    #[test]
29924    fn matches_scaled_monomial_general_binomial_fractional_normalization() {
29925        let x = symbol!("x");
29926        let integrand = parse!("(2*x)^(1/2)*(1 + x^(3/2))^2");
29927        let primitive = rubi_rules()
29928            .iter()
29929            .filter(|rule| rule.downvalue_order == Some(800))
29930            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29931            .expect("scaled monomial binomial fractional normalization should apply");
29932        let residual = (primitive.derivative(x) - integrand).together();
29933        assert!(
29934            residual_is_zero(&residual),
29935            "primitive derivative mismatch: {residual}"
29936        );
29937    }
29938
29939    #[test]
29940    fn matches_scaled_monomial_opposite_binomial_pair_fractional_normalization() {
29941        let x = symbol!("x");
29942        let integrand = parse!("(2*x)^(1/2)*(1 + x^(3/4))^2*(1 - x^(3/4))^2");
29943        let primitive = rubi_rules()
29944            .iter()
29945            .filter(|rule| rule.downvalue_order == Some(801))
29946            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29947            .expect("scaled monomial opposite-binomial pair fractional normalization should apply");
29948        let residual = (primitive.derivative(x) - integrand).together();
29949        assert!(
29950            residual_is_zero(&residual),
29951            "primitive derivative mismatch: {residual}"
29952        );
29953    }
29954
29955    #[test]
29956    fn matches_default_power_scaled_monomial_general_binomial_positive_integer_expand_integrand() {
29957        let x = symbol!("x");
29958        let integrand = parse!("x*(1 + x^2)");
29959        let primitive = rubi_rules()
29960            .iter()
29961            .filter(|rule| rule.downvalue_order == Some(802))
29962            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29963            .expect("default-power scaled monomial binomial expansion should apply");
29964        let residual = (primitive.derivative(x) - integrand).together();
29965        assert!(
29966            residual_is_zero(&residual),
29967            "primitive derivative mismatch: {residual}"
29968        );
29969    }
29970
29971    #[test]
29972    fn matches_monomial_opposite_binomial_pair_negative_balance_recurrence() {
29973        let x = symbol!("x");
29974        let integrand = parse!("x^3*(1 + x^2)^-3*(1 - x^2)^-3");
29975        let primitive = rubi_rules()
29976            .iter()
29977            .filter(|rule| rule.downvalue_order == Some(804))
29978            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29979            .expect("monomial opposite-binomial pair negative-balance recurrence should apply");
29980        let residual = (primitive.derivative(x) - integrand).together();
29981        assert!(
29982            residual_is_zero(&residual),
29983            "primitive derivative mismatch: {residual}"
29984        );
29985    }
29986
29987    #[test]
29988    fn matches_monomial_general_binomial_raise_exponent_recurrence() {
29989        let x = symbol!("x");
29990        let integrand = parse!("x*(1 + x^2)^-3");
29991        let primitive = rubi_rules()
29992            .iter()
29993            .filter(|rule| rule.downvalue_order == Some(805))
29994            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
29995            .expect("monomial binomial raise-exponent recurrence should apply");
29996        let residual = (primitive.derivative(x) - integrand).together();
29997        assert!(
29998            residual_is_zero(&residual),
29999            "primitive derivative mismatch: {residual}"
30000        );
30001    }
30002
30003    #[test]
30004    fn matches_monomial_opposite_binomial_pair_raise_exponent_recurrence() {
30005        let x = symbol!("x");
30006        let integrand = parse!("x^3*(1 + x^2)^-3*(1 - x^2)^-3");
30007        let primitive = rubi_rules()
30008            .iter()
30009            .filter(|rule| rule.downvalue_order == Some(806))
30010            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30011            .expect("monomial opposite-binomial pair raise-exponent recurrence should apply");
30012        let residual = (primitive.derivative(x) - integrand).together();
30013        assert!(
30014            residual_is_zero(&residual),
30015            "primitive derivative mismatch: {residual}"
30016        );
30017    }
30018
30019    #[test]
30020    fn matches_monomial_general_binomial_gcd_substitution() {
30021        let x = symbol!("x");
30022        let integrand = parse!("x^3*(1 + x^2)^2");
30023        let primitive = rubi_rules()
30024            .iter()
30025            .filter(|rule| rule.downvalue_order == Some(807))
30026            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30027            .expect("monomial binomial gcd substitution should apply");
30028        let residual = (primitive.derivative(x) - integrand).together();
30029        assert!(
30030            residual_is_zero(&residual),
30031            "primitive derivative mismatch: {residual}"
30032        );
30033    }
30034
30035    #[test]
30036    fn matches_default_monomial_general_binomial_gcd_substitution() {
30037        let x = symbol!("x");
30038        let integrand = parse!("x*(1 + x^2)^2");
30039        let primitive = rubi_rules()
30040            .iter()
30041            .filter(|rule| rule.downvalue_order == Some(807))
30042            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30043            .expect("default monomial binomial gcd substitution should apply");
30044        let residual = (primitive.derivative(x) - integrand).together();
30045        assert!(
30046            residual_is_zero(&residual),
30047            "primitive derivative mismatch: {residual}"
30048        );
30049    }
30050
30051    #[test]
30052    fn matches_monomial_opposite_binomial_pair_gcd_substitution() {
30053        let x = symbol!("x");
30054        let integrand = parse!("x*(1 + x^2)^2*(1 - x^2)^2");
30055        let primitive = rubi_rules()
30056            .iter()
30057            .filter(|rule| rule.downvalue_order == Some(808))
30058            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30059            .expect("monomial opposite-binomial pair gcd substitution should apply");
30060        let residual = (primitive.derivative(x) - integrand).together();
30061        assert!(
30062            residual_is_zero(&residual),
30063            "primitive derivative mismatch: {residual}"
30064        );
30065    }
30066
30067    #[test]
30068    fn matches_scaled_monomial_general_binomial_positive_power_lower_m_recurrence() {
30069        let x = symbol!("x");
30070        let integrand = parse!("x^-2*(1 + x^2)^2");
30071        let primitive = rubi_rules()
30072            .iter()
30073            .filter(|rule| rule.downvalue_order == Some(809))
30074            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30075            .expect("monomial binomial positive-power lower-m recurrence should apply");
30076        let residual = (primitive.derivative(x) - integrand).together();
30077        assert!(
30078            residual_is_zero(&residual),
30079            "primitive derivative mismatch: {residual}"
30080        );
30081    }
30082
30083    #[test]
30084    fn matches_downvalue_810_opposite_binomial_positive_power_lower_m_recurrence() {
30085        let x = symbol!("x");
30086        let integrand = parse!("x^-2*(1 + x^2)^2*(1 - x^2)^2");
30087        let primitive = rubi_rules()
30088            .iter()
30089            .filter(|rule| rule.downvalue_order == Some(810))
30090            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30091            .expect("DownValue 810 opposite-binomial lower-m recurrence should apply");
30092        let residual = (primitive.derivative(x) - integrand).together();
30093        assert!(
30094            residual_is_zero(&residual),
30095            "primitive derivative mismatch: {residual}"
30096        );
30097    }
30098
30099    #[test]
30100    fn matches_scaled_monomial_general_binomial_positive_power_lower_p_recurrence() {
30101        let x = symbol!("x");
30102        let integrand = parse!("x^2*(1 + x^2)^2");
30103        let primitive = rubi_rules()
30104            .iter()
30105            .filter(|rule| rule.downvalue_order == Some(811))
30106            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30107            .expect("monomial binomial positive-power lower-p recurrence should apply");
30108        let residual = (primitive.derivative(x) - integrand).together();
30109        assert!(
30110            residual_is_zero(&residual),
30111            "primitive derivative mismatch: {residual}"
30112        );
30113    }
30114
30115    #[test]
30116    fn matches_scaled_monomial_opposite_binomial_pair_positive_power_lower_p_recurrence() {
30117        let x = symbol!("x");
30118        let integrand = parse!("x^2*(1 + x^2)^2*(1 - x^2)^2");
30119        let primitive = rubi_rules()
30120            .iter()
30121            .filter(|rule| rule.downvalue_order == Some(812))
30122            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30123            .expect("opposite binomial pair positive-power lower-p recurrence should apply");
30124        let residual = (primitive.derivative(x) - integrand).together();
30125        assert!(
30126            residual_is_zero(&residual),
30127            "primitive derivative mismatch: {residual}"
30128        );
30129    }
30130
30131    #[test]
30132    fn matches_scaled_binomial_negative_power_lower_m_recurrence() {
30133        let x = symbol!("x");
30134        let integrand = parse!("x^4/(1 + x^2)^2");
30135        let primitive = rubi_rules()
30136            .iter()
30137            .filter(|rule| rule.downvalue_order == Some(817))
30138            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30139            .expect("negative-power lower-m recurrence should apply");
30140        let residual = (primitive.derivative(x) - integrand).together();
30141        assert!(
30142            residual_is_zero(&residual),
30143            "primitive derivative mismatch: {residual}"
30144        );
30145    }
30146
30147    #[test]
30148    fn matches_balanced_binomial_pair_negative_power_lower_m() {
30149        let x = symbol!("x");
30150        let integrand = parse!("x^7*(1 + x^2)^(-3/2)*(1 - x^2)^(-3/2)");
30151        let row = rubi_rules()
30152            .iter()
30153            .find(|rule| rule.downvalue_order == Some(818))
30154            .expect("DownValue 818 should be registered");
30155        let primitive = matcher_rule_for_test(&integrand, x, row)
30156            .expect("balanced-binomial lower-m recurrence should apply");
30157        let residual = (primitive.derivative(x) - integrand).together();
30158        assert!(
30159            residual_is_zero(&residual),
30160            "primitive derivative mismatch: {residual}"
30161        );
30162    }
30163
30164    #[test]
30165    fn matches_binomial_negative_power_raise_p_recurrence() {
30166        let x = symbol!("x");
30167        let integrand = parse!("x/(1 + x^2)^2");
30168        let primitive = rubi_rules()
30169            .iter()
30170            .filter(|rule| rule.downvalue_order == Some(819))
30171            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30172            .expect("negative-power raise-p recurrence should apply");
30173        let residual = (primitive.derivative(x) - integrand).together();
30174        assert!(
30175            residual_is_zero(&residual),
30176            "primitive derivative mismatch: {residual}"
30177        );
30178    }
30179
30180    #[test]
30181    fn matches_balanced_binomial_pair_negative_power_raise_p() {
30182        let x = symbol!("x");
30183        let integrand = parse!("x^3*(1 + x^2)^(-3/2)*(1 - x^2)^(-3/2)");
30184        let primitive = rubi_rules()
30185            .iter()
30186            .filter(|rule| rule.downvalue_order == Some(820))
30187            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30188            .unwrap_or_else(|| {
30189                panic!("balanced-binomial raise-p recurrence should apply: {integrand}")
30190            });
30191        let residual = (primitive.derivative(x) - integrand).together();
30192        assert!(
30193            residual_is_zero(&residual),
30194            "primitive derivative mismatch: {residual}"
30195        );
30196    }
30197
30198    #[test]
30199    fn matches_cubic_binomial_linear_numerator_decomposition() {
30200        let x = symbol!("x");
30201        let integrand = parse!("x/(1 + x^3)");
30202        let primitive = rubi_rules()
30203            .iter()
30204            .filter(|rule| rule.downvalue_order == Some(821))
30205            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30206            .expect("cubic binomial linear-numerator decomposition should apply");
30207        let residual = (primitive.derivative(x) - integrand).together();
30208        assert!(
30209            residual_is_zero(&residual),
30210            "primitive derivative mismatch: {residual}"
30211        );
30212    }
30213
30214    #[test]
30215    fn matches_positive_odd_binomial_linear_numerator_decomposition() {
30216        let x = symbol!("x");
30217        let integrand = parse!("x/(1 + x^5)");
30218        let primitive = rubi_rules()
30219            .iter()
30220            .filter(|rule| rule.downvalue_order == Some(822))
30221            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30222            .expect("positive odd binomial linear-numerator decomposition should apply");
30223        let residual = (primitive.derivative(x) - integrand).together();
30224        assert!(
30225            residual_is_zero(&residual),
30226            "primitive derivative mismatch: {residual}"
30227        );
30228    }
30229
30230    #[test]
30231    fn matches_negative_odd_binomial_linear_numerator_decomposition() {
30232        let x = symbol!("x");
30233        let integrand = parse!("x/(-1 + x^5)");
30234        let primitive = rubi_rules()
30235            .iter()
30236            .filter(|rule| rule.downvalue_order == Some(823))
30237            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30238            .expect("negative odd binomial linear-numerator decomposition should apply");
30239        let residual = (primitive.derivative(x) - integrand).together();
30240        assert!(
30241            residual_is_zero(&residual),
30242            "primitive derivative mismatch: {residual}"
30243        );
30244    }
30245
30246    #[test]
30247    fn matches_positive_even_binomial_linear_numerator_decomposition() {
30248        let x = symbol!("x");
30249        let integrand = parse!("x/(1 + x^6)");
30250        let primitive = rubi_rules()
30251            .iter()
30252            .filter(|rule| rule.downvalue_order == Some(824))
30253            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule));
30254        assert!(
30255            primitive.is_some(),
30256            "positive even binomial linear-numerator decomposition should apply"
30257        );
30258    }
30259
30260    #[test]
30261    fn matches_negative_even_binomial_linear_numerator_decomposition() {
30262        let x = symbol!("x");
30263        let integrand = parse!("x/(-1 + x^6)");
30264        let primitive = rubi_rules()
30265            .iter()
30266            .filter(|rule| rule.downvalue_order == Some(825))
30267            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule));
30268        assert!(
30269            primitive.is_some(),
30270            "negative even binomial linear-numerator decomposition should apply"
30271        );
30272    }
30273
30274    #[test]
30275    fn matches_positive_quartic_quadratic_numerator_split() {
30276        let x = symbol!("x");
30277        let integrand = parse!("x^2/(1 + x^4)");
30278        let primitive = rubi_rules()
30279            .iter()
30280            .filter(|rule| rule.downvalue_order == Some(826))
30281            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30282            .expect("positive quartic quadratic-numerator split should apply");
30283        let residual = (primitive.derivative(x) - integrand).together();
30284        assert!(
30285            residual_is_zero(&residual),
30286            "primitive derivative mismatch: {residual}"
30287        );
30288    }
30289
30290    #[test]
30291    fn matches_negative_quartic_quadratic_numerator_split() {
30292        let x = symbol!("x");
30293        let integrand = parse!("x^2/(1 - x^4)");
30294        let primitive = rubi_rules()
30295            .iter()
30296            .filter(|rule| rule.downvalue_order == Some(827))
30297            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30298            .expect("negative quartic quadratic-numerator split should apply");
30299        let residual = (primitive.derivative(x) - integrand).together();
30300        assert!(
30301            residual_is_zero(&residual),
30302            "primitive derivative mismatch: {residual}"
30303        );
30304    }
30305
30306    #[test]
30307    fn matches_positive_quartic_root_split_linear_numerator() {
30308        let x = symbol!("x");
30309        let integrand = parse!("x/(1 + x^4)");
30310        let primitive = rubi_rules()
30311            .iter()
30312            .filter(|rule| rule.downvalue_order == Some(828))
30313            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30314            .expect("positive quartic-root split should apply");
30315        let residual = (primitive.derivative(x) - integrand).together();
30316        assert!(
30317            residual_is_zero(&residual),
30318            "primitive derivative mismatch: {residual}"
30319        );
30320    }
30321
30322    #[test]
30323    fn matches_negative_quartic_lower_half_split_linear_numerator() {
30324        let x = symbol!("x");
30325        let integrand = parse!("x^2/(1 - x^8)");
30326        let primitive = rubi_rules()
30327            .iter()
30328            .filter(|rule| rule.downvalue_order == Some(829))
30329            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30330            .expect("negative lower-(Atom::num(1) / 2) split should apply");
30331        let residual = (primitive.derivative(x) - integrand).together();
30332        assert!(
30333            residual_is_zero(&residual),
30334            "primitive derivative mismatch: {residual}"
30335        );
30336    }
30337
30338    #[test]
30339    fn matches_negative_quartic_upper_half_split_quadratic_numerator() {
30340        let x = symbol!("x");
30341        let integrand = parse!("x^2/(1 - x^4)");
30342        let primitive = rubi_rules()
30343            .iter()
30344            .filter(|rule| rule.downvalue_order == Some(830))
30345            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30346            .expect("negative upper-(Atom::num(1) / 2) split should apply");
30347        let residual = (primitive.derivative(x) - integrand).together();
30348        assert!(
30349            residual_is_zero(&residual),
30350            "primitive derivative mismatch: {residual}"
30351        );
30352    }
30353
30354    #[test]
30355    fn matches_binomial_polynomial_divide_reduction() {
30356        let x = symbol!("x");
30357        let integrand = parse!("x^9/(1 + x^3)");
30358        let primitive = rubi_rules()
30359            .iter()
30360            .filter(|rule| rule.downvalue_order == Some(831))
30361            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule))
30362            .expect("polynomial divide reduction should apply");
30363        let residual = (primitive.derivative(x) - integrand).together();
30364        assert!(
30365            residual_is_zero(&residual),
30366            "primitive derivative mismatch: {residual}"
30367        );
30368    }
30369
30370    #[test]
30371    fn matches_positive_cubic_sqrt_linear_numerator() {
30372        assert_integrand_produces_primitive("x/sqrt(1 + x^3)");
30373    }
30374
30375    #[test]
30376    fn matches_negative_cubic_sqrt_linear_numerator() {
30377        assert_integrand_produces_primitive("x/sqrt(-1 + x^3)");
30378    }
30379
30380    #[test]
30381    fn matches_positive_quartic_sqrt_quadratic_numerator() {
30382        assert_integrand_produces_primitive("x^2/sqrt(1 + x^4)");
30383    }
30384
30385    #[test]
30386    fn matches_negative_a_quartic_sqrt_quadratic_numerator() {
30387        assert_integrand_produces_primitive("x^2/sqrt(-1 + x^4)");
30388    }
30389
30390    #[test]
30391    fn matches_negative_ratio_quartic_sqrt_quadratic_numerator() {
30392        assert_integrand_produces_primitive("x^2/sqrt(1 - x^4)");
30393    }
30394
30395    #[test]
30396    fn matches_sextic_sqrt_quartic_numerator() {
30397        assert_integrand_produces_primitive("x^4/sqrt(1 + x^6)");
30398    }
30399
30400    #[test]
30401    fn matches_octic_sqrt_quadratic_numerator() {
30402        assert_integrand_produces_primitive("x^2/sqrt(1 + x^8)");
30403    }
30404
30405    #[test]
30406    fn matches_quartic_quarter_positive_quadratic_numerator() {
30407        assert_integrand_produces_primitive("x^2/(1 + x^4)^(1/4)");
30408    }
30409
30410    #[test]
30411    fn matches_quartic_quarter_negative_quadratic_numerator() {
30412        assert_integrand_produces_primitive("x^2/(1 - x^4)^(1/4)");
30413    }
30414
30415    #[test]
30416    fn matches_quartic_quarter_positive_inverse_square() {
30417        assert_integrand_produces_primitive("1/(x^2*(1 + x^4)^(1/4))");
30418    }
30419
30420    #[test]
30421    fn matches_quartic_quarter_negative_inverse_square() {
30422        assert_integrand_produces_primitive("1/(x^2*(1 - x^4)^(1/4))");
30423    }
30424
30425    #[test]
30426    fn matches_scaled_sqrt_quadratic_quarter_positive() {
30427        assert_integrand_produces_primitive("sqrt(2*x)/(1 + x^2)^(1/4)");
30428    }
30429
30430    #[test]
30431    fn matches_scaled_sqrt_quadratic_quarter_negative() {
30432        assert_integrand_produces_primitive("sqrt(2*x)/(1 - x^2)^(1/4)");
30433    }
30434
30435    #[test]
30436    fn matches_scaled_quadratic_quarter_inverse_three_halves_positive() {
30437        assert_integrand_produces_primitive("1/((2*x)^(3/2)*(1 + x^2)^(1/4))");
30438    }
30439
30440    #[test]
30441    fn matches_scaled_quadratic_quarter_inverse_three_halves_negative() {
30442        assert_integrand_produces_primitive("1/((2*x)^(3/2)*(1 - x^2)^(1/4))");
30443    }
30444
30445    #[test]
30446    fn matches_sqrt_over_quadratic_sqrt_positive_a() {
30447        assert_integrand_produces_primitive("sqrt(x)/sqrt(1 - x^2)");
30448    }
30449
30450    #[test]
30451    fn matches_sqrt_over_quadratic_sqrt_nonpositive_a() {
30452        assert_integrand_produces_primitive("sqrt(x)/sqrt(-1 + x^2)");
30453    }
30454
30455    #[test]
30456    fn matches_scaled_sqrt_over_quadratic_sqrt() {
30457        assert_integrand_produces_primitive("sqrt(2*x)/sqrt(1 - x^2)");
30458    }
30459
30460    #[test]
30461    fn matches_general_binomial_high_m_int_binomial_reduction() {
30462        let x = symbol!("x");
30463        let integrand = parse!("x^4*(1+x^2)^-2");
30464        let primitive = downvalue_primitive(843, &integrand, x);
30465        let residual = (primitive.derivative(x) - integrand).together();
30466        assert!(
30467            residual_is_zero(&residual),
30468            "primitive derivative mismatch: {residual}"
30469        );
30470    }
30471
30472    #[test]
30473    fn matches_general_binomial_sum_simpler_high_m_reduction() {
30474        let x = symbol!("x");
30475        let integrand = parse!("x^3*(1+x^2)^-3");
30476        let primitive = downvalue_primitive(844, &integrand, x);
30477        let residual = (primitive.derivative(x) - integrand).together();
30478        assert!(
30479            residual_is_zero(&residual),
30480            "primitive derivative mismatch: {residual}"
30481        );
30482    }
30483
30484    #[test]
30485    fn matches_balanced_general_binomial_high_m_int_binomial_reduction() {
30486        let x = symbol!("x");
30487        let integrand = parse!("x^7*(1+x^2)^-3*(1-x^2)^-3");
30488        let primitive = downvalue_primitive(845, &integrand, x);
30489        let residual = (primitive.derivative(x) - integrand).together();
30490        assert!(
30491            residual_is_zero(&residual),
30492            "primitive derivative mismatch: {residual}"
30493        );
30494    }
30495
30496    #[test]
30497    fn matches_balanced_general_binomial_sum_simpler_high_m_reduction() {
30498        let x = symbol!("x");
30499        let integrand = parse!("x^7*(1+x^2)^-3*(1-x^2)^-3");
30500        let primitive = downvalue_primitive(846, &integrand, x);
30501        let residual = (primitive.derivative(x) - integrand).together();
30502        assert!(
30503            residual_is_zero(&residual),
30504            "primitive derivative mismatch: {residual}"
30505        );
30506    }
30507
30508    #[test]
30509    fn matches_general_binomial_low_m_int_binomial_reduction() {
30510        let x = symbol!("x");
30511        let integrand = parse!("x^-2*(1+x^2)^2");
30512        let primitive = downvalue_primitive(847, &integrand, x);
30513        let residual = (primitive.derivative(x) - integrand).together();
30514        assert!(
30515            residual_is_zero(&residual),
30516            "primitive derivative mismatch: {residual}"
30517        );
30518    }
30519
30520    #[test]
30521    fn matches_general_binomial_sum_simpler_low_m_reduction() {
30522        let x = symbol!("x");
30523        let integrand = parse!("x^-2*(1+x^2)^(-1/2)");
30524        let primitive = downvalue_primitive(848, &integrand, x);
30525        let residual = (primitive.derivative(x) - integrand).together();
30526        assert!(
30527            residual_is_zero(&residual),
30528            "primitive derivative mismatch: {residual}"
30529        );
30530    }
30531
30532    #[test]
30533    fn matches_balanced_general_binomial_low_m_int_binomial_reduction() {
30534        let x = symbol!("x");
30535        let integrand = parse!("x^-2*(1+x^2)^2*(1-x^2)^2");
30536        let primitive = downvalue_primitive(849, &integrand, x);
30537        let residual = (primitive.derivative(x) - integrand).together();
30538        assert!(
30539            residual_is_zero(&residual),
30540            "primitive derivative mismatch: {residual}"
30541        );
30542    }
30543
30544    #[test]
30545    fn matches_balanced_general_binomial_sum_simpler_low_m_reduction() {
30546        let x = symbol!("x");
30547        let integrand = parse!("x^-2*(1+x^2)^(-3/4)*(1-x^2)^(-3/4)");
30548        let primitive = downvalue_primitive(850, &integrand, x);
30549        let residual = (primitive.derivative(x) - integrand).together();
30550        assert!(
30551            residual_is_zero(&residual),
30552            "primitive derivative mismatch: {residual}"
30553        );
30554    }
30555
30556    #[test]
30557    fn matches_general_binomial_fractional_scaled_monomial_substitution() {
30558        let x = symbol!("x");
30559        let integrand = parse!("(2*x)^(1/2)*(1+x^3)^2");
30560        let primitive = downvalue_primitive(851, &integrand, x);
30561        let residual = (primitive.derivative(x) - integrand).together();
30562        assert!(
30563            residual_is_zero(&residual),
30564            "primitive derivative mismatch: {residual}"
30565        );
30566    }
30567
30568    #[test]
30569    fn matches_balanced_general_binomial_fractional_scaled_monomial_substitution() {
30570        let x = symbol!("x");
30571        let integrand = parse!("x^(1/2)*(1+x^(3/2))^2*(1-x^(3/2))^2");
30572        let primitive = downvalue_primitive(852, &integrand, x);
30573        let residual = (primitive.derivative(x) - integrand).together();
30574        assert!(
30575            residual_is_zero(&residual),
30576            "primitive derivative mismatch: {residual}"
30577        );
30578    }
30579
30580    #[test]
30581    fn matches_cubic_binomial_two_thirds_terminal_form() {
30582        let x = symbol!("x");
30583        let integrand = parse!("x/(1+x^3)^(2/3)");
30584        let primitive = downvalue_primitive(853, &integrand, x);
30585        let residual = (primitive.derivative(x) - integrand).together();
30586        assert!(
30587            residual_is_zero(&residual),
30588            "primitive derivative mismatch: {residual}"
30589        );
30590    }
30591
30592    #[test]
30593    fn matches_general_binomial_integer_exponent_sum_substitution() {
30594        let x = symbol!("x");
30595        let integrand = parse!("x*(1+x^3)^(-2/3)");
30596        let primitive = downvalue_primitive(854, &integrand, x);
30597        let residual = (primitive.derivative(x) - integrand).together();
30598        assert!(
30599            residual_is_zero(&residual),
30600            "primitive derivative mismatch: {residual}"
30601        );
30602    }
30603
30604    #[test]
30605    fn matches_balanced_general_binomial_integer_exponent_sum_substitution() {
30606        let x = symbol!("x");
30607        let integrand = parse!("x*(1+x^3)^(-1/3)*(1-x^3)^(-1/3)");
30608        let primitive = downvalue_primitive(855, &integrand, x);
30609        assert!(
30610            !rubi_contains_unintegrable(&primitive),
30611            "DownValue 855 should produce its substitution payload: {primitive}"
30612        );
30613    }
30614
30615    #[test]
30616    fn matches_downvalues_856_through_863_source_substitutions() {
30617        let x = symbol!("x");
30618        let cases = [
30619            (856, parse!("x*(1+x^3)^(-2/3)")),
30620            (857, parse!("x*(1+x^3)^(-1/3)*(1-x^3)^(-1/3)")),
30621            (858, parse!("x*(1+x^-2)^2")),
30622            (859, parse!("x*(1+x^-2)^2*(1-x^-2)^2")),
30623            (860, parse!("(2*x)^(1/2)*(1+x^-2)^2")),
30624            (861, parse!("x^(1/2)*(1+x^-2)^2*(1-x^-2)^2")),
30625            (862, parse!("(2*x)^q*(1+x^-2)^2")),
30626            (863, parse!("(2*x)^q*(1+x^-2)^2*(1-x^-2)^2")),
30627        ];
30628
30629        for (order, integrand) in cases {
30630            let primitive = downvalue_primitive(order, &integrand, x);
30631            assert!(
30632                !primitive.is_zero(),
30633                "Rubi DownValue {order} should produce its source substitution payload"
30634            );
30635        }
30636    }
30637
30638    #[test]
30639    fn matches_downvalues_864_through_871_source_substitutions() {
30640        let x = symbol!("x");
30641        let cases = [
30642            (864, parse!("x*(1+x^(1/2))^2")),
30643            (865, parse!("x*(1+x^(1/4))^2*(1-x^(1/4))^2")),
30644            (866, parse!("(2*x)^(1/3)*(1+x^(1/2))^2")),
30645            (867, parse!("(2*x)^(1/3)*(1+x^(1/4))^2*(1-x^(1/4))^2")),
30646            (868, parse!("x^(-1/2)*(1+x^(1/2))^2")),
30647            (869, parse!("x^(-1/2)*(1+x^(1/4))^2*(1-x^(1/4))^2")),
30648            (870, parse!("(2*x)^(-1/2)*(1+x^(1/2))^2")),
30649            (871, parse!("(2*x)^(-1/2)*(1+x^(1/4))^2*(1-x^(1/4))^2")),
30650        ];
30651
30652        for (order, integrand) in cases {
30653            let primitive = downvalue_primitive(order, &integrand, x);
30654            assert!(
30655                !primitive.is_zero(),
30656                "Rubi DownValue {order} should produce its source substitution payload"
30657            );
30658        }
30659    }
30660
30661    #[test]
30662    fn matches_downvalues_872_through_877_source_recurrences() {
30663        let x = symbol!("x");
30664        let cases = [
30665            (872, parse!("x^-5*(1+x^2)^2")),
30666            (873, parse!("x^-9*(1+x^2)^2*(1-x^2)^2")),
30667            (874, parse!("(2*x)^(-5/2)*(1+x^3)^(1/2)")),
30668            (
30669                875,
30670                parse!("(2*x)^(-5/2)*(1+x^(3/2))^(1/2)*(1-x^(3/2))^(1/2)"),
30671            ),
30672            (876, parse!("x*(1+x^2)^2")),
30673            (877, parse!("x^3*(1+x^2)^2*(1-x^2)^2")),
30674        ];
30675
30676        for (order, integrand) in cases {
30677            let primitive = downvalue_primitive(order, &integrand, x);
30678            assert!(
30679                !primitive.is_zero(),
30680                "Rubi DownValue {order} should produce its source recurrence payload"
30681            );
30682        }
30683    }
30684
30685    #[test]
30686    fn matches_downvalues_878_through_884_source_recurrences() {
30687        let x = symbol!("x");
30688        let cases = [
30689            (878, parse!("x^3*(1+x^2)^-2")),
30690            (879, parse!("x^3*(1+x^2)^-2*(1-x^2)^-2")),
30691            (880, parse!("x*(1+x^4)^(-1/2)")),
30692            (881, parse!("x*(1+x^2)^(-1/2)*(1-x^2)^(-1/2)")),
30693            (882, parse!("x*(1+x^2)^2")),
30694            (883, parse!("(2*x)^(1/3)*(1+x^2)^(1/3)")),
30695            (884, parse!("(2*x)^(1/3)*(1+x^2)^(2/3)*(1-x^2)^(2/3)")),
30696        ];
30697
30698        for (order, integrand) in cases {
30699            let primitive = downvalue_primitive(order, &integrand, x);
30700            assert!(
30701                !primitive.is_zero(),
30702                "Rubi DownValue {order} should produce its source recurrence payload"
30703            );
30704        }
30705    }
30706
30707    #[test]
30708    fn downvalue_1304_preserves_unary_neq_guard() {
30709        let x = symbol!("x");
30710        let integrand = parse!("sqrt(1+2*x+3*x^2)/(2+4*x^2)^2");
30711        let rule = rubi_rules()
30712            .iter()
30713            .find(|rule| rule.downvalue_order == Some(1304))
30714            .expect("Rubi DownValue 1304 should exist");
30715        assert!(
30716            matcher_rule_for_test(&integrand, x, rule).is_none(),
30717            "Rubi's unary NeQ guard is unevaluated and must not fire"
30718        );
30719    }
30720
30721    #[test]
30722    fn integrates_generated_log_over_variable_payload_for_exponential_log_rule() {
30723        let x = symbol!("x");
30724        let x_atom = Atom::var(x);
30725        let integrand = (Atom::num(1) - &x_atom / Atom::num(3)).log() / x_atom;
30726        let primitive = integrate_generated_payload(&integrand, x).unwrap_or_else(|| {
30727            panic!("Rubi generated log-over-variable payload should integrate: {integrand}")
30728        });
30729        assert!(
30730            !rubi_contains_unintegrable(&primitive),
30731            "payload integration should not return unintegrable: {primitive}"
30732        );
30733        assert!(
30734            primitive.to_string().contains("polylog"),
30735            "payload should use Rubi polylog rule: {primitive}"
30736        );
30737    }
30738
30739    #[test]
30740    fn integrates_log_of_collapsed_source_exponential() {
30741        let x = symbol!("x");
30742        let exponential = Atom::num(2).pow(Atom::i() * Atom::num(2) * Atom::var(x));
30743        let integrand = (Atom::num(1) - exponential / Atom::num(3)).log();
30744        let primitive = integrate(&integrand, x)
30745            .unwrap_or_else(|_| panic!("Rubi exponential-log rule should integrate: {integrand}"));
30746        assert!(
30747            !rubi_contains_unintegrable(&primitive),
30748            "exponential-log integration should not return unintegrable: {primitive}"
30749        );
30750        assert!(
30751            primitive.to_string().contains("polylog"),
30752            "exponential-log integration should use Rubi polylog substitution: {primitive}"
30753        );
30754    }
30755
30756    #[test]
30757    fn integrates_bondarenko_41_substituted_log_rational_payload() {
30758        let x = symbol!("x");
30759        let integrand = Atom::var(x) * (Atom::var(x).pow(2) + Atom::var(x) - 1).log()
30760            / (Atom::var(x).pow(2) - 1);
30761        let primitive = integrate_generated_payload(&integrand, x)
30762            .unwrap_or_else(|| panic!("Rubi substituted payload should integrate: {integrand}"));
30763        assert!(
30764            !rubi_contains_unintegrable(&primitive),
30765            "payload integration should not return unintegrable: {primitive}"
30766        );
30767    }
30768
30769    #[test]
30770    fn integrates_line41_generated_quadratic_log_partial_fraction_sum() {
30771        let x = symbol!("x");
30772        let x_atom = Atom::var(x);
30773        let quadratic = x_atom.pow(2) + &x_atom - 1;
30774        let quadratic_log = quadratic.log();
30775        let integrand = Atom::num(1) / Atom::num(2) * &quadratic_log / (Atom::num(1) + &x_atom)
30776            + Atom::num(1) / Atom::num(2) * &quadratic_log / (-Atom::num(1) + &x_atom);
30777        let primitive = integrate_generated_payload(&integrand, x).unwrap_or_else(|| {
30778            panic!("generated partial-fraction sum should integrate: {integrand}")
30779        });
30780
30781        assert!(
30782            !rubi_contains_unintegrable(&primitive),
30783            "generated partial-fraction sum should not return unintegrable: {primitive}"
30784        );
30785    }
30786
30787    #[test]
30788    fn int_hide_integrates_line41_log_derivative_rational() {
30789        let x = symbol!("x");
30790        let x_atom = Atom::var(x);
30791        let quadratic = x_atom.pow(2) + &x_atom - 1;
30792        let rational = (Atom::num(2) * &x_atom + 1) / quadratic;
30793        let primitive = rubi_int_hide(&rational, x)
30794            .unwrap_or_else(|| panic!("IntHide should integrate rational derivative {rational}"));
30795
30796        assert!(
30797            !rubi_contains_unintegrable(&primitive),
30798            "IntHide rational primitive should not be unintegrable: {primitive}"
30799        );
30800    }
30801
30802    #[test]
30803    fn integrates_line41_generated_linear_log_payload() {
30804        let x = symbol!("x");
30805        let x_atom = Atom::var(x);
30806        let quadratic = x_atom.pow(2) + &x_atom - 1;
30807        let integrand = (Atom::num(2) * &x_atom + 1) * (&x_atom - 1).log() / quadratic;
30808        let primitive = integrate_generated_payload(&integrand, x)
30809            .unwrap_or_else(|| panic!("generated line-41 payload should integrate: {integrand}"));
30810
30811        assert!(
30812            !rubi_contains_unintegrable(&primitive),
30813            "generated line-41 payload should not return unintegrable: {primitive}"
30814        );
30815    }
30816
30817    #[test]
30818    fn integrates_line41_expanded_linear_log_term() {
30819        let x = symbol!("x");
30820        let x_atom = Atom::var(x);
30821        let integrand = Atom::num(2) * (&x_atom - 1).log()
30822            / (Atom::num(1) + Atom::num(2) * &x_atom + Atom::num(5).sqrt());
30823        let primitive = integrate_generated_payload(&integrand, x)
30824            .unwrap_or_else(|| panic!("expanded line-41 term should integrate: {integrand}"));
30825
30826        assert!(
30827            !rubi_contains_unintegrable(&primitive),
30828            "expanded line-41 term should not return unintegrable: {primitive}"
30829        );
30830    }
30831
30832    #[test]
30833    fn skips_polynomial_constant_base_linear_exponential_until_expand_integrand_payload_is_covered()
30834    {
30835        let x = symbol!("x");
30836        let integrand = parse!("x*2^(1+x)");
30837        let primitive = rubi_rules()
30838            .iter()
30839            .filter(|rule| rule.id == "Rubi 2.3.2")
30840            .find_map(|rule| matcher_rule_for_test(&integrand, x, rule));
30841        assert!(
30842            primitive.is_none(),
30843            "block 2 should wait for source-shaped ExpandIntegrand payload coverage"
30844        );
30845    }
30846
30847    #[test]
30848    fn power_of_linear_normalizes_expanded_linear_power_like_rubi() {
30849        let x = symbol!("x");
30850        let expanded = parse!("d^3+3*d^2*e*x+3*d*e^2*x^2+e^3*x^3");
30851        let normalized = rubi_normalize_power_of_linear(&expanded, x)
30852            .expect("Rubi NormalizePowerOfLinear factors expanded linear powers");
30853
30854        assert_eq!(normalized, parse!("(d+e*x)^3"));
30855    }
30856
30857    #[test]
30858    fn integrates_exp_over_expanded_linear_power_denominator_like_rubi() {
30859        let x = symbol!("x");
30860        let integrand = parse!("F^(c*(a+b*x))/(d^3+3*d^2*e*x+3*d*e^2*x^2+e^3*x^3)");
30861        let primitive =
30862            integrate(&integrand, x).unwrap_or_else(|_| panic!("rule should apply to {integrand}"));
30863
30864        assert!(
30865            !primitive.to_string().contains("unintegrable"),
30866            "Rubi should integrate via PowerOfLinearQ/NormalizePowerOfLinear: {primitive}"
30867        );
30868    }
30869
30870    #[test]
30871    fn integrates_optional_zero_log_over_variable_linear() {
30872        let x = symbol!("x");
30873        let integrand = parse!("log(x)/x");
30874        let primitive = integrate(&integrand, x)
30875            .expect("optional zero linear log-over-variable rule should apply");
30876        let residual = (primitive.derivative(x) - integrand).together();
30877        assert!(
30878            residual_is_zero(&residual),
30879            "primitive derivative mismatch: {residual}; primitive: {primitive}"
30880        );
30881    }
30882
30883    #[test]
30884    fn integrates_constant_times_log_over_variable_linear() {
30885        let x = symbol!("x");
30886        let integrand = parse!("e*log(x)/x");
30887        let primitive =
30888            integrate(&integrand, x).expect("constant multiple of log-over-variable should apply");
30889        let residual = (primitive.derivative(x) - integrand).together();
30890        assert!(
30891            residual_is_zero(&residual),
30892            "primitive derivative mismatch: {residual}; primitive: {primitive}"
30893        );
30894    }
30895
30896    #[test]
30897    fn integrates_high_power_monomial_log_recurrence_without_rhs_recomputation() {
30898        let x = symbol!("x");
30899        let integrand = parse!("x^9*log(x)^11");
30900        let primitive = integrate(&integrand, x)
30901            .expect("positive monomial-log recurrence should apply without hanging");
30902        let residual = (primitive.derivative(x) - integrand).together();
30903        assert!(
30904            residual_is_zero(&residual),
30905            "primitive derivative mismatch: {residual}"
30906        );
30907    }
30908
30909    #[test]
30910    fn integrates_affine_times_log_square_with_already_expanded_base() {
30911        assert_derivative_round_trip(parse!("(d+e*x)*(a+b*log(c*x^n))^2"));
30912    }
30913
30914    #[test]
30915    fn integrates_section_3_1_4_linear_binomial_log_over_x_squared() {
30916        let x = symbol!("x");
30917        let integrand = parse!("(d+e*x)*(a+b*log(c*x^n))/x^2");
30918        let primitive = integrate(&integrand, x)
30919            .expect("Section 3.1.4 linear binomial-log corpus row should integrate");
30920        let residual = (primitive.derivative(x) - integrand).together();
30921        assert!(
30922            residual_is_zero(&residual),
30923            "primitive derivative mismatch: {residual}; primitive: {primitive}"
30924        );
30925    }
30926
30927    #[test]
30928    fn integrates_section_3_1_4_expanded_linear_binomial_log_partial_fractions() {
30929        assert_derivative_round_trip(parse!("(a+b*log(c*x^n))/(x^3*(d+e*x)^4)"));
30930    }
30931
30932    #[test]
30933    fn integrates_section_3_1_4_high_order_linear_binomial_log_sum_promptly() {
30934        assert_derivative_round_trip(parse!("(a+b*log(c*x^n))/(x^2*(d+e*x)^7)"));
30935    }
30936
30937    #[test]
30938    fn integrates_symbolic_negative_linear_exponential_times_half_power_recurrence() {
30939        assert_derivative_round_trip(parse!("x^(13/2)*e^(-b*x)"));
30940    }
30941
30942    #[test]
30943    fn integrates_timofeev_894_via_rubi_inverse_sine_reduction_path() {
30944        let x = symbol!("x");
30945        let integrand = parse!("asin(x)/(1-x^2)^(5/2)");
30946        let primitive =
30947            integrate(&integrand, x).expect("Timofeev line 894 should follow Rubi rules 5162/5160");
30948        let residual = (primitive.derivative(x) - integrand).together();
30949
30950        assert!(
30951            !rubi_contains_unintegrable(&primitive),
30952            "primitive should not contain internal unintegrable marker: {primitive}"
30953        );
30954        assert!(
30955            residual_is_zero(&residual),
30956            "primitive derivative mismatch: {residual}"
30957        );
30958    }
30959
30960    #[test]
30961    fn generated_payload_integrates_negative_quadratic_exponential() {
30962        let sub1 = symbol!("sub1");
30963        let integrand = parse!("2^(-sub1^2)");
30964        let primitive = integrate_generated_payload(&integrand, sub1)
30965            .expect("generated negative quadratic exponential should integrate");
30966        let residual = (primitive.derivative(sub1) - integrand).together();
30967        assert!(
30968            residual_is_zero(&residual),
30969            "primitive derivative mismatch: {residual}"
30970        );
30971    }
30972
30973    #[test]
30974    fn integrates_polylog_regression_rule() {
30975        assert_derivative_round_trip(parse!("polylog(2, x)"));
30976        assert_derivative_round_trip(parse!("log(1 - 2*x)/x"));
30977        assert_derivative_round_trip(parse!("polylog(2, x)/x"));
30978        assert_derivative_round_trip(parse!("polylog(2, 3*x)/x"));
30979        assert_derivative_round_trip(parse!("polylog(2, 3*x^2)/x"));
30980        assert_derivative_round_trip(parse!("polylog(3, 3*x^2)/x"));
30981        assert_derivative_round_trip(parse!("polylog(2, 5*(2^(3*(1 + 7*x)))^11)"));
30982        assert_derivative_round_trip(parse!("polylog(2, 3*x)"));
30983        assert_derivative_round_trip(parse!("polylog(3, 3*x)"));
30984        assert_derivative_round_trip(parse!("polylog(2, 3*x^2)"));
30985        assert_derivative_round_trip(parse!("polylog(3, 3*x^2)"));
30986        assert_derivative_round_trip(parse!("x*polylog(2, 3*x)"));
30987        assert_derivative_round_trip(parse!("x^2*polylog(2, 3*x)"));
30988        assert_derivative_round_trip(parse!("x^3*polylog(2, 3*x)"));
30989        assert_derivative_round_trip(parse!("x^4*polylog(2, 3*x)"));
30990        assert_derivative_round_trip(parse!("x*polylog(3, 3*x)"));
30991        assert_derivative_round_trip(parse!("x^2*polylog(3, 3*x)"));
30992        assert_derivative_round_trip(parse!("x^3*polylog(3, 3*x)"));
30993        assert_derivative_round_trip(parse!("x*polylog(2, 3*x^2)"));
30994        assert_derivative_round_trip(parse!("x^3*polylog(2, 3*x^2)"));
30995        assert_derivative_round_trip(parse!("x^5*polylog(2, 3*x^2)"));
30996        assert_derivative_round_trip(parse!("x*polylog(3, 3*x^2)"));
30997        assert_derivative_round_trip(parse!("x^3*polylog(3, 3*x^2)"));
30998        assert_derivative_round_trip(parse!("x^5*polylog(3, 3*x^2)"));
30999        assert_derivative_round_trip(parse!("polylog(2, 5*(1 + 3*x))"));
31000        assert_derivative_round_trip(parse!("polylog(2, 1 + 3*x)"));
31001        assert_derivative_round_trip(parse!("polylog(3, 5*(1 + 3*x))"));
31002        assert_derivative_round_trip(parse!("polylog(3, 1 + 3*x)"));
31003        assert_derivative_round_trip(parse!("polylog(1, 1/(x+y))"));
31004        assert_derivative_round_trip(parse!("polylog(2, 1/(x+y))"));
31005        assert_derivative_round_trip(parse!("polylog(3, 1/(x+y))"));
31006        assert_derivative_round_trip(parse!("polylog(4, 5/(2+3*x))"));
31007        assert_derivative_round_trip(parse!("polylog(4, (a+b*x)^3)"));
31008    }
31009
31010    #[test]
31011    fn integrates_low_degree_rational_dilogarithms() {
31012        assert_derivative_round_trip(parse!("polylog(2, (1+x)/(2+x))"));
31013        assert_derivative_round_trip(parse!("polylog(2, 1/(1+x+x^2))"));
31014        assert_derivative_round_trip(parse!("polylog(2, 1+x+x^2)"));
31015        assert_derivative_round_trip(parse!("polylog(2, x*(1+x)/(2+x)^2)"));
31016        assert_derivative_round_trip(parse!("polylog(2, x/(x+y)^2)"));
31017    }
31018
31019    #[test]
31020    fn derivative_divides_strips_x_power_before_easy_dq() {
31021        let x = symbol!("x");
31022        let y = parse!("a*x*cos(a*x)-sin(a*x)");
31023        let u = parse!("x*sin(a*x)");
31024
31025        assert_eq!(
31026            rubi_derivative_divides(&y, &u, x),
31027            Some(parse!("-1/a^2")),
31028            "Rubi EasyDQ strips x^m before testing the remaining product"
31029        );
31030    }
31031
31032    #[test]
31033    fn derivative_divides_scaled_x_guard_is_structural() {
31034        let x = symbol!("x");
31035
31036        assert!(rubi_optional_free_coefficient_times_x_q(&parse!("x"), x));
31037        assert!(rubi_optional_free_coefficient_times_x_q(&parse!("a*x"), x));
31038        assert!(!rubi_optional_free_coefficient_times_x_q(
31039            &parse!("x*(a+x)"),
31040            x,
31041        ));
31042        assert!(!rubi_optional_free_coefficient_times_x_q(
31043            &parse!("(x+x^2)/(1+x)"),
31044            x,
31045        ));
31046    }
31047
31048    #[test]
31049    fn derivative_divides_uses_exact_polynomial_proportionality() {
31050        let x = symbol!("x");
31051        let y = parse!("1+2*x+3*x^2");
31052
31053        assert_eq!(
31054            rubi_derivative_divides(&y, &parse!("a*(2+6*x)"), x),
31055            Some(parse!("a"))
31056        );
31057        assert_eq!(rubi_derivative_divides(&y, &parse!("1+x"), x), None);
31058    }
31059
31060    #[test]
31061    fn derivative_divides_accepts_unary_exponential_integral() {
31062        let x = symbol!("x");
31063        let b = Atom::var(symbol!("b"));
31064        let bx = b * Atom::var(x);
31065        let y = rubi_exp_integral_ei(bx.to_owned());
31066        let u = bx.exp() / Atom::var(x);
31067
31068        assert_eq!(
31069            rubi_derivative_divides(&y, &u, x),
31070            Some(Atom::num(1)),
31071            "Rubi EasyDQ recurses into every unary non-calculus function"
31072        );
31073    }
31074
31075    #[test]
31076    fn derivative_divides_simplifies_fractional_linear_power_quotient() {
31077        let x = symbol!("x");
31078        let ratio = parse!("(a+b*x)/(c+d*x)");
31079        let y = Atom::num(1) - parse!("e") * ratio.pow(parse!("n"));
31080        let u = parse!("(a+b*x)^(-1+n)*(c+d*x)^(-1-n)");
31081        let quotient = rubi_derivative_divides(&y, &u, x)
31082            .expect("Mathematica Simplify makes the DerivativeDivides quotient constant");
31083        let expected = parse!("-1/(e*n*(b*c-a*d))");
31084        assert!(
31085            (quotient - expected).together().is_zero(),
31086            "unexpected DerivativeDivides quotient"
31087        );
31088    }
31089
31090    #[test]
31091    fn derivative_divides_simplifies_bondarenko_349_radical_quotient() {
31092        let x = symbol!("x");
31093        let y = Atom::num(1) + Atom::i() * parse!("sqrt(1-a*x)") / parse!("sqrt(1+a*x)");
31094        let u = (Atom::num(1) - &y) / parse!("1-a^2*x^2");
31095
31096        assert_eq!(
31097            rubi_derivative_divides(&y, &u, x),
31098            Some(parse!("1/a")),
31099            "Mathematica Simplify reduces the rule-2998 DerivativeDivides quotient"
31100        );
31101    }
31102
31103    #[test]
31104    fn derivative_divides_simplifies_arcsech_logarithm_quotient() {
31105        let x = symbol!("x");
31106        let discriminant = parse!("sqrt(-c^2*d^2+e^2)");
31107        let u = parse!("sqrt((1-c*x)/(1+c*x))/(x*(1-c*x))");
31108        let v = Atom::num(1)
31109            + (parse!("e") - discriminant) / (parse!("c*d") * parse!("exp(asech(c*x))"));
31110        let target = &u * (Atom::num(1) - &v);
31111
31112        assert_eq!(rubi_derivative_divides(&v, &target, x), Some(Atom::num(-1)));
31113        let normalized_u = parse!("1/(x*sqrt(1+c*x)*sqrt(1-c*x))");
31114        assert_eq!(
31115            rubi_derivative_divides(&v, &(&normalized_u * (Atom::num(1) - &v)), x,),
31116            Some(Atom::num(-1))
31117        );
31118    }
31119
31120    #[test]
31121    fn derivative_divides_rejects_nonconstant_algebraic_quotient() {
31122        let x = symbol!("x");
31123        let y = parse!("x*(-3+x^(27/2))");
31124        let u = parse!("(-1/3+4*x^(25/2))*(-3+x^(27/2))^(-40)");
31125
31126        assert_eq!(rubi_derivative_divides(&y, &u, x), None);
31127    }
31128
31129    #[test]
31130    fn derivative_divides_simplifies_hyperbolic_logarithmic_derivative() {
31131        let x = symbol!("x");
31132        let y = parse!("log(tanh(x))");
31133        let u = parse!("sech(x)*csch(x)");
31134
31135        assert_eq!(
31136            rubi_mathematica_hyperbolic_quotient(&parse!("tanh(x)*csch(x)/sech(x)")),
31137            Some(Atom::num(1)),
31138            "Mathematica evaluates the chained hyperbolic quotient to 1"
31139        );
31140        assert_eq!(rubi_derivative_divides(&y, &u, x), Some(Atom::num(1)));
31141        let double_angle_quotient = parse!("csch(2*x)") / rubi_d(&y, x);
31142        let exponential_quotient =
31143            rubi_hyperbolic_trig_to_exp(double_angle_quotient.as_view()).together();
31144        assert_eq!(
31145            exponential_quotient,
31146            Atom::num(1) / 2,
31147            "hyperbolic exponential normalization should prove the double-angle quotient; got {exponential_quotient}"
31148        );
31149        assert_eq!(
31150            rubi_derivative_divides(&y, &parse!("csch(2*x)"), x),
31151            Some(Atom::num(1) / 2),
31152            "Mathematica Simplify applies the hyperbolic double-angle identity"
31153        );
31154    }
31155
31156    #[test]
31157    fn inert_fractional_product_rows_match_hyperbolic_square_root() {
31158        let x = symbol!("x");
31159        let deactivated = rubi_deactivate_trig(&parse!("sqrt(sinh(x)*tanh(x))"), x);
31160        let row_4898 = rubi_rules()
31161            .iter()
31162            .find(|rule| rule.downvalue_order == Some(4898))
31163            .expect("DownValue 4898 should be registered");
31164        let matches_4898 = matcher_rule_for_test(&deactivated, x, row_4898).is_some();
31165
31166        let argument = rubi_i() * Atom::var(x);
31167        let inert_product = (rubi_symbols().inert_sin.call(argument.to_owned())
31168            * rubi_symbols().inert_tan.call(argument))
31169        .sqrt();
31170        let row_4900 = rubi_rules()
31171            .iter()
31172            .find(|rule| rule.downvalue_order == Some(4900))
31173            .expect("DownValue 4900 should be registered");
31174        let matches_4900 = matcher_rule_for_test(&inert_product, x, row_4900).is_some();
31175
31176        assert!(matches_4900, "DownValue 4900 should match {inert_product}");
31177        assert!(matches_4898, "DownValue 4898 should match {deactivated}");
31178    }
31179
31180    #[test]
31181    fn matches_polylog_194_derivative_divides_substitution_row() {
31182        let x = symbol!("x");
31183        let integrand = parse!("polylog(-2,e*((a+b*x)/(c+d*x))^n)/((a+b*x)*(c+d*x))");
31184        let normalized = rubi_normalize_integrand(&integrand, x);
31185        let row = rubi_rules()
31186            .iter()
31187            .find(|rule| rule.downvalue_order == Some(7243))
31188            .expect("Rubi DownValue 7243 should be registered");
31189        let primitive = matcher_rule_for_test(&normalized, x, row)
31190            .unwrap_or_else(|| panic!("DownValue 7243 should match {normalized}"));
31191        let expected = parse!("e*((a+b*x)/(c+d*x))^n/((b*c-a*d)*n*(1-e*((a+b*x)/(c+d*x))^n)^2)");
31192
31193        let residual = (&primitive - &expected).together();
31194        assert!(
31195            is_free_of(&residual, x),
31196            "DownValue 7243 should follow the Mathematica polylog line 194 trace up to an integration constant\nexpected: {expected}\nactual: {primitive}\ndifference: {residual}"
31197        );
31198    }
31199
31200    #[test]
31201    fn integrates_rubi_9_4_simplify_integrand_before_sum_split() {
31202        let x = Symbol::parse("x", "rubi_corpus").unwrap();
31203        let integrand = Atom::parse(
31204            "e^x/(x+e^x)^(1/2)+1/(x+e^x)^(1/2)",
31205            "rubi_corpus",
31206            Default::default(),
31207        )
31208        .unwrap();
31209        let simplify_candidate =
31210            rubi_simplify_integrand_mathematica_simplify_candidate(&integrand, x)
31211                .expect("the shared Mathematica Simplify emulation should find the common factor");
31212        assert_eq!(
31213            simplify_candidate,
31214            Atom::parse("(1+e^x)/(x+e^x)^(1/2)", "rubi_corpus", Default::default()).unwrap(),
31215            "SimplifyIntegrand must start from Mathematica's Simplify[u] shape"
31216        );
31217        let simplified = rubi_simplify_integrand(&integrand, x);
31218
31219        assert_eq!(
31220            simplified,
31221            Atom::parse("(1+e^x)/(x+e^x)^(1/2)", "rubi_corpus", Default::default()).unwrap()
31222        );
31223        let primitive = integrate(&integrand, x).expect("Rubi 9.4 block 5 should apply");
31224        assert_eq!(
31225            primitive,
31226            Atom::parse("2*(x+e^x)^(1/2)", "rubi_corpus", Default::default()).unwrap()
31227        );
31228    }
31229
31230    #[test]
31231    fn integrates_bronstein_exponential_root_via_rubi_deferred_path() {
31232        let x = Symbol::parse("x", "rubi_corpus").unwrap();
31233        let integrand = Atom::parse(
31234            "(5*x^2+3*(e^x+x)^(1/3)+e^x*(3*x+2*x^2))/(x*(e^x+x)^(1/3))",
31235            "rubi_corpus",
31236            Default::default(),
31237        )
31238        .unwrap();
31239        let primitive =
31240            integrate(&integrand, x).expect("Bronstein Problems.input line 19 should integrate");
31241
31242        assert!(
31243            !rubi_contains_unintegrable(&primitive),
31244            "primitive should not retain unintegrable terms: {primitive}"
31245        );
31246        let residual = primitive.derivative(x) - integrand;
31247        let residual = rubi_normalize_euler_logs(residual.as_view()).together();
31248
31249        assert!(
31250            residual_is_zero(&residual),
31251            "primitive derivative mismatch: {residual}; primitive: {primitive}"
31252        );
31253    }
31254
31255    #[test]
31256    fn algebraic_zero_binomial_uses_the_opening_rubi_simplification_row() {
31257        let x = symbol!("x");
31258        let integrand = parse!("1/sqrt(2+2*a-2*(1+a)+c*x^4)");
31259        let primitive = integrate(&integrand, x).expect("loaded Rubi DownValue 1 should apply");
31260
31261        assert_eq!(primitive, parse!("-x/sqrt(c*x^4)"));
31262    }
31263
31264    #[test]
31265    fn quadratic_linear_numerator_split_precedes_polynomial_expansion() {
31266        let x = symbol!("x");
31267        let integrand = parse!("sqrt(d+e*x)/(a+c*x^2)");
31268        let primitive = integrate(&integrand, x).expect("loaded Rubi DownValue 483 should apply");
31269
31270        assert!(!rubi_contains_unintegrable(&primitive));
31271    }
31272
31273    #[test]
31274    fn builds_rubi_3_5_fractional_power_of_linear_substitution_payload() {
31275        let x = symbol!("x");
31276        let sub = symbol!("sub1");
31277        let payload =
31278            rubi_subst_for_fractional_power_of_linear(&parse!("x*log((1+x)^(1/2))"), x, sub)
31279                .expect("fractional power of linear helper should apply");
31280
31281        assert_eq!(payload.denominator, 2);
31282        assert!(residual_is_zero(&(payload.base - parse!("1+x"))));
31283        assert!(is_free_of(&payload.integrand, x));
31284        assert!(!is_free_of(&payload.integrand, sub));
31285        assert!(is_free_of(&payload.multiplier, sub));
31286    }
31287
31288    #[test]
31289    fn fractional_power_of_linear_simplifies_timofeev_315_payload() {
31290        let x = symbol!("x");
31291        let sub = symbol!("sub1");
31292        let integrand =
31293            parse!("x*(1+x)^(2/3)*sqrt(1-x)/(-(1-x)^(5/6)*(1+x)^(1/3)+(1-x)^(2/3)*sqrt(1+x))");
31294        let normalized = rubi_normalize_integrand(&integrand, x);
31295        let payload = rubi_subst_for_fractional_power_of_linear(&normalized, x, sub)
31296            .expect("Timofeev line 315 should use Rubi SubstForFractionalPowerOfLinear");
31297        assert_eq!(payload.denominator, 6);
31298        assert!(
31299            rubi_equivalent_q(&payload.base, &parse!("1-x")),
31300            "selected base should match the Mathematica trace after NormalizeIntegrand, got {} from normalized {}",
31301            payload.base,
31302            normalized
31303        );
31304        let expected = parse!("sub1^4*(2-sub1^6)^(1/3)*(-1+sub1^6)/(-sub1+(2-sub1^6)^(1/6))");
31305        assert_eq!(
31306            payload.integrand, expected,
31307            "SubstForFractionalPowerOfLinear should preserve Mathematica's compact Simplify result"
31308        );
31309        assert_eq!(payload.multiplier, Atom::num(1));
31310    }
31311
31312    #[test]
31313    fn normalize_integrand_matches_timofeev_315_rubi_trace() {
31314        let x = symbol!("x");
31315        let integrand =
31316            parse!("x*(1+x)^(2/3)*sqrt(1-x)/(-(1-x)^(5/6)*(1+x)^(1/3)+(1-x)^(2/3)*sqrt(1+x))");
31317        let normalized = rubi_normalize_integrand(&integrand, x);
31318        let expected = parse!("x*(1+x)^(1/3)/((1-x)^(1/6)*(-(1-x)^(1/6)+(1+x)^(1/6)))");
31319
31320        assert!(
31321            rubi_equivalent_q(&normalized, &expected),
31322            "NormalizeIntegrand should follow Mathematica rule 7292 trace\nexpected: {expected}\nactual: {normalized}"
31323        );
31324        assert!(
31325            rubi_leaf_count(normalized.as_view()) <= rubi_leaf_count(expected.as_view()) + 4,
31326            "NormalizeIntegrand should keep the compact traced shape\nexpected: {expected}\nactual: {normalized}"
31327        );
31328    }
31329
31330    #[test]
31331    fn expand_integrand_preserves_normalized_timofeev_315_rubi_trace() {
31332        let x = symbol!("x");
31333        let normalized = parse!("x*(1+x)^(1/3)/((1-x)^(1/6)*(-(1-x)^(1/6)+(1+x)^(1/6)))");
31334
31335        assert_eq!(
31336            rubi_expand_integrand(&normalized, x),
31337            normalized,
31338            "Mathematica ExpandIntegrand leaves the normalized payload unchanged"
31339        );
31340    }
31341
31342    #[test]
31343    fn normalize_integrand_does_not_refactor_integer_power_rational_sum_cycle() {
31344        let x = symbol!("x");
31345        let sum = parse!("A/x^4+B/x^3");
31346        let normalized = rubi_normalize_integrand(&sum, x);
31347
31348        assert!(
31349            rubi_equivalent_q(&normalized, &sum),
31350            "NormalizeIntegrand should preserve the rational sum; got {normalized}"
31351        );
31352    }
31353
31354    #[test]
31355    fn normalize_integrand_preserves_hearn_346_like_mathematica() {
31356        let y = symbol!("y");
31357        let integrand = parse!("(1+2*y)*sqrt(1-5*y-5*y^2)/(y*(1+y)*(2+y)*sqrt(1-y-y^2))");
31358        let normalized = rubi_normalize_integrand(&integrand, y);
31359
31360        assert_eq!(
31361            normalized, integrand,
31362            "Mathematica NormalizeIntegrand leaves Hearn line 346 unchanged; got {normalized}"
31363        );
31364    }
31365
31366    #[test]
31367    fn together_simplify_factors_timofeev_315_radical_sum_like_mathematica() {
31368        let x = symbol!("x");
31369        let input = parse!("-(1-x)^(5/6)*(1+x)^(1/3)+(1-x)^(2/3)*(1+x)^(1/2)");
31370        let expected = parse!("(1-x)^(2/3)*(1+x)^(1/3)*(-(1-x)^(1/6)+(1+x)^(1/6))");
31371        let actual = rubi_together_simplify(&input);
31372
31373        assert_eq!(actual, expected, "TogetherSimplify payload differs");
31374        assert_eq!(rubi_leaf_count(input.as_view()), 36);
31375        assert_eq!(rubi_leaf_count(actual.as_view()), 36);
31376        assert!(!rubi_binomial_q(input.as_view(), x));
31377        assert!(!rubi_trinomial_q(&input, x));
31378        assert_eq!(
31379            rubi_normalize_integrand_factor_base(&input, x),
31380            expected,
31381            "NormalizeIntegrandFactorBase payload differs"
31382        );
31383    }
31384
31385    #[test]
31386    fn together_simplify_combines_exact_radical_base_factor_like_mathematica() {
31387        let input = parse!("1/(d^2*sqrt(-1/d^2)*sqrt(4*c*a-b^2))");
31388        let expected = parse!("-sqrt(-1/d^2)/sqrt(4*c*a-b^2)");
31389
31390        assert_eq!(
31391            rubi_together_simplify(&input),
31392            expected,
31393            "Mathematica Simplify combines the exact -d^-2 radical base"
31394        );
31395        assert!(!rubi_pos_q(&input));
31396        assert!(rubi_neg_q(&input));
31397    }
31398
31399    #[test]
31400    fn fractional_power_of_linear_ignores_different_later_linear_base_like_rubi() {
31401        let x = symbol!("x");
31402        let sub = symbol!("sub1");
31403        let payload =
31404            rubi_subst_for_fractional_power_of_linear(&parse!("1/(2*sqrt(x)+sqrt(1+x))^2"), x, sub)
31405                .expect(
31406                    "Rubi chooses the first fractional linear base and keeps scanning later bases",
31407                );
31408
31409        assert_eq!(payload.denominator, 2);
31410        assert!(residual_is_zero(&(payload.base - parse!("x"))));
31411        assert!(rubi_equivalent_q(
31412            &payload.integrand,
31413            &parse!("sub1/(2*sub1+sqrt(1+sub1^2))^2")
31414        ));
31415        assert!(rubi_equivalent_q(&payload.multiplier, &parse!("1")));
31416    }
31417
31418    #[test]
31419    fn integrates_linear_times_shifted_cubic_root_regression() {
31420        let z = symbol!("z");
31421        let integrand = parse!("z*(-1+z)^(1/3)");
31422        let primitive = integrate(&integrand, z)
31423            .expect("linear factor times shifted cubic root should integrate");
31424        let residual = (primitive.derivative(z) - integrand).together();
31425
31426        assert!(
31427            residual_is_zero(&residual),
31428            "primitive derivative mismatch: {residual}"
31429        );
31430    }
31431
31432    #[test]
31433    fn keeps_symbolic_polylog_log_derivative_rules_rubi_shaped() {
31434        let x = symbol!("x");
31435        let linear = integrate(&parse!("polylog(n, 3*x)/x"), x)
31436            .expect("symbolic-order linear polylog rule should apply");
31437        let power = integrate(&parse!("polylog(n, 3*x^q)/x"), x)
31438            .expect("symbolic-order power polylog rule should apply");
31439
31440        assert_eq!(linear, parse!("polylog(1 + n, 3*x)"));
31441        assert_eq!(power, parse!("polylog(1 + n, 3*x^q)/q"));
31442    }
31443
31444    #[test]
31445    fn keeps_symbolic_order_polygamma_rule_rubi_shaped() {
31446        let x = symbol!("x");
31447        let primitive = integrate(&parse!("polygamma(n, 1 + 3*x)"), x)
31448            .expect("symbolic-order polygamma rule should apply");
31449
31450        assert_eq!(primitive, parse!("polygamma(-1 + n, 1 + 3*x)/3"));
31451    }
31452
31453    #[test]
31454    fn integrates_scaled_monomial_affine_power_hypergeometric_row() {
31455        let x = symbol!("x");
31456        let primitive =
31457            integrate(&parse!("(2*x)^q*(1+x)^(-3)"), x).expect("Rubi 1.1.1.2.H.1.1 should apply");
31458        let text = primitive.to_string();
31459
31460        assert!(
31461            text.contains("hypergeometric_2f1"),
31462            "primitive should contain opaque Hypergeometric2F1 RHS: {text}"
31463        );
31464        assert!(
31465            text.contains('q'),
31466            "primitive should keep the symbolic exponent: {text}"
31467        );
31468    }
31469
31470    #[test]
31471    fn integrates_corpus_1112_line_1124_via_scaled_power_normalization() {
31472        let x = symbol!("x");
31473        let integrand = parse!("(d*x)^m*(c*x^2)^p*(a+b*x)^(-2-m-2*p)");
31474        let primitive = integrate(&integrand, x)
31475            .expect("Rubi corpus 1.1.1.2 line 1124 should follow rules 30 and 48");
31476        let text = primitive.to_string();
31477
31478        assert!(
31479            !text.contains("hypergeometric_2f1"),
31480            "Rubi rule 30 should normalize this before hypergeometric fallback: {primitive}"
31481        );
31482        assert_derivative_round_trip(integrand);
31483    }
31484
31485    #[test]
31486    fn integrates_corpus_1113_line_1011_via_proportional_binomial_row() {
31487        let x = symbol!("x");
31488        let integrand = parse!("(a+b*x)^n/(x^3*(-a-b*x)^n)");
31489        let primitive = integrate(&integrand, x)
31490            .expect("Rubi corpus 1.1.1.3 line 1011 should follow Rubi Int rule 37 then 15");
31491        let expected = parse!("-1/2*(a+b*x)^n/(x^2*(-a-b*x)^n)");
31492
31493        assert_eq!(primitive, expected);
31494        assert_derivative_round_trip(integrand);
31495    }
31496
31497    #[test]
31498    fn integrates_scaled_monomial_two_affine_power_appell_f1_row() {
31499        let x = symbol!("x");
31500        let primitive = integrate(&parse!("(2*x)^q*(1+x)^r*(1+2*x)^s"), x)
31501            .expect("Rubi 1.1.1.3.A.1.1 should apply");
31502        let text = primitive.to_string();
31503
31504        assert!(
31505            text.contains("appell_f1"),
31506            "primitive should contain opaque AppellF1 RHS: {text}"
31507        );
31508        assert!(
31509            text.contains('q') && text.contains('r') && text.contains('s'),
31510            "primitive should keep symbolic exponents: {text}"
31511        );
31512    }
31513
31514    #[test]
31515    fn rubi_simplerq_matches_core_numeric_and_structural_cases() {
31516        assert!(!rubi_simpler_q(&Atom::num(2), &Atom::num(2)));
31517        assert!(rubi_simpler_q(&Atom::num(2), &Atom::num(3)));
31518        assert!(!rubi_simpler_q(&Atom::num(-3), &Atom::num(2)));
31519        assert!(rubi_simpler_q(
31520            &(Atom::num(1) / Atom::num(3)),
31521            &(Atom::num(1) / Atom::num(5))
31522        ));
31523        assert!(rubi_simpler_q(&Atom::var(symbol!("a")), &parse!("a + b")));
31524    }
31525
31526    #[test]
31527    fn rubi_sum_simplerq_preserves_rational_coverage_and_ports_aux_cases() {
31528        assert!(!rubi_sum_simpler(&(Atom::num(-1) / Atom::num(2)), 1));
31529        assert!(!rubi_sum_simpler(&Atom::num(-1), 1));
31530        assert!(rubi_sum_simpler(&Atom::num(-2), 1));
31531        assert!(rubi_sum_simpler(&Atom::num(-2), 2));
31532        assert!(rubi_sum_simpler(&Atom::num(-3), 2));
31533        assert!(rubi_sum_simpler(&Atom::num(1), -1));
31534        assert!(!rubi_sum_simpler(&(Atom::num(1) / Atom::num(2)), -1));
31535        assert!(!rubi_sum_simpler(&Atom::num(1), -2));
31536        assert!(rubi_sum_simpler(&Atom::num(2), -2));
31537        assert!(!rubi_sum_simpler(&parse!("m"), 1));
31538        assert!(rubi_sum_simpler_aux(&parse!("m - 2"), &Atom::num(1)));
31539        assert!(rubi_sum_simpler(&parse!("m - 3"), 1));
31540        assert!(!rubi_sum_simpler(&parse!("m + 2"), 1));
31541        assert!(rubi_sum_simpler_aux(&parse!("m + 1"), &Atom::num(-1)));
31542        assert!(rubi_sum_simpler_q(&Atom::num(-3), &Atom::num(2)));
31543        assert!(rubi_sum_simpler_q(&Atom::num(-2), &Atom::num(2)));
31544    }
31545
31546    #[test]
31547    fn rubi_merge_monomials_combines_proportional_linear_powers() {
31548        let x = symbol!("x");
31549        assert_eq!(
31550            rubi_merge_monomials(&parse!("(d*x)^m*(a+b*x)/x^3"), x),
31551            parse!("d^3*(d*x)^(-3+m)*(a+b*x)")
31552        );
31553    }
31554
31555    #[test]
31556    fn rubi_pos_q_uses_rubi_structural_positivity() {
31557        assert!(rubi_pos_q(&parse!("9/a")));
31558        assert!(rubi_pos_q(&parse!("a")));
31559        assert!(rubi_pos_q(&parse!("(a+b*x^2)^(3/4)")));
31560        assert!(posq!(Atom::num(4) - Atom::num(4) * Atom::i()));
31561        assert!(!rubi_neg_q(&parse!("a")));
31562        assert!(!rubi_neg_q(&(Atom::num(4) - Atom::num(4) * Atom::i())));
31563    }
31564
31565    #[test]
31566    fn rubi_pos_q_matches_together_simplify_for_radical_coefficient() {
31567        let bare_radical_quotient = parse!("b/sqrt(-b)");
31568        assert_eq!(
31569            rubi_simplify(&bare_radical_quotient),
31570            bare_radical_quotient,
31571            "ordinary Mathematica Simplify leaves b/Sqrt[-b] unchanged"
31572        );
31573        assert_eq!(
31574            rubi_together_simplify(&bare_radical_quotient),
31575            parse!("-sqrt(-b)"),
31576            "Rubi TogetherSimplify applies the stronger exact-power identity"
31577        );
31578
31579        let coefficient = parse!("b*sqrt(-b*c+a*d)/(d*sqrt(-b)*(a-b*c/d))");
31580        let together = rubi_together_simplify(&coefficient);
31581
31582        assert!(
31583            rubi_neg_q(&coefficient),
31584            "Rubi TogetherSimplify should give this coefficient negative form: {together}"
31585        );
31586
31587        let external_coefficient =
31588            ["a", "b", "c", "d"]
31589                .into_iter()
31590                .fold(coefficient.to_owned(), |expr, name| {
31591                    substitute_symbol(
31592                        &expr,
31593                        symbol!(name),
31594                        Atom::var(Symbol::parse(name, "rubi_corpus").unwrap()),
31595                    )
31596                });
31597        assert!(
31598            rubi_neg_q(&external_coefficient),
31599            "the result must not depend on the caller's symbol namespace: {}",
31600            rubi_together_simplify(&external_coefficient)
31601        );
31602
31603        let x = symbol!("x");
31604        let ratio = parse!(
31605            "sqrt(1+x^2*sqrt(-b)/sqrt(-c*b+d*a))/\
31606             sqrt(1+x^2*b*sqrt(-c*b+d*a)/(d*sqrt(-b)*(-c*b/d+a)))"
31607        );
31608        let positive_rule = rubi_rules()
31609            .iter()
31610            .find(|rule| rule.downvalue_order == Some(324))
31611            .expect("DownValue 324 should be registered");
31612        let negative_rule = rubi_rules()
31613            .iter()
31614            .find(|rule| rule.downvalue_order == Some(327))
31615            .expect("DownValue 327 should be registered");
31616
31617        assert!(matcher_rule(ratio.as_view(), x, positive_rule).is_none());
31618        assert!(matcher_rule(ratio.as_view(), x, negative_rule).is_some());
31619
31620        let integrand = parse!("(c+d*x)^(3/4)/sqrt(a+b*x)");
31621        assert!(
31622            integrate(&integrand, x).is_ok(),
31623            "the linear-binomial path should reach DownValue 327"
31624        );
31625    }
31626
31627    #[test]
31628    fn algebraic_equality_accepts_borrowed_captures_and_rule_literals() {
31629        let x = symbol!("x");
31630        let left = parse!("(x+1)^2");
31631        let right = parse!("x^2+2*x+1");
31632        let left_before = left.to_owned();
31633        let right_before = right.to_owned();
31634        let mut evaluated = Vec::new();
31635
31636        assert!(eqq!(
31637            {
31638                evaluated.push("left");
31639                &left
31640            },
31641            {
31642                evaluated.push("right");
31643                &right
31644            }
31645        ));
31646        assert_eq!(evaluated, ["left", "right"]);
31647        assert_eq!(left, left_before);
31648        assert_eq!(right, right_before);
31649        assert!(eqq!(left.as_view(), right.as_view()));
31650        assert!(eqq!(parse!("(x+1)^2").as_view(), &right));
31651        assert!(eqq!(x, Atom::var(x)));
31652        assert!(eqq!((1, 2), parse!("1/2")));
31653        assert!(eqq!(parse!("1+x-x"), 1));
31654        assert!(neq!(&left, parse!("x^2+1")));
31655    }
31656
31657    #[test]
31658    fn integer_list_guards_borrow_operands_and_evaluate_each_once() {
31659        let fractional = parse!("1/2");
31660        let mut evaluated = Vec::new();
31661        assert!(!integersq!([
31662            {
31663                evaluated.push("first");
31664                &fractional
31665            },
31666            {
31667                evaluated.push("second");
31668                Atom::num(2)
31669            },
31670        ]));
31671        assert_eq!(evaluated, ["first", "second"]);
31672        assert_eq!(fractional, parse!("1/2"));
31673        assert!(integersq!([Atom::num(2), &Atom::num(4), parse!("1+2")]));
31674    }
31675
31676    #[test]
31677    fn numeric_inequalities_apply_mathematica_together() {
31678        let normalized_one = parse!("a/(a+b)+b/(a+b)");
31679
31680        assert!(is_number_greater_than(&normalized_one, 0));
31681        assert!(is_number_greater_or_equal(&normalized_one, 1));
31682        assert!(is_number_less_than(&normalized_one, 2));
31683        assert!(is_number_less_or_equal(&normalized_one, 1));
31684    }
31685
31686    #[test]
31687    fn rubi_pos_q_uses_mathematica_sum_term_ordering() {
31688        assert!(rubi_neg_q(&parse!("-b^2+4*a*c")));
31689
31690        let minus_root = parse!("(b*e-2*c*d-sqrt(b^2*e^2-4*a*c*e^2))/(2*c)");
31691        let plus_root = parse!("(b*e-2*c*d+sqrt(b^2*e^2-4*a*c*e^2))/(2*c)");
31692
31693        assert!(rubi_neg_q(&minus_root));
31694        assert!(rubi_neg_q(&plus_root));
31695    }
31696
31697    #[test]
31698    fn rubi_sum_q_is_syntactic_and_rejects_unsplit_quartic_ratio() {
31699        assert!(!rubi_sum_q(&parse!("(1+x^2)/(1+x^4)")));
31700        assert!(rubi_sum_q(&parse!("1/(1+x^4)+x^2/(1+x^4)")));
31701    }
31702
31703    #[test]
31704    fn expand_integrand_3806_replace_all_preserves_temporary_variable_payload() {
31705        let x = symbol!("x");
31706        let expanded = rubi_expand_integrand(&parse!("1/(d+e*x^2)^2"), x);
31707
31708        assert!(
31709            rubi_sum_q(&expanded),
31710            "expected a partial-fraction sum: {expanded}"
31711        );
31712        assert_ne!(expanded, Atom::num(0));
31713        assert!(!expanded.to_string().contains("ExpandIntegrand"));
31714
31715        let specialized = substitute_symbol(
31716            &substitute_symbol(&expanded, symbol!("d"), Atom::num(-1)),
31717            symbol!("e"),
31718            Atom::num(1),
31719        )
31720        .expand();
31721        let residual = (specialized.to_owned() - parse!("1/(-1+x^2)^2")).together();
31722        assert!(
31723            residual.is_zero(),
31724            "ExpandIntegrand 3806 must preserve the input rational function; expanded={expanded}; specialized={specialized}; residual={residual}"
31725        );
31726    }
31727
31728    #[test]
31729    fn smart_apart_3822_splits_all_cubic_double_poles() {
31730        let x = symbol!("x");
31731        let q = rubi_rt(&parse!("-d/e"), 3);
31732        let factors = (1..=3).fold(Atom::num(1), |product, ii| {
31733            let phase = Atom::num(-1).pow(Atom::num(2 * ii) / 3);
31734            product * (&q - phase * Atom::var(x)).pow(-2)
31735        });
31736        let apart = rubi_smart_apart(&factors, x);
31737        let terms = rubi_add_terms(&apart);
31738        let double_poles = terms
31739            .iter()
31740            .filter(|term| {
31741                rubi_product_factors(term).iter().any(|factor| {
31742                    let AtomView::Pow(power) = factor.as_view() else {
31743                        return false;
31744                    };
31745                    integer_i64_view(power.get_exp()) == Some(-2)
31746                        && polynomial_degree(&power.get_base().to_owned(), x) == Some(1)
31747                })
31748            })
31749            .count();
31750
31751        assert_eq!(
31752            terms.len(),
31753            6,
31754            "expected three simple and three double poles: {apart}"
31755        );
31756        assert_eq!(
31757            double_poles, 3,
31758            "expected all three cubic double poles: {apart}"
31759        );
31760    }
31761
31762    #[test]
31763    fn expand_integrand_uses_ordered_even_binomial_rows() {
31764        let x = symbol!("x");
31765
31766        let quartic = rubi_expand_integrand(&parse!("1/(1+x^4)"), x);
31767        assert!(
31768            rubi_sum_q(&quartic),
31769            "quartic denominator should expand to a sum: {quartic}"
31770        );
31771        assert!(
31772            !quartic.to_string().contains("x^2/(1+x^4)"),
31773            "quartic denominator should not split numerator terms over the same denominator: {quartic}"
31774        );
31775
31776        let quartic_ratio = rubi_expand_integrand(&parse!("(1+x^2)/(1+x^4)"), x);
31777        assert!(
31778            rubi_sum_q(&quartic_ratio),
31779            "quartic ratio should expand to lower-degree denominator terms: {quartic_ratio}"
31780        );
31781        assert!(
31782            !quartic_ratio.to_string().contains("x^2/(1+x^4)"),
31783            "quartic ratio should not use generic numerator splitting: {quartic_ratio}"
31784        );
31785
31786        let octic = rubi_expand_integrand(&parse!("1/(1+x^8)"), x);
31787        assert!(
31788            rubi_sum_q(&octic),
31789            "octic denominator should expand to a sum: {octic}"
31790        );
31791    }
31792
31793    #[test]
31794    fn expand_integrand_product_splits_quadratic_reciprocal_before_distribution() {
31795        let x = symbol!("x");
31796        let expanded =
31797            rubi_expand_integrand_product(&parse!("cosh(c+d*x)"), &parse!("1/(a+b*x^2)"), x);
31798
31799        assert!(
31800            rubi_sum_q(&expanded),
31801            "three-argument ExpandIntegrand should distribute over the reciprocal split: {expanded}"
31802        );
31803        assert!(
31804            !expanded.to_string().contains("a+x^2*b"),
31805            "the quadratic reciprocal should be split into linear factors: {expanded}"
31806        );
31807    }
31808
31809    #[test]
31810    fn expand_integrand_stops_at_unchanged_first_applicable_downvalue() {
31811        let x = symbol!("x");
31812        let input = parse!("c/e*(f+g*x)^n");
31813
31814        assert_eq!(
31815            rubi_expand_integrand(&input, x),
31816            input,
31817            "ExpandIntegrand 3688 applies first and Mathematica does not continue to row 3573"
31818        );
31819    }
31820
31821    #[test]
31822    fn expand_integrand_three_arg_matches_quartic_244_trace() {
31823        let x = symbol!("x");
31824        let u = parse!("(a+b*x^4)^p");
31825        let v = parse!("(c/(c^2-e^2*x^4)-e*x^2/(c^2-e^2*x^4))^2");
31826        let expanded = rubi_expand_integrand_product(&u, &v, x);
31827        let expected = parse!(
31828            "c^2*(a+b*x^4)^p/(c^2-e^2*x^4)^2 \
31829             -2*c*e*x^2*(a+b*x^4)^p/(c^2-e^2*x^4)^2 \
31830             +e^2*x^4*(a+b*x^4)^p/(-c^2+e^2*x^4)^2"
31831        );
31832
31833        assert!(
31834            rubi_sum_q(&expanded),
31835            "expected a termwise sum, got {expanded}"
31836        );
31837        assert!(
31838            residual_is_zero(&(expanded - expected)),
31839            "three-argument ExpandIntegrand should match Mathematica rule 1569"
31840        );
31841    }
31842
31843    #[test]
31844    fn expand_to_sum_matches_downvalue_713_recurrence_payload() {
31845        let x = symbol!("x");
31846        let x_atom = Atom::var(x);
31847        let d = Atom::var(symbol!("d"));
31848        let e = Atom::var(symbol!("e"));
31849        let f = Atom::var(symbol!("f"));
31850        let g = Atom::var(symbol!("g"));
31851        let affine = &f + &g * &x_atom;
31852        let polynomial = (&d + &e * &x_atom).pow(3);
31853        let quadratic = d.pow(2) - e.pow(2) * x_atom.pow(2);
31854        let (quotient, remainder) = polynomial_quotient_remainder_rational_dividend(
31855            &polynomial,
31856            &affine.pow(2),
31857            &quadratic,
31858            x,
31859        )
31860        .expect("DownValue 713 rational polynomial division should succeed");
31861        let r = polynomial_coefficient(&remainder, x, 0).unwrap();
31862        let p = Atom::num(-7) / Atom::num(2);
31863        let a = d.pow(2);
31864        let c = -e.pow(2);
31865        let raised_p = &p + Atom::num(1);
31866        let raw_payload = Atom::num(2) * &a * &c * &raised_p * affine.pow(2) * quotient
31867            + &c * &r * (Atom::num(2) * p + Atom::num(3)) * affine.pow(2);
31868        let expanded = rubi_expand_to_sum(&raw_payload, x);
31869        let expected = parse!(
31870            "d^3*e^2*(e^2*f^2+10*d*e*f*g+5*d^2*g^2)/(e*f+d*g)^2 \
31871             -d^2*e^3*(e*f-5*d*g)*(5*e*f+3*d*g)*x/(e*f+d*g)^2 \
31872             +16*d^3*e^4*g^2*x^2/(e*f+d*g)^2"
31873        );
31874
31875        assert!(
31876            (&expanded - &expected).together().is_zero(),
31877            "ExpandToSum should reproduce DownValue 713's recurrence payload: {expanded}"
31878        );
31879    }
31880
31881    #[test]
31882    fn expand_to_sum_cancels_pseudo_rational_polynomial_like_rubi_poly_q() {
31883        let x = symbol!("x");
31884        let x_atom = Atom::var(x);
31885        let c = Atom::var(symbol!("c"));
31886        let d = Atom::var(symbol!("d"));
31887        let e = Atom::var(symbol!("e"));
31888        let f = Atom::var(symbol!("f"));
31889        let affine = &f * (&c + &d * &x_atom);
31890        let constant = &c * &f - &d * &e;
31891        let quotient = (affine.pow(4) - constant.pow(4)) / (&e + &f * &x_atom);
31892
31893        assert!(rubi_poly_q(&quotient, x));
31894        assert_eq!(rubi_expon(quotient.as_view(), x), Some(3));
31895        let expanded = rubi_expand_to_sum(&quotient, x);
31896        assert!(
31897            collect_polynomial_terms(&expanded, x).is_some(),
31898            "{expanded}"
31899        );
31900        assert!(
31901            (&expanded - quotient).together().is_zero(),
31902            "ExpandToSum must use Rubi PolyQ's Together branch: {expanded}"
31903        );
31904    }
31905
31906    #[test]
31907    fn integrates_quadratic_trinomial_line_1035() {
31908        let x = symbol!("x");
31909        let integrand = parse!("(f+g*x)^n*(a+2*c*d*x+c*e*x^2)/(d+e*x)^2");
31910        let primitive = integrate(&integrand, x)
31911            .expect("Rubi DownValues 1195, 2009, and 78 should integrate corpus line 1035");
31912
31913        assert!(
31914            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
31915            "the traced Rubi path should produce a completed primitive: {primitive}"
31916        );
31917    }
31918
31919    #[test]
31920    fn expand_integrand_preserves_linear_square_denominator_for_algebraic_split() {
31921        let x = symbol!("x");
31922        let expanded = rubi_expand_integrand(&parse!("1/(1+sqrt(2+2*x+x^2))"), x);
31923        let expected = parse!("-1/(1+x)^2+(2+2*x+x^2)^(1/2)/(1+x)^2");
31924
31925        assert_eq!(
31926            expanded, expected,
31927            "ExpandIntegrand should keep the denominator as the visible linear square"
31928        );
31929        assert_derivative_round_trip(parse!("1/(1+sqrt(2+2*x+x^2))"));
31930    }
31931
31932    #[test]
31933    fn simplify_term_preserves_canonical_positive_fractional_power() {
31934        let x = symbol!("x");
31935        let expression = parse!("x^2/(-1+x^3-(1+x^2)^(3/2))");
31936        let simplified = rubi_simplify_term(&expression, x);
31937
31938        assert_eq!(
31939            simplified, expression,
31940            "SimplifyTerm should preserve Mathematica's canonical half-integer power"
31941        );
31942    }
31943
31944    #[test]
31945    fn smart_apart_rationalizes_timofeev_365_square_root_denominators() {
31946        let x = symbol!("x");
31947        let cases = [
31948            (
31949                parse!("x^2/(-1+x^3-(1+x^2)^(3/2))"),
31950                parse!(
31951                    "2/9-x/3-sqrt(1+x^2)/3+(3+5*x)/(9*(3+2*x+3*x^2))+2*x*sqrt(1+x^2)/(3*(3+2*x+3*x^2))"
31952                ),
31953            ),
31954            (
31955                parse!("x^2/(sqrt(1+x^2)*(-1+x^3-(1+x^2)^(3/2)))"),
31956                parse!(
31957                    "-1/3+1/(2*sqrt(1+x^2))-x/(2*sqrt(1+x^2))+2*x/(3*(3+2*x+3*x^2))-sqrt(1+x^2)/(2*(3+2*x+3*x^2))+x*sqrt(1+x^2)/(2*(3+2*x+3*x^2))"
31958                ),
31959            ),
31960        ];
31961
31962        for (expression, expected) in cases {
31963            let apart = rubi_smart_apart(&expression, x);
31964            assert!(
31965                rubi_sum_q(&apart),
31966                "SmartApart should produce a sum: {apart}"
31967            );
31968            assert!(
31969                rubi_equivalent_q(&apart, &expected),
31970                "SmartApart should match Mathematica for {expression}; got {apart}"
31971            );
31972        }
31973    }
31974
31975    #[test]
31976    fn integrates_timofeev_365_via_mathematica_smart_apart_path() {
31977        let x = symbol!("x");
31978        let integrand = parse!("x^2*(2-sqrt(1+x^2))/((1-x^3+(1+x^2)^(3/2))*sqrt(1+x^2))");
31979        let primitive =
31980            integrate(&integrand, x).expect("Timofeev line 365 should integrate like Rubi 4.17.3");
31981
31982        assert!(
31983            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
31984            "Timofeev line 365 should complete after SmartApart: {primitive}"
31985        );
31986    }
31987
31988    #[test]
31989    fn integrates_timofeev_436_via_nested_linear_pseudo_binomial_pair() {
31990        let x = symbol!("x");
31991        let integrand = parse!("1/((3*x+3*x^2+x^3)*(3+3*x+3*x^2+x^3)^(1/3))");
31992        let primitive = integrate(&integrand, x)
31993            .expect("Timofeev line 436 should follow DownValues 939/938/901");
31994
31995        assert!(
31996            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
31997            "Timofeev line 436 should complete after pseudo-binomial normalization: {primitive}"
31998        );
31999    }
32000
32001    #[test]
32002    fn downvalue_7266_rejects_composite_power_base() {
32003        let x = symbol!("x");
32004        let integrand = parse!("x^6*(x^3*(1+x^6)^3)^(1/3)");
32005        let rule = rubi_rules()
32006            .iter()
32007            .find(|rule| rule.downvalue_order == Some(7266))
32008            .expect("DownValue 7266 should be registered");
32009
32010        assert!(
32011            matcher_rule(integrand.as_view(), x, rule).is_none(),
32012            "Mathematica's literal x_^m pattern must not treat the composite root as x^m"
32013        );
32014    }
32015
32016    #[test]
32017    fn integrates_timofeev_569_via_fractional_product_normalization() {
32018        let x = symbol!("x");
32019        let integrand = parse!("((sin(x)/cos(x)^7)^(1/3)-3*tan(x))/(cos(x)^5*sin(x))^(2/3)");
32020        let primitive = integrate(&integrand, x)
32021            .expect("Timofeev line 569 should follow DownValues 3042/4889/7270/2035");
32022
32023        assert!(
32024            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
32025            "Timofeev line 569 should complete through Rubi's fractional product rules: {primitive}"
32026        );
32027    }
32028
32029    #[test]
32030    fn integrates_timofeev_604_via_secant_substitution() {
32031        let x = symbol!("x");
32032        let integrand = parse!("cot(x)/(a^4-b^4*csc(x)^2)^(1/4)");
32033        let primitive = integrate(&integrand, x)
32034            .expect("Timofeev line 604 should follow DownValues 3042/25/4627/243/73/827");
32035
32036        assert!(
32037            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
32038            "Timofeev line 604 should complete through Rubi's secant substitution: {primitive}"
32039        );
32040    }
32041
32042    #[test]
32043    fn rational_function_expand_splits_timofeev_568_tan_payload_like_mathematica() {
32044        let x = symbol!("x");
32045        let payload =
32046            parse!("((x^3/(1+x^2)^2)^(1/2)-4*x/(1+x^2))/((1+x^2)*(x^(1/2)-(x/(1+x^2)^2)^(1/2)))");
32047        let expanded = rubi_rational_function_expand(&payload, x)
32048            .expect("RationalFunctionExpand should split the Timofeev 568 tangent payload");
32049        let expected = parse!(
32050            "4*x/((1+x^2)^2*(-x^(1/2)+(x/(1+x^2)^2)^(1/2)))-(x^3/(1+x^2)^2)^(1/2)/((1+x^2)*(-x^(1/2)+(x/(1+x^2)^2)^(1/2)))"
32051        );
32052        assert!(
32053            rubi_equivalent_q(&expanded, &expected),
32054            "RationalFunctionExpand should match the first split in the Mathematica trace; got {expanded}"
32055        );
32056        assert!(
32057            !expanded.to_string().contains("1+2*x^2+x^4"),
32058            "RationalFunctionExpand should preserve the visible square denominator: {expanded}"
32059        );
32060    }
32061
32062    #[test]
32063    fn smart_apart_distributes_arcsech_numerator_without_aparting_in_x() {
32064        let x = symbol!("x");
32065        let payload = parse!("x*(-1+exp(asech(a*x))*a*x)/(1-a^2*x^2)");
32066        let smart_apart_expected = parse!(
32067            "x/((-1+a*x)*(1+a*x))\
32068             -a*exp(asech(a*x))*x^2/((-1+a*x)*(1+a*x))"
32069        );
32070        let expand_expected = parse!("x/(-1+a^2*x^2)-a*exp(asech(a*x))*x^2/(-1+a^2*x^2)");
32071
32072        assert_eq!(rubi_smart_apart(&payload, x), smart_apart_expected);
32073        assert!(eqq!(rubi_expand_expression(&payload, x), expand_expected));
32074    }
32075
32076    #[test]
32077    fn expand_integrand_splits_trace_quadratic_log_multiplier() {
32078        let x = symbol!("x");
32079        let multiplier = parse!("x/(-1+i+x^2)");
32080        let expanded_multiplier = rubi_expand_integrand(&multiplier, x);
32081        assert!(
32082            rubi_sum_q(&expanded_multiplier),
32083            "quadratic multiplier should split into linear denominators: {expanded_multiplier}"
32084        );
32085
32086        let log_quadratic = parse!("log(-1+x+x^2)");
32087        let expanded = rubi_expand_integrand_product_sum(&log_quadratic, &multiplier, x)
32088            .expect("Rubi line 39 trace expands Log[-1+x+x^2] times x/(-1+i+x^2)");
32089        assert!(
32090            rubi_sum_q(&expanded),
32091            "logarithmic multiplier should expand to a sum: {expanded}"
32092        );
32093        assert!(
32094            !expanded.to_string().contains("x*log(-1+x+x^2)/(-1+i+x^2)"),
32095            "expanded payload should not preserve the unsplit quadratic multiplier: {expanded}"
32096        );
32097    }
32098
32099    #[test]
32100    fn expand_integrand_splits_bondarenko_39_linear_quadratic_multiplier() {
32101        let x = symbol!("x");
32102        let multiplier = parse!("(1+2*x)/(-1+x+x^2)");
32103        let expanded = rubi_expand_integrand(&multiplier, x);
32104
32105        assert!(
32106            rubi_sum_q(&expanded),
32107            "linear/quadratic multiplier should split into linear denominators: {expanded}"
32108        );
32109        assert!(
32110            residual_is_zero(
32111                &(expanded.to_owned() - parse!("2/(1-sqrt(5)+2*x)+2/(1+sqrt(5)+2*x)"))
32112            ),
32113            "ExpandIntegrand should follow the Bondarenko 39 Rubi trace; got {expanded}"
32114        );
32115    }
32116
32117    #[test]
32118    fn expand_integrand_product_splits_bondarenko_39_generated_substitution_payload() {
32119        let sub1 = symbol!("sub1");
32120        let log_linear = parse!("log(sub1+(1-i/2*4^(1/2))^(1/2))");
32121        let multiplier = parse!("(1+2*sub1)/(-1+sub1+sub1^2)");
32122        let expanded_multiplier = rubi_expand_integrand(&multiplier, sub1);
32123        assert!(
32124            rubi_sum_q(&expanded_multiplier),
32125            "generated substitution multiplier should split into linear denominators: {expanded_multiplier}"
32126        );
32127        assert!(
32128            !expanded_multiplier
32129                .to_string()
32130                .contains("sub1/(-1+sub1+sub1^2)"),
32131            "generated substitution multiplier should not remain split only over the original quadratic: {expanded_multiplier}"
32132        );
32133
32134        let expanded = rubi_expand_integrand_product_sum(&log_linear, &multiplier, sub1)
32135            .expect("Rubi 3.3 block 28 should expand the generated rational multiplier as a sum");
32136
32137        assert!(
32138            rubi_sum_q(&expanded),
32139            "generated logarithmic payload should split into linear denominators: {expanded}"
32140        );
32141        assert!(
32142            !expanded.to_string().contains("sub1*log"),
32143            "expanded payload should not expose the x*log(linear)/quadratic dead branch: {expanded}"
32144        );
32145    }
32146
32147    #[test]
32148    fn integrates_bondarenko_39_substituted_log_quadratic_payload() {
32149        let sub1 = symbol!("sub1");
32150        let integrand = parse!("sub1*log(-1+sub1+sub1^2)/(2-2*sub1^2+sub1^4)");
32151        let primitive = integrate(&integrand, sub1)
32152            .expect("Rubi should integrate the Bondarenko line 39 substituted payload");
32153
32154        assert!(
32155            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
32156            "substituted Bondarenko line 39 payload should not leave deferred integrals or return unintegrable: {primitive}"
32157        );
32158        assert_derivative_round_trip(integrand);
32159    }
32160
32161    #[test]
32162    fn integrates_bondarenko_40_generated_rational_by_expand_integrand() {
32163        let x = symbol!("x");
32164        let integrand = parse!("(1+2*x)/(x*(-1+x+x^2))");
32165        let expanded = rubi_expand_integrand(&integrand, x);
32166        assert!(
32167            rubi_sum_q(&expanded),
32168            "generated rational should expand before the trinomial terminal row: {expanded}"
32169        );
32170
32171        let primitive = integrate(&integrand, x)
32172            .expect("Rubi should integrate the Bondarenko line 40 rational payload");
32173        assert!(
32174            !rubi_contains_unintegrable(&primitive),
32175            "rational payload should not return unintegrable: {primitive}"
32176        );
32177    }
32178
32179    #[test]
32180    fn expand_integrand_splits_moses_124_exponential_rational_multiplier() {
32181        let x = symbol!("x");
32182        let exponential = Atom::var(Symbol::E).pow(Atom::var(x).pow(2));
32183        let rational = parse!("(1+4*x^2+x^3+5*x^4+2*x^6)/(1+x^2)^2");
32184        let integrand = &exponential * rational;
32185        let expanded = rubi_expand_integrand(&integrand, x);
32186        let expected = &exponential + Atom::num(2) * &exponential * Atom::var(x).pow(2)
32187            - &exponential * Atom::var(x) / parse!("(1+x^2)^2")
32188            + &exponential * Atom::var(x) / parse!("1+x^2");
32189
32190        assert!(
32191            rubi_sum_q(&expanded),
32192            "Moses line 124 multiplier should expand to a sum: {expanded}"
32193        );
32194        assert!(
32195            residual_is_zero(&(expanded - expected)),
32196            "ExpandIntegrand should follow the Moses line 124 Rubi trace"
32197        );
32198    }
32199
32200    #[test]
32201    fn freeq_rejects_variable_in_power_exponent() {
32202        let x = symbol!("x");
32203        let exponential = Atom::var(Symbol::E).pow(Atom::var(x).pow(2));
32204        assert!(
32205            !freeq!(exponential, x),
32206            "FreeQ must see x in E^(x^2) so Rubi guards reject exponent-dependent powers"
32207        );
32208    }
32209
32210    #[test]
32211    fn integrates_moses_124_via_rubi_expand_integrand_trace() {
32212        let x = symbol!("x");
32213        let exponential = Atom::var(Symbol::E).pow(Atom::var(x).pow(2));
32214        let rational = parse!("(1+4*x^2+x^3+5*x^4+2*x^6)/(1+x^2)^2");
32215        let integrand = &exponential * rational;
32216        let primitive = integrate(&integrand, x)
32217            .expect("Moses Problems.input line 124 should integrate via Rubi ExpandIntegrand");
32218        let residual = (primitive.derivative(x) - integrand).together();
32219
32220        assert!(
32221            residual_is_zero(&residual),
32222            "Moses Problems.input line 124 derivative round trip failed; residual: {residual}; primitive: {primitive}"
32223        );
32224    }
32225
32226    #[test]
32227    fn integrates_bondarenko_40_fractional_power_payload() {
32228        let x = symbol!("x");
32229        let integrand = parse!("log(x+sqrt(1+x))^2/(1+x)^2");
32230        let primitive = integrate(&integrand, x)
32231            .expect("Rubi should integrate Bondarenko Problems.input line 40");
32232        assert!(
32233            !rubi_contains_unintegrable(&primitive),
32234            "Bondarenko line 40 should not return unintegrable: {primitive}"
32235        );
32236    }
32237
32238    #[test]
32239    fn expand_integrand_conjugates_square_root_denominator() {
32240        let x = symbol!("x");
32241        let expanded = rubi_expand_integrand(&parse!("1/(1+sqrt(2+2*x+x^2))"), x);
32242
32243        assert_eq!(
32244            expanded.expand(),
32245            parse!("-1/(1+x)^2 + sqrt(2+2*x+x^2)/(1+x)^2").expand()
32246        );
32247    }
32248
32249    #[test]
32250    fn expand_integrand_matches_welz_42_conjugate_square_split() {
32251        let x = symbol!("x");
32252        let integrand = parse!("1/(sqrt(-1+x^2)*(sqrt(x)+sqrt(-1+x^2))^2)");
32253        let expanded = rubi_expand_integrand(&integrand, x);
32254        let expected = parse!(
32255            "-2*sqrt(x)/(-1-x+x^2)^2\
32256             +2*x/(sqrt(-1+x^2)*(-1-x+x^2)^2)\
32257             +1/(sqrt(-1+x^2)*(-1-x+x^2))"
32258        );
32259
32260        assert_eq!(expanded, expected, "native ExpandIntegrand: {expanded}");
32261    }
32262
32263    #[test]
32264    fn smart_apart_conjugates_square_root_denominator_with_polynomial_numerator() {
32265        let x = symbol!("x");
32266        let integrand = parse!("x^2/(1+x+sqrt(1+x^2))");
32267        let expanded = rubi_smart_apart(&integrand, x);
32268        let expected = parse!("x/2+x^2/2-x*sqrt(1+x^2)/2");
32269        let residual = (expanded.to_owned() - &integrand).together();
32270
32271        assert_eq!(expanded.expand(), expected.expand());
32272        assert!(
32273            rubi_algebraic_zero_q(&residual),
32274            "SmartApart should preserve equivalence after conjugating square-root denominator; expanded: {expanded}; residual: {residual}"
32275        );
32276    }
32277
32278    #[test]
32279    fn smart_apart_uses_a_single_dependent_trig_kernel_like_mathematica() {
32280        let x = symbol!("x");
32281        let integrand = parse!("cos(c+d*x)^2/((-b-a*cos(c+d*x))^2*(1-cos(c+d*x)^2)^2)");
32282        let expanded = rubi_smart_apart(&integrand, x);
32283        let residual = (expanded.to_owned() - &integrand).together();
32284
32285        assert!(
32286            rubi_sum_q(&expanded),
32287            "Mathematica Apart treats the dependent cosine as a rational kernel: {expanded}"
32288        );
32289        assert!(
32290            residual.is_zero(),
32291            "dependent-kernel partial fractions must preserve the payload: {residual}"
32292        );
32293    }
32294
32295    #[test]
32296    fn expand_integrand_preserves_quadratic_trig_denominator_during_distribution() {
32297        let x = symbol!("x");
32298        let sine = parse!("sin(e+f*x)");
32299        let multiplier = (parse!("a") - parse!("b") * &sine).pow(2)
32300            / (parse!("a^2") - parse!("b^2") * sine.pow(2)).pow(2);
32301        let expanded = rubi_expand_integrand(&multiplier, x);
32302        let mathematica = parse!(
32303            "a^2/(a^2-b^2*sin(e+f*x)^2)^2\
32304             -2*a*b*sin(e+f*x)/(a^2-b^2*sin(e+f*x)^2)^2\
32305             +b^2*sin(e+f*x)^2/(-a^2+b^2*sin(e+f*x)^2)^2"
32306        );
32307        assert!(
32308            rubi_equivalent_q(&expanded, &mathematica),
32309            "ExpandIntegrand must be equivalent to the Mathematica trace: {expanded}"
32310        );
32311
32312        let quadratic = parse!("a^2-b^2*sin(e+f*x)^2");
32313        for term in rubi_add_terms(&expanded) {
32314            let (_, denominator) = rational_numerator_denominator_unexpanded(&term)
32315                .expect("each expanded term should remain rational");
32316            assert!(
32317                denominator == quadratic.pow(2) || denominator == (-&quadratic).pow(2),
32318                "ExpandIntegrand must preserve one quadratic denominator power: {term}"
32319            );
32320        }
32321    }
32322
32323    #[test]
32324    fn integrates_symbolic_sine_power_over_affine_sine_square_without_recurrence() {
32325        let x = symbol!("x");
32326        let integrand = parse!("(d*sin(e+f*x))^m/(a+b*sin(e+f*x))^2");
32327        let primitive = integrate(&integrand, x)
32328            .expect("Rubi's traced quadratic-sine path should reach its AppellF1 row");
32329
32330        assert!(
32331            primitive.to_string().contains("appell_f1"),
32332            "the traced Rubi path should return an AppellF1 primitive: {primitive}"
32333        );
32334    }
32335
32336    #[test]
32337    fn smart_apart_rationalizes_timofeev_315_sixth_root_denominator() {
32338        let x = symbol!("x");
32339        let integrand = parse!("x^4*(2-x^6)^(1/3)/(x-(2-x^6)^(1/6))");
32340        let radical_denominator = parse!("x-(2-x^6)^(1/6)");
32341        let expanded = rubi_smart_apart(&integrand, x);
32342        let residual = (expanded.to_owned() - &integrand).together();
32343
32344        assert!(
32345            rubi_sum_q(&expanded),
32346            "SmartApart should return a sum: {expanded}"
32347        );
32348        assert!(
32349            !rubi_contains_subexpression(expanded.as_view(), radical_denominator.as_view()),
32350            "Mathematica Apart rationalizes the sixth-root denominator: {expanded}"
32351        );
32352        assert!(
32353            rubi_contains_subexpression(expanded.as_view(), parse!("1-x+x^2").as_view()),
32354            "Mathematica Apart exposes the cyclotomic partial fractions: {expanded}"
32355        );
32356        assert!(
32357            rubi_algebraic_zero_q(&residual),
32358            "SmartApart must preserve equivalence; expanded: {expanded}; residual: {residual}"
32359        );
32360    }
32361
32362    #[test]
32363    fn integrates_algebraic_expansion_corpus_1_3_2_line_1090() {
32364        assert_derivative_round_trip(parse!("(-1+x+x^2)/(1+x+sqrt(1+x^2))"));
32365    }
32366
32367    #[test]
32368    fn smart_apart_splits_radical_multiplier_after_conjugation() {
32369        let x = symbol!("x");
32370        let integrand = parse!("1/(3*(1-x^2)+(-5-4*x)*sqrt(1-x^2))");
32371        let expanded = rubi_smart_apart(&integrand, x);
32372        let expected = parse!(
32373            "-3/(4+5*x)^2 + sqrt(1-x^2)/(18*(-1+x)) - sqrt(1-x^2)/(2*(1+x)) - 5*sqrt(1-x^2)/(4+5*x)^2 + 20*sqrt(1-x^2)/(9*(4+5*x))"
32374        );
32375        let residual = (expanded.to_owned() - &integrand).together();
32376
32377        assert!(
32378            residual_is_zero(&(expanded.to_owned() - expected)),
32379            "SmartApart should match the Rubi trace algebraically; expanded: {expanded}"
32380        );
32381        assert!(
32382            rubi_algebraic_zero_q(&residual),
32383            "SmartApart radical split should preserve equivalence; expanded: {expanded}; residual: {residual}"
32384        );
32385    }
32386
32387    #[test]
32388    fn smart_apart_splits_difference_of_square_roots_like_timofeev_580() {
32389        let x = symbol!("x");
32390
32391        let reciprocal = parse!("1/(sqrt(7-8*x^2)-sqrt(3-4*x^2))");
32392        let reciprocal_expanded = rubi_smart_apart(&reciprocal, x);
32393        let reciprocal_expected = parse!("-sqrt(7-8*x^2)/(4*(-1+x^2))-sqrt(3-4*x^2)/(4*(-1+x^2))");
32394        assert!(
32395            residual_is_zero(&(reciprocal_expanded.to_owned() - reciprocal_expected)),
32396            "SmartApart should match Rubi's reciprocal split; got {reciprocal_expanded}"
32397        );
32398
32399        let quadratic = parse!("x^2/(sqrt(7-8*x^2)-sqrt(3-4*x^2))");
32400        let quadratic_expanded = rubi_smart_apart(&quadratic, x);
32401        let quadratic_expected = parse!(
32402            "-sqrt(7-8*x^2)/4-sqrt(7-8*x^2)/(4*(-1+x^2))-sqrt(3-4*x^2)/4-sqrt(3-4*x^2)/(4*(-1+x^2))"
32403        );
32404        assert!(
32405            residual_is_zero(&(quadratic_expanded.to_owned() - quadratic_expected)),
32406            "SmartApart should match Rubi's quadratic numerator split; got {quadratic_expanded}"
32407        );
32408    }
32409
32410    #[test]
32411    fn integrates_algebraic_expansion_corpus_1_3_2_line_1115() {
32412        assert_derivative_round_trip(parse!("1/(3*(1-x^2)+(-5-4*x)*sqrt(1-x^2))"));
32413    }
32414
32415    #[test]
32416    fn simplify_integrand_preserves_bondarenko_35_square_root_quotient_like_rubi() {
32417        let x = symbol!("x");
32418        let integrand = parse!("x^2/(x^2+(1-x^2)^(1/2))");
32419        let simplified = rubi_simplify_integrand(&integrand, x);
32420
32421        assert_eq!(
32422            simplified, integrand,
32423            "SimplifyIntegrand should match the Bondarenko 35 Rubi trace"
32424        );
32425    }
32426
32427    #[test]
32428    fn simplify_integrand_pulls_integer_powers_from_fractional_power_like_timofeev_565() {
32429        let x = symbol!("x");
32430        let integrand = parse!("(x^2*(1+x^2)^6)^(1/3)/(1+x^2)");
32431        let simplified = rubi_simplify_integrand(&integrand, x);
32432        let expected = parse!("x^(2/3)*(1+x^2)");
32433
32434        assert!(
32435            residual_is_zero(&(simplified.to_owned() - expected)),
32436            "SimplifyIntegrand should follow Rubi's Timofeev 565 payload; got {simplified}"
32437        );
32438    }
32439
32440    #[test]
32441    fn simplify_integrand_matches_timofeev_950_hyperbolic_payload() {
32442        let x = symbol!("x");
32443        let payload = parse!("cosh(x)*(tanh(x)-tanh(x)^3/3)/(1-sinh(x)^2)^(1/2)");
32444        let expected = parse!("(2+cosh(2*x))*sech(x)*tanh(x)/(3*(-(-1+sinh(x)^2))^(1/2))");
32445
32446        assert_eq!(rubi_simplify_integrand(&payload, x), expected);
32447    }
32448
32449    #[test]
32450    fn integrates_timofeev_950_through_rubi_function_of_cosine_substitution() {
32451        let primitive = integrate(&parse!("asin(sinh(x))*sech(x)^4"), symbol!("x"))
32452            .expect("Rubi DownValues 5343, 4857, 358, and 223 should integrate the payload");
32453
32454        assert!(!rubi_contains_unintegrable(&primitive), "{primitive}");
32455    }
32456
32457    #[test]
32458    fn integrates_timofeev_565_tangent_fractional_power_trace() {
32459        assert_derivative_round_trip(parse!("(sin(x)^2/cos(x)^14)^(1/3)"));
32460    }
32461
32462    #[test]
32463    fn expand_integrand_uses_bondarenko_35_expand_algebraic_function_trace() {
32464        let x = symbol!("x");
32465        let integrand = parse!("x^2*(2-1/(1-x^2)^(1/2))/(x^2+(1-x^2)^(1/2))");
32466        let expanded = rubi_expand_integrand(&integrand, x);
32467        let expected = parse!("2*x^2/(x^2+(1-x^2)^(1/2)) - x^2/(1-x^2+x^2*(1-x^2)^(1/2))");
32468
32469        assert!(
32470            residual_is_zero(&(expanded.to_owned() - expected)),
32471            "ExpandIntegrand should match the Bondarenko 35 Rubi trace; got {expanded}"
32472        );
32473    }
32474
32475    #[test]
32476    fn expand_cleanup_preserves_mathematica_affine_numerator_grouping() {
32477        let x = symbol!("x");
32478        let split = parse!("A/(a+b*x+c*x^2)+B*x/(a+b*x+c*x^2)+C/(a+b*x+c*x^2)^2");
32479        let grouped = rubi_collect_common_rational_denominators(&split, x);
32480        let expected = parse!("(A+B*x)/(a+b*x+c*x^2)+C/(a+b*x+c*x^2)^2");
32481
32482        assert_eq!(grouped, expected);
32483    }
32484
32485    #[test]
32486    fn expand_cleanup_combines_opposite_affine_poles_after_polynomial_terms() {
32487        let x = symbol!("x");
32488        let split = parse!(
32489            "3*c*d^2/e^4+c*x^2/e^2\
32490             +(c*d^4+a*e^4)/(2*e^4*(-d+e*x)^2)\
32491             +2*c*d^3/(e^4*(-d+e*x))\
32492             +(c*d^4+a*e^4)/(2*e^4*(d+e*x)^2)\
32493             -2*c*d^3/(e^4*(d+e*x))"
32494        );
32495        let expected = parse!(
32496            "3*c*d^2/e^4+c*x^2/e^2\
32497             +(c*d^4+a*e^4)/(2*e^4*(-d+e*x)^2)\
32498             +(c*d^4+a*e^4)/(2*e^4*(d+e*x)^2)\
32499             -4*c*d^4/(e^4*(d^2-e^2*x^2))"
32500        );
32501
32502        let cleaned = rubi_expand_cleanup(&split, x);
32503        assert!(
32504            rubi_equivalent_q(&cleaned, &expected),
32505            "ExpandCleanup should preserve the Mathematica value; got {cleaned}"
32506        );
32507        let has_quadratic_denominator = rubi_add_terms(&cleaned).iter().any(|term| {
32508            rational_numerator_denominator_unexpanded(term)
32509                .and_then(|(_, denominator)| collect_polynomial_terms(&denominator, x))
32510                .is_some_and(|terms| {
32511                    terms.len() == 2 && terms.contains_key(&0) && terms.contains_key(&2)
32512                })
32513        });
32514        assert!(
32515            has_quadratic_denominator,
32516            "ExpandCleanup should retain the quadratic denominator produced by its affine-pair rule; got {cleaned}"
32517        );
32518    }
32519
32520    #[test]
32521    fn expand_integrand_matches_quartic_affine_mathematica_cleanup() {
32522        let x = symbol!("x");
32523        let rational = parse!("(a+c*x^4)*(d^2+e^2*x^2)/(d^2-e^2*x^2)^2");
32524        let factor = parse!("1/sqrt(a+c*x^4)");
32525        let expected = parse!(
32526            "3*c*d^2/(e^4*sqrt(a+c*x^4))\
32527             +c*x^2/(e^2*sqrt(a+c*x^4))\
32528             +(c*d^4+a*e^4)/(2*e^4*(-d+e*x)^2*sqrt(a+c*x^4))\
32529             +(c*d^4+a*e^4)/(2*e^4*(d+e*x)^2*sqrt(a+c*x^4))\
32530             -4*c*d^4/(e^4*(d^2-e^2*x^2)*sqrt(a+c*x^4))"
32531        );
32532
32533        let expanded = rubi_expand_integrand_product(&factor, &rational, x);
32534        assert!(
32535            rubi_equivalent_q(&expanded, &expected),
32536            "ExpandIntegrand should preserve the Mathematica value; got {expanded}"
32537        );
32538    }
32539
32540    #[test]
32541    fn integrates_quartic_square_root_over_affine_square_via_rubi_trace() {
32542        let primitive = integrate(&parse!("sqrt(a+c*x^4)/(d+e*x)^2"), symbol!("x")).expect(
32543            "Rubi DownValue 2584 and its downstream elliptic rules should integrate the case",
32544        );
32545
32546        assert!(
32547            rubi_integral_free_q(&primitive),
32548            "Rubi trace should complete without a deferred integral: {primitive}"
32549        );
32550    }
32551
32552    #[test]
32553    fn rubi_log_base_evaluates_exact_integer_powers() {
32554        assert_eq!(rubi_log_base(&Atom::num(2), &Atom::num(4)), Atom::num(2));
32555        assert_eq!(
32556            rubi_log_base(&Atom::num(2), &(Atom::num(1) / Atom::num(4))),
32557            Atom::num(-2)
32558        );
32559    }
32560
32561    #[test]
32562    fn polynomial_divide_preserves_rubi_coefficient_grouping() {
32563        let x = symbol!("x");
32564        let numerator = parse!("d+e*x+f*x^2+g*x^3+h*x^4+j*x^5+k*x^6+l*x^7+m*x^8");
32565        let denominator = parse!("a+b*x+c*x^2");
32566        let divided = rubi_polynomial_divide(&numerator, &denominator, x).unwrap();
32567        let term_count = match divided.as_view() {
32568            AtomView::Add(sum) => sum.into_iter().count(),
32569            _ => 1,
32570        };
32571
32572        assert_eq!(term_count, 8, "divided = {divided}");
32573    }
32574
32575    #[test]
32576    fn expand_integrand_follows_bondarenko_35_smart_apart_trace() {
32577        let x = symbol!("x");
32578        let integrand = parse!("x^2/(1-x^2+x^2*(1-x^2)^(1/2))");
32579        let expanded = rubi_expand_integrand(&integrand, x);
32580        let expected = parse!("1/(1-x^2)^(1/2) - x^2/(-1+x^2+x^4) + (1-x^2)^(1/2)/(-1+x^2+x^4)");
32581
32582        assert!(
32583            residual_is_zero(&(expanded.to_owned() - expected)),
32584            "ExpandIntegrand should match the Bondarenko 35 Rubi trace; got {expanded}"
32585        );
32586    }
32587
32588    #[test]
32589    fn expand_integrand_smart_aparts_substitution_rational_over_monomial_quadratic_product() {
32590        let sub1 = symbol!("sub1");
32591        let integrand = parse!(
32592            "(-B*a*b^2*d^3 - 2*B*b^3*c*d^2 + 2*C*a*b^2*d^2*sub1^2 + C*a^2*b*d^3 - 2*C*b^3*c*d*sub1^2 + 2*C*b^3*c^2*d + 3*A*b^3*d^3 - 2*D*a*b^2*c*d*sub1^2 + 2*D*a*b^2*d*sub1^4 - 2*D*a^2*b*d^2*sub1^2 - D*a^3*d^3 - 2*D*b^3*c*sub1^4 + 4*D*b^3*c^2*sub1^2 - 2*D*b^3*c^3)/(2*a*b^3*d^2*sub1^2 - 2*b^4*c*d*sub1^2 + 2*b^4*d*sub1^4)"
32593        );
32594        let expanded = rubi_expand_integrand(&integrand, sub1);
32595
32596        assert!(
32597            rubi_sum_q(&expanded),
32598            "substitution rational should expand to a partial-fraction sum: {expanded}"
32599        );
32600        let residual = (expanded - integrand).together();
32601        assert!(
32602            rubi_algebraic_zero_q(&residual),
32603            "expanded substitution rational is not equivalent: {residual}"
32604        );
32605    }
32606
32607    #[test]
32608    fn expand_integrand_smart_aparts_substitution_rational_over_repeated_monomial_quadratic_product()
32609     {
32610        let sub1 = symbol!("sub1");
32611        let integrand = parse!(
32612            "(-B*a*b^2*d^3 - 4*B*b^3*c*d^2 + 4*C*a*b^2*d^2*sub1^2 + C*a^2*b*d^3 - 4*C*b^3*c*d*sub1^2 + 4*C*b^3*c^2*d + 5*A*b^3*d^3 - 4*D*a*b^2*c*d*sub1^2 + 4*D*a*b^2*d*sub1^4 - 4*D*a^2*b*d^2*sub1^2 - D*a^3*d^3 - 4*D*b^3*c*sub1^4 + 8*D*b^3*c^2*sub1^2 - 4*D*b^3*c^3)/(-4*a*b^4*c*d*sub1^2 + 4*a*b^4*d*sub1^4 + 2*a^2*b^3*d^2*sub1^2 - 4*b^5*c*sub1^4 + 2*b^5*c^2*sub1^2 + 2*b^5*sub1^6)"
32613        );
32614        let expanded = rubi_expand_integrand(&integrand, sub1);
32615
32616        assert!(
32617            rubi_sum_q(&expanded),
32618            "repeated substitution rational should expand to a partial-fraction sum: {expanded}"
32619        );
32620        let residual = (expanded - integrand).together();
32621        assert!(
32622            rubi_algebraic_zero_q(&residual),
32623            "expanded repeated substitution rational is not equivalent: {residual}"
32624        );
32625    }
32626
32627    #[test]
32628    fn expand_integrand_smart_aparts_substitution_rational_over_cubed_monomial_quadratic_product() {
32629        let sub1 = symbol!("sub1");
32630        let integrand = parse!(
32631            "(-B*a*b^2*d^4 - 6*B*b^3*c*d^3 + 6*C*a*b^2*d^3*sub1^2 + C*a^2*b*d^4 - 6*C*b^3*c*d^2*sub1^2 + 6*C*b^3*c^2*d^2 + 7*A*b^3*d^4 - 6*D*a*b^2*c*d^2*sub1^2 + 6*D*a*b^2*d^2*sub1^4 - 6*D*a^2*b*d^3*sub1^2 - D*a^3*d^4 - 6*D*b^3*c*d*sub1^4 + 12*D*b^3*c^2*d*sub1^2 - 6*D*b^3*c^3*d)/(-12*a*b^5*c*d*sub1^4 + 6*a*b^5*d*sub1^6 + 6*a*b^5*c^2*d*sub1^2 - 6*a^2*b^4*c*d^2*sub1^2 + 6*a^2*b^4*d^2*sub1^4 + 2*a^3*b^3*d^3*sub1^2 - 6*b^6*c*sub1^6 + 6*b^6*c^2*sub1^4 - 2*b^6*c^3*sub1^2 + 2*b^6*sub1^8)"
32632        );
32633        let expanded = rubi_expand_integrand(&integrand, sub1);
32634
32635        assert!(
32636            rubi_sum_q(&expanded),
32637            "cubed substitution rational should expand to a partial-fraction sum: {expanded}"
32638        );
32639        let residual = (expanded - integrand).together();
32640        assert!(
32641            rubi_algebraic_zero_q(&residual),
32642            "expanded cubed substitution rational is not equivalent: {residual}"
32643        );
32644    }
32645
32646    #[test]
32647    fn power_variable_expn_keeps_cubed_binomial_payload_for_expand_integrand() {
32648        let x = symbol!("x");
32649        let sub1 = symbol!("sub1");
32650        let data = rubi_power_variable_expn(&parse!("1/(a+b*x^n)^3"), Atom::num(0), x)
32651            .expect("PowerVariableExpn should identify the symbolic power substitution");
32652        let sub_atom = Atom::var(sub1);
32653        let normalized = rubi_normalize_integrand(
32654            &rubi_mathematica_simplify(&(data.integrand / sub_atom)),
32655            sub1,
32656        );
32657        let expanded = rubi_expand_integrand(&normalized, sub1);
32658        let expected =
32659            parse!("1/(a^3*sub1) - b/(a*(a+b*sub1)^3) - b/(a^2*(a+b*sub1)^2) - b/(a^3*(a+b*sub1))");
32660
32661        assert!(
32662            rubi_sum_q(&expanded),
32663            "Rubi payload should expand to a partial-fraction sum: {expanded}"
32664        );
32665        let residual = (expanded - expected).together();
32666        assert!(
32667            rubi_algebraic_zero_q(&residual),
32668            "PowerVariableExpn payload should follow the Rubi trace; residual: {residual}"
32669        );
32670    }
32671
32672    #[test]
32673    fn held_power_preserves_negative_integer_power_of_sum() {
32674        let held = rubi_hold_power(&parse!("a+b*x^n"), &Atom::num(-3));
32675        assert_eq!(held, parse!("1/(a+b*x^n)^3"));
32676    }
32677
32678    #[test]
32679    fn integrates_symbolic_exponential_cubed_denominator_like_rubi() {
32680        let x = symbol!("x");
32681        let integrand = parse!("1/(a+b*(F^(g*(e+f*x)))^n)^3");
32682        let primitive =
32683            integrate(&integrand, x).expect("Rubi should integrate the symbolic cubed denominator");
32684        assert!(
32685            !rubi_contains_unintegrable(&primitive),
32686            "primitive should not be unintegrable: {primitive}"
32687        );
32688    }
32689
32690    #[test]
32691    fn integrates_timofeev_square_root_denominator_via_rubi_expand_integrand() {
32692        let x = symbol!("x");
32693        let integrand = parse!("1/(1+sqrt(2+2*x+x^2))");
32694        let primitive = integrate(&integrand, x)
32695            .expect("Rubi should integrate Timofeev square-root denominator problem");
32696        let residual = (primitive.derivative(x) - integrand).together();
32697
32698        assert!(
32699            residual_is_zero(&residual),
32700            "primitive derivative mismatch: {residual}; primitive: {primitive}"
32701        );
32702    }
32703
32704    #[test]
32705    fn integrates_timofeev_298_via_int_sum() {
32706        let x = symbol!("x");
32707        let integrand = parse!("(-3*x^(3/5)+x^(3/2))^2*(-1/3*x^(2/3)+4*x^(3/2))");
32708        let primitive = integrate(&integrand, x)
32709            .expect("Timofeev line 298 should follow Rubi DownValues through IntSum");
32710        let residual = (primitive.derivative(x) - integrand).together();
32711
32712        assert!(
32713            residual_is_zero(&residual),
32714            "Timofeev line 298 derivative mismatch: {residual}; primitive: {primitive}"
32715        );
32716    }
32717
32718    #[test]
32719    fn integrates_inverse_tangent_exponentials_with_compound_coefficient() {
32720        let x_symbol = symbol!("x");
32721        let x = Atom::var(x_symbol);
32722        let a = Atom::var(symbol!("a"));
32723        let c = Atom::var(symbol!("c"));
32724        let n = Atom::var(symbol!("n"));
32725        let p = Atom::var(symbol!("p"));
32726        let angle = (&a * &x).atan();
32727        let quadratic = &c + a.pow(2) * x.pow(2) * &c;
32728
32729        let integrands = [
32730            (Atom::i() * &n * &angle).exp() / x.pow(4),
32731            quadratic.pow(&p) / (Atom::num(2) * Atom::i() * &p * &angle).exp(),
32732            (Atom::i() * &n * angle).exp() * x.pow(2) * quadratic.pow(-Atom::num(1) - n.pow(2) / 2),
32733        ];
32734
32735        for integrand in integrands {
32736            let primitive = integrate(&integrand, x_symbol)
32737                .unwrap_or_else(|_| panic!("compound coefficient should match: {integrand}"));
32738            assert!(
32739                !rubi_contains_unintegrable(&primitive),
32740                "compound coefficient should not defer: {integrand}; primitive: {primitive}"
32741            );
32742        }
32743    }
32744
32745    #[test]
32746    fn integrates_inverse_hyperbolic_tangent_exponentials_with_compound_coefficient() {
32747        let x_symbol = symbol!("x");
32748        let x = Atom::var(x_symbol);
32749        let a = Atom::var(symbol!("a"));
32750        let c = Atom::var(symbol!("c"));
32751        let p = Atom::var(symbol!("p"));
32752        let angle = (&a * &x).atanh();
32753        let exponential = (Atom::num(2) * &p * &angle).exp();
32754        let integrands = [
32755            (&c - &a * &c * &x).pow(&p) / &exponential,
32756            (&c - &c / (&a * &x)).pow(&p) / &exponential,
32757            (&c - &c / (a.pow(2) * x.pow(2))).pow(&p) / &exponential,
32758            (Atom::num(2) * (Atom::num(1) + &p) * angle).exp()
32759                / (Atom::num(1) - a.pow(2) * x.pow(2)).pow(&p),
32760        ];
32761
32762        for integrand in integrands {
32763            let primitive = integrate(&integrand, x_symbol)
32764                .unwrap_or_else(|_| panic!("compound coefficient should match: {integrand}"));
32765            assert!(
32766                !rubi_contains_unintegrable(&primitive),
32767                "compound coefficient should not defer: {integrand}; primitive: {primitive}"
32768            );
32769        }
32770    }
32771
32772    #[test]
32773    fn normalize_integrand_applies_mathematica_trig_square_simplification() {
32774        let x = symbol!("x");
32775
32776        assert_eq!(
32777            rubi_together_simplify(&parse!("1-sin(x)^2")),
32778            parse!("cos(x)^2")
32779        );
32780        assert_eq!(
32781            rubi_together_simplify(&parse!("csc(x)^3/(1-csc(x)^2)")),
32782            parse!("-csc(x)*sec(x)^2")
32783        );
32784        assert_eq!(
32785            rubi_together_simplify(&parse!("sec(x)^3/(1-sec(x)^2)")),
32786            parse!("-sec(x)*csc(x)^2")
32787        );
32788        assert_eq!(
32789            rubi_normalize_integrand(&parse!("exp(x)*(1-sin(x)^2)^(5/2)*cos(x)"), x),
32790            parse!("exp(x)*(cos(x)^2)^(5/2)*cos(x)")
32791        );
32792        let trig_remainder = parse!(
32793            "(-3/2*csc(a+b*x)+3/2*atanh(csc(a+b*x)))/b-1/2*csc(a+b*x)^3/(b*(1-csc(a+b*x)^2))"
32794        );
32795        let simplified_remainder =
32796            parse!("1/2*(-3*csc(a+b*x)+3*atanh(csc(a+b*x))+sec(a+b*x)^2*csc(a+b*x))/b");
32797        assert_eq!(
32798            rubi_together_simplify(&trig_remainder),
32799            simplified_remainder
32800        );
32801        assert_eq!(
32802            rubi_normalize_integrand(&(&parse!("(c+d*x)^2") * &trig_remainder), x),
32803            parse!("(c+d*x)^2") * simplified_remainder
32804        );
32805    }
32806
32807    #[test]
32808    fn integrates_inverse_sine_exponentials_via_normalize_integrand() {
32809        let x = symbol!("x");
32810        let integrands = [
32811            parse!("exp(asin(a*x))*(1-a^2*x^2)^(5/2)"),
32812            parse!("exp(asin(a*x))*(1-a^2*x^2)^(3/2)"),
32813            parse!("exp(asin(a*x))*sqrt(1-a^2*x^2)"),
32814            parse!("exp(asin(a*x))/sqrt(1-a^2*x^2)"),
32815            parse!("exp(asin(a*x))/(1-a^2*x^2)^(3/2)"),
32816            parse!("exp(asin(a*x))/(1-a^2*x^2)^(5/2)"),
32817        ];
32818
32819        for integrand in integrands {
32820            let primitive = integrate(&integrand, x)
32821                .unwrap_or_else(|_| panic!("NormalizeIntegrand path should match: {integrand}"));
32822            assert!(
32823                !rubi_contains_unintegrable(&primitive),
32824                "NormalizeIntegrand path should not defer: {integrand}; primitive: {primitive}"
32825            );
32826        }
32827    }
32828
32829    #[test]
32830    fn simplify_integrand_splits_cancellable_log_affine_factor() {
32831        let x = symbol!("x");
32832        let integrand = parse!(
32833            "(x*g*e*log((x*e+d)/e)+g*d*log((x*e+d)/e)+g*d*(1-f*e/(g*d)))/(e^2*(1-x^2*c^2)^(1/2)*(x*e+d))"
32834        );
32835        let apart = integrand.apart(x);
32836
32837        assert!(rubi_simplify_integrand_mathematica_simplify_candidate_q(
32838            &integrand, &apart, x
32839        ));
32840        assert_eq!(
32841            rubi_simplify_integrand_mathematica_simplify_candidate(&integrand, x),
32842            Some(apart.to_owned())
32843        );
32844        assert_eq!(
32845            rubi_simplify_integrand(&integrand, x),
32846            parse!(
32847                "g*log((d+e*x)/e)/(e^2*(1-c^2*x^2)^(1/2))+(g*d-e*f)/(e^2*(1-c^2*x^2)^(1/2)*(d+e*x))"
32848            )
32849        );
32850
32851        let int_hide_form = parse!("(g*log(x+d/e)/e^2-(f*e-g*d)/(e^2*(d+e*x)))/(1-c^2*x^2)^(1/2)");
32852        let int_hide_apart = int_hide_form.apart(x);
32853        assert!(rubi_sum_q(&int_hide_apart));
32854        assert!(rubi_log_apart_cancellation_q(
32855            &int_hide_form,
32856            &int_hide_apart
32857        ));
32858        assert_eq!(
32859            rubi_simplify_integrand_mathematica_simplify_candidate(&int_hide_form, x),
32860            Some(int_hide_apart.to_owned())
32861        );
32862        assert_eq!(rubi_simplify_integrand(&int_hide_form, x), int_hide_apart);
32863
32864        let source_integrand = parse!("(f+g*x)*(a+b*asin(c*x))/(d+e*x)^2");
32865        let primitive = integrate(&source_integrand, x)
32866            .expect("Rubi's SimplifyIntegrand path should integrate the source expression");
32867        assert!(
32868            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
32869            "SimplifyIntegrand path should not defer: {primitive}"
32870        );
32871    }
32872
32873    #[test]
32874    fn expand_trig_to_exp_expands_hyperbolic_squares_before_simplifying_terms() {
32875        let x = symbol!("x");
32876        let v = parse!("v");
32877
32878        assert_eq!(
32879            rubi_hyperbolic_trig_to_exp(v.cosh().pow(2).as_view()),
32880            parse!("1/2+exp(2*v)/4+exp(-2*v)/4")
32881        );
32882        assert_eq!(
32883            rubi_hyperbolic_trig_to_exp(v.sinh().pow(2).as_view()),
32884            parse!("-1/2+exp(2*v)/4+exp(-2*v)/4")
32885        );
32886        let exp_positive = (Atom::num(2) * Atom::i() * &v).exp();
32887        let exp_negative = (-Atom::num(2) * Atom::i() * &v).exp();
32888        assert_eq!(
32889            rubi_trig_to_exp(v.cos().pow(2).as_view()),
32890            Atom::num(1) / 2 + &exp_positive / 4 + &exp_negative / 4
32891        );
32892        assert_eq!(
32893            rubi_trig_to_exp(v.sin().pow(2).as_view()),
32894            Atom::num(1) / 2 - exp_positive / 4 - exp_negative / 4
32895        );
32896
32897        for source_integrand in [
32898            parse!("f^(a+b*x)*cosh(d+e*x+f*x^2)^2"),
32899            parse!("f^(a+b*x)*sinh(d+e*x+f*x^2)^2"),
32900        ] {
32901            let primitive = integrate(&source_integrand, x)
32902                .expect("Rubi's ExpandTrigToExp path should integrate the hyperbolic square");
32903            assert!(
32904                rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
32905                "ExpandTrigToExp path should not defer: {primitive}"
32906            );
32907        }
32908    }
32909
32910    #[test]
32911    fn integrates_inverse_hyperbolic_cotangent_symbolic_power_paths() {
32912        let x_symbol = symbol!("x");
32913        let x = Atom::var(x_symbol);
32914        let a = Atom::var(symbol!("a"));
32915        let c = Atom::var(symbol!("c"));
32916        let p = Atom::var(symbol!("p"));
32917        let exponential = (Atom::num(2) * &p * (&a * &x).acoth()).exp();
32918        let integrands = [
32919            (&c - &c / (&a * &x)).pow(&p) * &exponential,
32920            (&c - a.pow(2) * &c * x.pow(2)).pow(&p) * &exponential,
32921            (&c - &c / (a.pow(2) * x.pow(2))).pow(&p) / &exponential,
32922        ];
32923
32924        for integrand in integrands {
32925            let primitive = integrate(&integrand, x_symbol)
32926                .unwrap_or_else(|_| panic!("compound coefficient should match: {integrand}"));
32927            assert!(
32928                !rubi_contains_unintegrable(&primitive),
32929                "compound coefficient should not defer: {integrand}; primitive: {primitive}"
32930            );
32931        }
32932    }
32933
32934    #[test]
32935    fn expand_integrand_preserves_affine_square_over_monomial_coefficients() {
32936        let x = symbol!("x");
32937        let expanded = rubi_expand_integrand(&parse!("(a+b*x)^2/x^2"), x);
32938
32939        assert_eq!(expanded.expand(), parse!("a^2/x^2 + 2*a*b/x + b^2"));
32940    }
32941
32942    #[test]
32943    fn rubi_poly_gcd_returns_monic_common_polynomial_factor() {
32944        let x = symbol!("x");
32945        assert_eq!(
32946            rubi_poly_gcd(&parse!("(1+x)^2*(2+x)"), &parse!("(1+x)*(3+x)"), x),
32947            Some(parse!("1+x"))
32948        );
32949        assert_eq!(
32950            rubi_poly_gcd(&parse!("1+x"), &parse!("2+x"), x),
32951            Some(Atom::num(1))
32952        );
32953        assert_eq!(
32954            rubi_poly_gcd(&parse!("1+x+3^(1/2)"), &parse!("1+x-3^(1/2)"), x),
32955            Some(Atom::num(1))
32956        );
32957        assert_eq!(
32958            rubi_poly_gcd(&parse!("x-2^(1/2)"), &parse!("x^2-2"), x),
32959            Some(parse!("-2^(1/2)+x"))
32960        );
32961        assert_eq!(
32962            rubi_poly_gcd(&parse!("(b-d*x)^3"), &parse!("-a*g+b*f-x*(-c*g+d*f)"), x,),
32963            Some(Atom::num(1))
32964        );
32965        let high_degree_gcd = rubi_poly_gcd(&parse!("(1+x)^342"), &parse!("(1+x)^2"), x)
32966            .expect("PolyGCD should not impose an 8-bit degree limit");
32967        assert!(eqq!(high_degree_gcd, (Atom::num(1) + Atom::var(x)).pow(2)));
32968    }
32969
32970    #[test]
32971    fn rubi_poly_gcd_handles_sparse_symbolic_even_polynomials() {
32972        let sub1 = symbol!("sub1");
32973        let numerator = parse!(
32974            "-B*a*b^2*d^4-6*B*b^3*c*d^3+6*C*a*b^2*d^3*sub1^2+C*a^2*b*d^4-6*C*b^3*c*d^2*sub1^2+6*C*b^3*c^2*d^2+7*A*b^3*d^4-6*D*a*b^2*c*d^2*sub1^2+6*D*a*b^2*d^2*sub1^4-6*D*a^2*b*d^3*sub1^2-D*a^3*d^4-6*D*b^3*c*d*sub1^4+12*D*b^3*c^2*d*sub1^2-6*D*b^3*c^3*d"
32975        );
32976        let denominator = parse!(
32977            "-12*a*b^5*c*d*sub1^4+6*a*b^5*d*sub1^6+6*a*b^5*c^2*d*sub1^2-6*a^2*b^4*c*d^2*sub1^2+6*a^2*b^4*d^2*sub1^4+2*a^3*b^3*d^3*sub1^2-6*b^6*c*sub1^6+6*b^6*c^2*sub1^4-2*b^6*c^3*sub1^2+2*b^6*sub1^8"
32978        );
32979
32980        assert_eq!(
32981            rubi_poly_gcd(&numerator, &denominator, sub1),
32982            Some(Atom::num(1))
32983        );
32984    }
32985
32986    #[test]
32987    fn rubi_rt_rationalizes_positive_rational_square_roots() {
32988        assert_eq!(
32989            rubi_rt(&(Atom::num(1) / Atom::num(3)), 2),
32990            parse!("3^(1/2)/3")
32991        );
32992    }
32993
32994    #[test]
32995    fn rubi_numerator_and_denominator_split_rationalized_roots() {
32996        let root = rubi_rt(&(Atom::num(2) / Atom::num(3)), 3);
32997        assert_eq!(rubi_numerator(&root), parse!("18^(1/3)"));
32998        assert_eq!(rubi_denominator_atom(&root), Atom::num(3));
32999    }
33000
33001    #[test]
33002    fn rubi_rt_attaches_unknown_product_sign_like_mathematica() {
33003        assert_eq!(rubi_rt(&parse!("-f*g"), 2), parse!("sqrt(-f)*sqrt(g)"));
33004    }
33005
33006    #[test]
33007    fn int_part_and_frac_part_split_symbolic_sums_like_rubi() {
33008        let m = parse!("-1-3*n/4");
33009        assert_eq!(rubi_int_part(&m), Atom::num(-1));
33010        assert_eq!(rubi_frac_part(&m), parse!("-3*n/4"));
33011
33012        let scaled = parse!("2*(n+1/2)");
33013        assert_eq!(rubi_int_part(&scaled), Atom::num(1));
33014        assert_eq!(rubi_frac_part(&scaled), parse!("2*n"));
33015    }
33016
33017    #[test]
33018    fn pure_function_of_tan_rejects_mixed_trig_families_like_rubi() {
33019        let x = symbol!("x");
33020        let u = parse!("(-2*sin(2*x)+sqrt(cos(x)*sin(x)^3))/(-sqrt(cos(x)^3*sin(x))+sqrt(tan(x)))");
33021
33022        assert_eq!(rubi_function_of_trig(&u, x), Some(Atom::var(x)));
33023        assert!(
33024            !rubi_pure_function_of_q(&Atom::var(x).tan(), &u, x),
33025            "Rubi's PureFunctionOfTanQ rejects sin/cos factors"
33026        );
33027        assert!(
33028            !rubi_pure_function_of_q(&Atom::var(x).cot(), &u, x),
33029            "the explicit sqrt(tan[x]) term makes the Rubi Cot[x] row decline"
33030        );
33031    }
33032
33033    #[test]
33034    fn rubi_expand_to_sum_ports_source_shaped_parts_helpers() {
33035        let x = symbol!("x");
33036        assert!(rubi_binomial_q(parse!("1+a*x^3").as_view(), x));
33037        assert!(rubi_trinomial_q(&parse!("1+a*x^3+b*x^6"), x));
33038        assert!(!rubi_trinomial_q(&parse!("a+b*x+c*x^2"), x));
33039        assert!(!rubi_trinomial_q(&parse!("(a+b*x^2)^2"), x));
33040        assert!(rubi_generalized_binomial_q(&parse!("a*x^2+b*x^5"), x));
33041        assert!(rubi_generalized_trinomial_q(
33042            &parse!("a*x^2+b*x^5+c*x^8"),
33043            x
33044        ));
33045        assert!(rubi_generalized_trinomial_q(&parse!("1-(1-x^2)^3"), x));
33046        assert!(!rubi_generalized_trinomial_match_q(
33047            &parse!("1-(1-x^2)^3"),
33048            x
33049        ));
33050
33051        assert_eq!(
33052            rubi_expand_to_sum(&parse!("(1+x)^2"), x),
33053            parse!("1+2*x+x^2")
33054        );
33055        assert_eq!(rubi_expand_to_sum(&parse!("1+a*x^3"), x), parse!("1+a*x^3"));
33056        assert_eq!(
33057            rubi_expand_to_sum(&parse!("1+a*x^3+b*x^6"), x),
33058            parse!("1+a*x^3+b*x^6")
33059        );
33060        assert_eq!(
33061            rubi_expand_to_sum(&parse!("a*x^2+b*x^5"), x),
33062            parse!("a*x^2+b*x^5")
33063        );
33064        assert_eq!(
33065            rubi_expand_to_sum(&parse!("a*x^2+b*x^5+c*x^8"), x),
33066            parse!("a*x^2+b*x^5+c*x^8")
33067        );
33068        assert_eq!(
33069            rubi_expand_to_sum(&parse!("1-(1-x^2)^3"), x),
33070            parse!("3*x^2-3*x^4+x^6")
33071        );
33072    }
33073
33074    #[test]
33075    fn rubi_linear_match_q_keeps_source_shape_distinct_from_linear_q() {
33076        let x = symbol!("x");
33077        let undistributed = Atom::num(2) * (Atom::num(1) + Atom::var(x));
33078
33079        assert!(rubi_linear_q(parse!("1+2*x").as_view(), x));
33080        assert!(rubi_linear_match_q(&parse!("1+2*x"), x));
33081        assert!(rubi_linear_q(undistributed.as_view(), x));
33082        assert!(!rubi_linear_match_q(&undistributed, x));
33083        assert!(rubi_linear_match_q_list(
33084            &[
33085                &parse!("1-k*x"),
33086                &parse!("x"),
33087                &parse!("1-x"),
33088                &parse!("1+(-2+k)*x"),
33089            ],
33090            x,
33091        ));
33092    }
33093
33094    #[test]
33095    fn rubi_quadratic_match_q_keeps_source_shape_distinct_from_quadratic_q() {
33096        let x = symbol!("x");
33097        let undistributed = parse!("(a+b*x+c*x^2)/f^2");
33098
33099        assert!(rubi_quadratic_match_q(&parse!("a+b*x+c*x^2"), x));
33100        assert!(rubi_quadratic_match_q(&parse!("a+c*x^2"), x));
33101        assert!(rubi_quadratic_match_q(&parse!("c*x^2"), x));
33102        assert!(rubi_quadratic_q(&undistributed, x));
33103        assert!(!rubi_quadratic_match_q(&undistributed, x));
33104    }
33105
33106    #[test]
33107    fn binomial_square_polynomial_follows_rubi_2018_2333_2009_path() {
33108        let x = symbol!("x");
33109        let integrand = parse!("(a+b*x^2)^2*(A+B*x+C*x^2+D*x^3)/x");
33110        let primitive = integrate(&integrand, x)
33111            .expect("Rubi DownValues 2018, 2333, and 2009 should integrate corpus line 117");
33112
33113        assert!(
33114            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
33115            "the Mathematica path should produce a completed primitive: {primitive}"
33116        );
33117    }
33118
33119    #[test]
33120    fn simplify_integrand_normalizes_linear_inverse_tangent_argument() {
33121        let x = symbol!("x");
33122        let expr = parse!("atan((1/3)^(1/2)*(1+2*x))");
33123        let normalized = rubi_simplify_integrand(&expr, x);
33124
33125        let AtomView::Fun(fun) = normalized.as_view() else {
33126            panic!("normalized expression should remain an inverse tangent: {normalized}");
33127        };
33128        assert_eq!(fun.get_symbol(), symbol!("atan"));
33129        let arguments = fun.into_iter().collect::<Vec<_>>();
33130        assert_eq!(arguments.len(), 1);
33131        let argument = arguments[0].to_owned();
33132        assert!(
33133            rubi_linear_match_q(&argument, x),
33134            "Rubi NormalizeIntegrandAux should expose affine inverse tangent arguments: {argument}"
33135        );
33136        assert_ne!(
33137            argument,
33138            parse!("(1/3)^(1/2)*(1+2*x)"),
33139            "linear product should be expanded inside inverse tangent arguments"
33140        );
33141    }
33142
33143    #[test]
33144    fn simplify_integrand_recombines_charlwood_146_quartic_denominator() {
33145        let x = symbol!("x");
33146        let recursive_integrand = parse!("x*(1+2*x^2)/((1+x^2)^(1/2)*(1+x+x^2)*(1-x+x^2))");
33147        let expected = parse!("x*(1+2*x^2)/((1+x^2)^(1/2)*(1+x^2+x^4))");
33148
33149        assert_eq!(
33150            rubi_simplify_integrand(&recursive_integrand, x),
33151            expected,
33152            "Mathematica Simplify exposes the quartic-trinomial rule 2238 shape"
33153        );
33154        let rule_2238 = rubi_rules()
33155            .iter()
33156            .find(|rule| rule.downvalue_order == Some(2238))
33157            .expect("Rubi rule 2238 is loaded");
33158        assert!(
33159            matcher_rule_for_test(&expected, x, rule_2238).is_some(),
33160            "the simplified Charlwood 146 payload must dispatch to source rule 2238"
33161        );
33162    }
33163
33164    #[test]
33165    fn simplify_integrand_preserves_bondarenko_38_log_product() {
33166        let x = symbol!("x");
33167        let integrand = parse!("(x*log(1+x+x^2)+2*x^2*log(1+x+x^2))/(1+x+x^2)");
33168        let simplified = rubi_simplify_integrand(&integrand, x);
33169        let expected = parse!("x*(1+2*x)*log(1+x+x^2)/(1+x+x^2)");
33170
33171        assert!(
33172            eqq!(simplified, expected),
33173            "SimplifyIntegrand should preserve Rubi's product shape; got {simplified}"
33174        );
33175    }
33176
33177    #[test]
33178    fn simplify_integrand_cancels_charlwood_38_log_derivative_quotient_like_rubi() {
33179        let x = symbol!("x");
33180        let quotient = parse!("sqrt(1+x^2)*(1+x/sqrt(1+x^2))/(x+sqrt(1+x^2))");
33181        let simplified_quotient = rubi_simplify_integrand(&quotient, x);
33182        assert_eq!(
33183            simplified_quotient,
33184            parse!("1"),
33185            "Rubi SimplifyIntegrand reduces the Charlwood line 38 logarithmic derivative quotient to 1"
33186        );
33187
33188        let logarithmic = &quotient * parse!("log(1+x^2)");
33189        let simplified_logarithmic = rubi_simplify_integrand(&logarithmic, x);
33190        assert_eq!(
33191            simplified_logarithmic,
33192            parse!("log(1+x^2)"),
33193            "Rubi SimplifyIntegrand keeps only the logarithmic factor after reducing the quotient"
33194        );
33195
33196        let expanded_logarithmic =
33197            parse!("x*log(1+x^2)/(x+sqrt(1+x^2))+sqrt(1+x^2)*log(1+x^2)/(x+sqrt(1+x^2))");
33198        let simplified_expanded_logarithmic = rubi_simplify_integrand(&expanded_logarithmic, x);
33199        assert_eq!(
33200            simplified_expanded_logarithmic,
33201            parse!("log(1+x^2)"),
33202            "Rubi SimplifyIntegrand should follow Mathematica Simplify before NormalizeIntegrandAux for the generated sum"
33203        );
33204
33205        let arctangent = &quotient * parse!("atan(x)");
33206        let simplified_arctangent = rubi_simplify_integrand(&arctangent, x);
33207        assert_eq!(
33208            simplified_arctangent,
33209            parse!("atan(x)"),
33210            "Rubi SimplifyIntegrand keeps only the inverse tangent factor after reducing the quotient"
33211        );
33212
33213        let expanded_arctangent =
33214            parse!("x*atan(x)/(x+sqrt(1+x^2))+sqrt(1+x^2)*atan(x)/(x+sqrt(1+x^2))");
33215        let simplified_expanded_arctangent = rubi_simplify_integrand(&expanded_arctangent, x);
33216        assert_eq!(
33217            simplified_expanded_arctangent,
33218            parse!("atan(x)"),
33219            "Rubi SimplifyIntegrand should follow Mathematica Simplify for the expanded inverse tangent quotient"
33220        );
33221    }
33222
33223    #[test]
33224    fn simplify_integrand_follows_charlwood_35_trig_quotient_trace() {
33225        let x = symbol!("x");
33226        let integrand = parse!("e^x*cos(x)*sin(x)^3/(1-sin(x)^2)^(1/2)");
33227        let simplified = rubi_simplify_integrand(&integrand, x);
33228        let expected = parse!("e^x*(cos(x)^2)^(1/2)*sin(x)^2*tan(x)");
33229
33230        assert_eq!(
33231            simplified, expected,
33232            "SimplifyIntegrand should match the Charlwood line 35 Rubi trace"
33233        );
33234    }
33235
33236    #[test]
33237    fn simplify_integrand_factors_trig_substitution_radicand_like_mathematica() {
33238        let x = symbol!("x");
33239        let payload = parse!("2*x/((1+x^2)^2*sqrt((1+4*x+2*x^2-4*x^3+x^4)/(1+x^2)^2))");
33240        let expected = parse!("2*x/((1+x^2)^2*sqrt((1+2*x-x^2)^2/(1+x^2)^2))");
33241
33242        assert_eq!(
33243            rubi_simplify_integrand(&payload, x),
33244            expected,
33245            "Mathematica Simplify preserves the perfect square inside the rule-4902 radicand"
33246        );
33247    }
33248
33249    #[test]
33250    fn integrates_misc_trig_1124_through_mathematica_rule_4901_path() {
33251        let x = symbol!("x");
33252        let integrand = parse!("(cos(x)+sin(x))/sqrt(1+sin(2*x))");
33253        let primitive = integrate(&integrand, x)
33254            .expect("Rubi DownValues 3042 and 4901 should complete corpus line 1124");
33255
33256        assert!(
33257            rubi_integral_free_q(&primitive) && !rubi_contains_unintegrable(&primitive),
33258            "the Mathematica rule-4901 path should produce a completed primitive: {primitive}"
33259        );
33260    }
33261
33262    #[test]
33263    fn mathematica_trig_quotient_rewrites_cos_tan_product() {
33264        let expr = parse!("e^x*sin(x)^2*cos(x)*tan(x)");
33265        let simplified =
33266            rubi_mathematica_trig_quotient(&expr).expect("cos(x)*tan(x) should simplify");
33267
33268        assert_eq!(
33269            simplified,
33270            parse!("e^x*sin(x)^3"),
33271            "Mathematica evaluates Cos[x]*Tan[x] to Sin[x] in the Rubi block-20 payload"
33272        );
33273
33274        let sub_expr = parse!("e^sub1*sin(sub1)^2*cos(sub1)*tan(sub1)");
33275        let sub_simplified =
33276            rubi_mathematica_trig_quotient(&sub_expr).expect("cos(sub1)*tan(sub1) should simplify");
33277        assert_eq!(sub_simplified, parse!("e^sub1*sin(sub1)^3"));
33278    }
33279
33280    #[test]
33281    fn mathematica_trig_quotient_rewrites_reciprocal_products() {
33282        for (input, expected) in [
33283            ("sin(x)^3*csc(x)", "sin(x)^2"),
33284            ("cos(x)^3*sec(x)", "cos(x)^2"),
33285            ("tan(x)^3*cot(x)", "tan(x)^2"),
33286            ("sin(x)*sec(x)", "tan(x)"),
33287            ("cos(x)*csc(x)", "cot(x)"),
33288            ("tan(x)*csc(x)", "sec(x)"),
33289            ("cot(x)*sec(x)", "csc(x)"),
33290            ("cot(x)/csc(x)^3", "cos(x)*sin(x)^2"),
33291            ("tan(x)/sec(x)^3", "sin(x)*cos(x)^2"),
33292            ("sin(x)^2/tan(x)", "sin(x)*cos(x)"),
33293            ("cos(x)^2/cot(x)", "cos(x)*sin(x)"),
33294            ("tan(x)^2/sin(x)", "tan(x)*sec(x)"),
33295            ("cot(x)^2/cos(x)", "cot(x)*csc(x)"),
33296            ("sec(x)^2/tan(x)", "sec(x)*csc(x)"),
33297            ("csc(x)^2/cot(x)", "csc(x)*sec(x)"),
33298        ] {
33299            assert_eq!(
33300                rubi_mathematica_trig_quotient(&parse!(input)),
33301                Some(parse!(expected)),
33302                "Mathematica automatic evaluation differs for {input}"
33303            );
33304        }
33305    }
33306
33307    #[test]
33308    fn mathematica_hyperbolic_quotient_rewrites_reciprocal_products() {
33309        for (input, expected) in [
33310            ("x^3*sinh(z)*sech(z)", "x^3*tanh(z)"),
33311            ("cosh(z)^z*tanh(z)", "sinh(z)*cosh(z)^(-1+z)"),
33312            ("sinh(z)^3*sech(z)^2", "sinh(z)*tanh(z)^2"),
33313            ("cosh(z)^3*csch(z)^2", "cosh(z)*coth(z)^2"),
33314            ("sinh(z)*csch(z)", "1"),
33315            ("cosh(z)*sech(z)", "1"),
33316            ("tanh(z)*coth(z)", "1"),
33317            ("cosh(z)*tanh(z)", "sinh(z)"),
33318            ("sinh(z)*coth(z)", "cosh(z)"),
33319            ("tanh(z)*csch(z)", "sech(z)"),
33320            ("coth(z)*sech(z)", "csch(z)"),
33321        ] {
33322            assert_eq!(
33323                rubi_mathematica_hyperbolic_quotient(&parse!(input)),
33324                Some(parse!(expected)),
33325                "Mathematica automatic evaluation differs for {input}"
33326            );
33327        }
33328    }
33329
33330    #[test]
33331    fn mathematica_evaluates_half_integer_i_pi_exponentials() {
33332        for (multiple, expected) in [
33333            ("0", Atom::num(1)),
33334            ("1/2", rubi_i()),
33335            ("1", -Atom::num(1)),
33336            ("3/2", -rubi_i()),
33337            ("2", Atom::num(1)),
33338            ("-1/2", -rubi_i()),
33339        ] {
33340            assert_eq!(
33341                rubi_exp_i_pi_multiple(&parse!(multiple)),
33342                expected,
33343                "Mathematica automatic evaluation differs for Exp[I*Pi*({multiple})]"
33344            );
33345        }
33346    }
33347
33348    #[test]
33349    fn symbolica_collapses_one_to_symbolic_power() {
33350        let x = Atom::var(symbol!("x"));
33351        assert_eq!(Atom::num(1).pow(x), Atom::num(1));
33352        assert_eq!(parse!("1^x"), Atom::num(1));
33353    }
33354
33355    #[test]
33356    fn simplify_proves_timofeev_671_trig_substitution_coefficient() {
33357        let quotient = parse!("(2*x+sin(2*x))/(x*sin(x)*(-sin(x))-cos(x)*(sin(x)+x*cos(x)))");
33358        assert_eq!(
33359            rubi_simplify(&quotient),
33360            Atom::num(-2),
33361            "trig-to-exp candidate: {}",
33362            rubi_trig_to_exp(quotient.as_view()).together()
33363        );
33364    }
33365
33366    #[test]
33367    fn simplify_keeps_radical_trig_derivative_quotient_algebraic() {
33368        let x = symbol!("x");
33369        let quotient =
33370            parse!("1/(sqrt(b+a*cos(e+f*x))*(d+c*cos(e+f*x))^(3/2)*(A+B*cos(e+f*x))*sin(e+f*x))");
33371        let simplified = rubi_simplify(&quotient);
33372
33373        assert!(simplified.contains(&x));
33374    }
33375
33376    #[test]
33377    fn integrates_polynomial_times_sine_secant_via_rubi_3719() {
33378        assert_derivative_round_trip(parse!("(c+d*x)^2*sec(a+b*x)*sin(a+b*x)"));
33379    }
33380
33381    #[test]
33382    fn integrates_exponential_of_inverse_cosecant_via_rubi_5267() {
33383        assert_rubi_derivative_round_trip(parse!("exp(acsc(a*x))/x^4"));
33384    }
33385
33386    #[test]
33387    fn subst_power_target_follows_rubi_compatible_power_branch() {
33388        let x = symbol!("x");
33389        let payload = parse!("1+x^(1/2)+x+x^(3/2)+x^a");
33390
33391        assert_eq!(
33392            rubi_subst_power_target(&payload, x, &Atom::num(1), &parse!("1/2"), &parse!("y"),),
33393            parse!("1+y+x+y^3+x^a")
33394        );
33395    }
33396
33397    #[test]
33398    fn piecewise_linear_slope_simplifies_inverse_compositions_like_mathematica() {
33399        let x = symbol!("x");
33400        for (expression, slope) in [
33401            ("atanh(tanh(a+b*x))", "b"),
33402            ("atan(tan(a+b*x))", "b"),
33403            ("atan(cot(a+b*x))", "-b"),
33404            ("atanh(coth(a+b*x))", "b"),
33405            ("acoth(coth(a+b*x))", "b"),
33406        ] {
33407            let expression = parse!(expression);
33408            assert_eq!(rubi_slope(&expression, x), parse!(slope), "{expression}");
33409            assert!(rubi_piecewise_linear_q(&expression, x), "{expression}");
33410        }
33411    }
33412
33413    #[test]
33414    fn simp_preserves_tangent_polynomial_sum_like_latest_rubi() {
33415        let x = symbol!("x");
33416        let input = parse!(
33417            "8*a^2*b-7/2*a^3*tan(c+d*x)+21/2*a*b^2*tan(c+d*x)\
33418             -5/2*a^2*b*tan(c+d*x)^2+7/2*b^3*tan(c+d*x)^2"
33419        );
33420
33421        assert_eq!(rubi_simp(&input, x), input);
33422    }
33423
33424    #[test]
33425    fn star_identity_reuses_owned_input_and_preserves_borrowed_input() {
33426        let owned = parse!("f(x)+g(y)+h(z)");
33427        let original_allocation = owned.as_view().get_data().as_ptr();
33428        let identity = rubi_star(Atom::num(1), owned);
33429        assert_eq!(identity, parse!("f(x)+g(y)+h(z)"));
33430        assert_eq!(original_allocation, identity.as_view().get_data().as_ptr());
33431
33432        let borrowed = parse!("f(x)+g(y)+h(z)");
33433        let independent = rubi_star(Atom::num(1), &borrowed);
33434        assert_eq!(independent, borrowed);
33435        assert_ne!(
33436            borrowed.as_view().get_data().as_ptr(),
33437            independent.as_view().get_data().as_ptr()
33438        );
33439    }
33440
33441    #[test]
33442    fn star_distributes_its_multiplier_over_a_sum() {
33443        assert_eq!(rubi_star(parse!("a"), parse!("u+v")), parse!("a*u+a*v"));
33444    }
33445
33446    #[test]
33447    fn star_uses_rubi_eq_q_for_a_zero_multiplier() {
33448        assert_eq!(
33449            rubi_star(parse!("a*(b+c)-a*b-a*c"), parse!("u")),
33450            Atom::num(0)
33451        );
33452    }
33453
33454    #[test]
33455    fn integrates_power_over_atanh_tanh_via_rubi_2168() {
33456        assert_rubi_derivative_round_trip(parse!("x^3/sqrt(atanh(tanh(a+b*x)))"));
33457    }
33458
33459    #[test]
33460    fn simplify_integrand_follows_timofeev_498_trig_substitution_trace() {
33461        let x = symbol!("x");
33462        let integrand = parse!("(1+x^(-3))*(-2*x/(1+x^2)+a*(1+x^2))^2/(1+x^2)");
33463        let simplified = rubi_simplify_integrand(&integrand, x);
33464        let expected = parse!("((1+x^3)*(a-2*x+2*a*x^2+a*x^4)^2)/(x^3*(1+x^2)^3)");
33465        let sign_input = parse!("(2*x-a-2*a*x^2-a*x^4)^2");
33466        let sign_expected = parse!("(-2*x+a+2*a*x^2+a*x^4)^2");
33467        assert_eq!(
33468            rubi_normalize_polynomial_power_lead_signs(sign_input.as_view(), x),
33469            sign_expected,
33470            "the Symbolica-to-Mathematica Plus-order adapter should normalize the power base",
33471        );
33472
33473        assert_eq!(
33474            simplified, expected,
33475            "SimplifyIntegrand should follow Rubi's NormalizeIntegrandAux payload shape"
33476        );
33477    }
33478
33479    #[test]
33480    fn simplify_integrand_clears_laurent_denominator_like_bondarenko_28_trace() {
33481        let x = symbol!("x");
33482        let integrand = parse!("sqrt(1+1/x)/(-1/x+x)");
33483        let simplified = rubi_simplify_integrand(&integrand, x);
33484        let expected = parse!("x*sqrt(1+1/x)/(-1+x^2)");
33485
33486        assert_eq!(
33487            simplified, expected,
33488            "SimplifyIntegrand should match Rubi's NormalizeIntegrandAux payload for Bondarenko Problems.input line 28"
33489        );
33490    }
33491
33492    #[test]
33493    fn simplify_integrand_factors_exponential_denominator_like_rubi() {
33494        let x = symbol!("x");
33495        let integrand = parse!("x/(1+2*exp(x)+exp(2*x))");
33496        let simplified = rubi_simplify_integrand(&integrand, x);
33497        let expected = parse!("x/(1+exp(x))^2");
33498
33499        assert_eq!(
33500            simplified, expected,
33501            "Rubi SimplifyIntegrand first applies Mathematica Simplify, which exposes the squared exponential denominator"
33502        );
33503    }
33504
33505    #[test]
33506    fn simplify_integrand_factors_timofeev_568_square_radicand_like_mathematica() {
33507        let x = symbol!("x");
33508        let integrand = parse!("sqrt(x)*sqrt(1/(1+2*x^2+x^4))/(2+x^2)");
33509        let expected = parse!("sqrt(x)*sqrt((1+x^2)^(-2))/(2+x^2)");
33510
33511        assert_eq!(rubi_simplify_integrand(&integrand, x), expected);
33512    }
33513
33514    #[test]
33515    fn simplify_integrand_leaves_bondarenko_28_inner_substitution_target() {
33516        let x = symbol!("x");
33517        let integrand = parse!("sqrt(1+1/x)/(-1+x^2)");
33518        let simplified = rubi_simplify_integrand(&integrand, x);
33519
33520        assert_eq!(
33521            simplified, integrand,
33522            "SimplifyIntegrand should not make Rubi 9.4 block 5 fire before the fractional-power substitution path"
33523        );
33524    }
33525
33526    #[test]
33527    fn fractional_quotient_substitution_handles_bondarenko_28_inner_target() {
33528        let x = symbol!("x");
33529        let sub = symbol!("sub_test");
33530        let integrand = parse!("sqrt(1+1/x)/(-1+x^2)");
33531        let data = rubi_subst_for_fractional_power_of_quotient_of_linears(&integrand, x, sub)
33532            .expect("Bondarenko line 28 inner integrand should use Rubi SubstForFractionalPowerOfQuotientOfLinears");
33533
33534        assert_eq!(data.denominator, 2);
33535        assert_eq!(data.base, parse!("1+1/x"));
33536        assert_eq!(data.integrand, parse!("1/(2-sub_test^2)"));
33537        assert_eq!(data.multiplier, parse!("-1"));
33538    }
33539
33540    #[test]
33541    fn fractional_power_of_quotient_ignores_different_later_quotient_base_like_rubi() {
33542        let x = symbol!("x");
33543        let expr = parse!("sqrt((1+x)/(2+x))*sqrt((3+x)/(4+x))");
33544        let (denominator, base, a, b, c, d) =
33545            rubi_fractional_power_of_quotient_of_linears(&expr, x)
33546                .expect("Rubi scans through nonmatching later quotient bases");
33547
33548        assert_eq!(denominator, 2);
33549        assert!(
33550            rubi_equivalent_q(&base, &parse!("(1+x)/(2+x)"))
33551                || rubi_equivalent_q(&base, &parse!("(3+x)/(4+x)")),
33552            "selected quotient base should be one of the visible fractional quotient bases: {base}"
33553        );
33554        assert!(
33555            neq!(b, 0) && neq!(d, 0),
33556            "selected base should be a proper quotient of linears: {a}, {b}, {c}, {d}"
33557        );
33558    }
33559
33560    #[test]
33561    fn simpler_integrand_cancels_common_factors_like_rubi() {
33562        let integrand = parse!("sqrt(1+1/x)/(-1/x+x)");
33563        let simplified = parse!("x*sqrt(1+1/x)/(-1+x^2)");
33564        assert_eq!(
33565            rubi_cancel_common_factors(&simplified, &integrand),
33566            (parse!("x/(-1+x^2)"), parse!("1/(-1/x+x)")),
33567            "CancelCommonFactors should remove the common radical before SimplerIntegrandQ compares the residuals"
33568        );
33569    }
33570
33571    #[test]
33572    fn nice_sqrt_q_matches_rubi_4_17_3_fractional_power_test() {
33573        assert!(rubi_nice_sqrt_q(&parse!("2")));
33574        assert!(!rubi_nice_sqrt_q(&parse!("-2")));
33575        assert!(rubi_nice_sqrt_q(&parse!("a^2")));
33576        assert!(!rubi_nice_sqrt_q(&parse!("a^3")));
33577        assert!(!rubi_nice_sqrt_q(&parse!("a*b^2")));
33578        assert!(rubi_nice_sqrt_q(&parse!("(1+x)^2")));
33579        assert!(!rubi_nice_sqrt_q(&parse!("(1+x)^3")));
33580        assert!(!rubi_nice_sqrt_q(&parse!("sqrt(a)*b^2")));
33581    }
33582
33583    #[test]
33584    fn subst_power_matches_rubi_4_17_3_recursive_definition() {
33585        let x = symbol!("x");
33586        assert_eq!(
33587            rubi_subst_power(&parse!("a+x+x^m+(1+x)^p+f(x^q)"), x, 3),
33588            parse!("a+x^3+x^(3*m)+(1+x^3)^p+f(x^(3*q))")
33589        );
33590    }
33591
33592    #[test]
33593    fn expand_integrand_product_follows_bondarenko_38_log_square_trace() {
33594        let x = symbol!("x");
33595        let logarithmic = parse!("log(1+x+x^2)");
33596        let multiplier = parse!("x*(1+2*x)/(1+x+x^2)");
33597        let expanded = rubi_expand_integrand_product_sum(&logarithmic, &multiplier, x)
33598            .expect("Rubi 3.5 block 11 should expand the log-rational payload");
33599        let expected = parse!("2*log(1+x+x^2)-(2+x)*log(1+x+x^2)/(1+x+x^2)");
33600
33601        assert!(
33602            eqq!(expanded, expected),
33603            "ExpandIntegrand should match the Rubi trace for Log[1+x+x^2]^2; got {expanded}"
33604        );
33605    }
33606
33607    #[test]
33608    fn expand_integrand_4_17_collects_log_reciprocal_terms_before_distribution() {
33609        let x = symbol!("x");
33610        let logarithmic = parse!("(1+log(x))^2");
33611        let reciprocal_product = parse!("1/(x*(1+x))");
33612        let expanded_reciprocals = rubi_expand_integrand(&reciprocal_product, x);
33613        let collected = rubi_collect_recip_terms(&expanded_reciprocals, x);
33614        assert!(eqq!(collected, reciprocal_product));
33615
33616        let latest_branch =
33617            rubi_expand_integrand_log_reciprocal_product(&logarithmic, &reciprocal_product, x)
33618                .expect("the Rubi 4.17.3 three-argument branch should match");
33619        assert!(eqq!(latest_branch, logarithmic * reciprocal_product));
33620        assert!(
33621            rubi_expand_integrand_product_changed(
33622                &parse!("(1+log(x))^2"),
33623                &parse!("1/(x*(1+x))"),
33624                x,
33625            )
33626            .is_none(),
33627            "the specific 4.17.3 branch must block generic partial-fraction distribution"
33628        );
33629    }
33630
33631    #[test]
33632    fn simplify_integrand_preserves_bondarenko_38_log_rational_product() {
33633        let x = symbol!("x");
33634        let integrand = parse!("x*(1+2*x)*log(1+x+x^2)/(1+x+x^2)");
33635        let simplified = rubi_simplify_integrand(&integrand, x);
33636
33637        assert!(
33638            eqq!(simplified, integrand),
33639            "SimplifyIntegrand should preserve Rubi's log-rational product form; got {simplified}"
33640        );
33641    }
33642
33643    #[test]
33644    fn simplify_integrand_preserves_constructed_bondarenko_38_log_rational_product() {
33645        let x = symbol!("x");
33646        let x_atom = Atom::var(x);
33647        let rfx = parse!("1+x+x^2");
33648        let logarithmic = (Atom::num(1) * rfx.pow(Atom::num(1))).log();
33649        let recursive_integrand =
33650            &x_atom * logarithmic.pow(Atom::num(2) - Atom::num(1)) * rubi_d(&rfx, x) / &rfx;
33651        let simplified = rubi_simplify_integrand(&recursive_integrand, x);
33652        let expected = parse!("x*(1+2*x)*log(1+x+x^2)/(1+x+x^2)");
33653
33654        assert!(
33655            eqq!(simplified, expected),
33656            "SimplifyIntegrand should preserve Rubi's constructed log-rational product form; got {simplified}"
33657        );
33658    }
33659
33660    #[test]
33661    fn simplify_integrand_factors_exponential_square_denominator_like_rubi() {
33662        let x = symbol!("x");
33663        let x_atom = Atom::var(x);
33664        let exp_x = Atom::var(Symbol::E).pow(&x_atom);
33665        let integrand = &x_atom / (Atom::num(1) + Atom::num(2) * &exp_x + exp_x.pow(2));
33666        let simplified = rubi_simplify_integrand(&integrand, x);
33667        let expected = &x_atom / (Atom::num(1) + exp_x).pow(2);
33668
33669        assert_eq!(
33670            simplified, expected,
33671            "SimplifyIntegrand should match the Rubi trace for 2.3 Exponential functions.input line 577; got {simplified}"
33672        );
33673    }
33674
33675    #[test]
33676    fn expand_integrand_product_follows_bondarenko_37_log_square_trace() {
33677        let x = symbol!("x");
33678        let logarithmic = parse!("log(2+x^2)");
33679        let multiplier = parse!("x^2/(2+x^2)");
33680        let expanded = rubi_expand_integrand_product_sum(&logarithmic, &multiplier, x)
33681            .expect("Rubi 3.1.3 block 18 should expand the log-rational payload");
33682        let expected = parse!("log(2+x^2)-2*log(2+x^2)/(2+x^2)");
33683
33684        assert!(
33685            eqq!(expanded, expected),
33686            "ExpandIntegrand should match the Bondarenko 37 Rubi trace; got {expanded}"
33687        );
33688    }
33689
33690    #[test]
33691    fn expand_integrand_product_splits_bondarenko_38_log_quadratic_remainder() {
33692        let x = symbol!("x");
33693        let i = Atom::i();
33694        let sqrt_three = Atom::num(3).sqrt();
33695        let normalized_sqrt_three = Atom::num(3) * (Atom::num(1) / Atom::num(3)).sqrt();
33696        let logarithmic = parse!("log(1+x+x^2)");
33697        let multiplier = parse!("(2+x)/(1+x+x^2)");
33698        let expanded = rubi_expand_integrand_product_sum(&logarithmic, &multiplier, x)
33699            .expect("Rubi 3.5 block 11 should split the log-quadratic remainder");
33700        let x_atom = Atom::var(x);
33701        let expected = (Atom::num(1) - &i * &normalized_sqrt_three) * &logarithmic
33702            / (Atom::num(1) - &i * &sqrt_three + Atom::num(2) * &x_atom)
33703            + (Atom::num(1) + &i * &normalized_sqrt_three) * &logarithmic
33704                / (Atom::num(1) + &i * &sqrt_three + Atom::num(2) * &x_atom);
33705
33706        assert!(
33707            eqq!(expanded, expected),
33708            "ExpandIntegrand should match Rubi's complex split for the log-quadratic remainder; got {expanded}"
33709        );
33710    }
33711
33712    #[test]
33713    fn expand_integrand_product_splits_bondarenko_38_negative_log_quadratic_remainder() {
33714        let x = symbol!("x");
33715        let logarithmic = parse!("log(1+x+x^2)");
33716        let positive = parse!("(2+x)/(1+x+x^2)");
33717        let negative = parse!("(-2-x)/(1+x+x^2)");
33718        let positive_expanded = rubi_expand_integrand_product_sum(&logarithmic, &positive, x)
33719            .expect("positive log-quadratic remainder should split");
33720        let negative_expanded = rubi_expand_integrand_product_sum(&logarithmic, &negative, x)
33721            .expect("negative log-quadratic remainder should split");
33722
33723        assert!(
33724            eqq!(negative_expanded, -positive_expanded),
33725            "negative remainder should follow the same Rubi split with a sign; got {negative_expanded}"
33726        );
33727    }
33728
33729    #[test]
33730    fn expand_integrand_product_splits_bondarenko_36_log_linear_remainder() {
33731        let x = symbol!("x");
33732        let i = Atom::i();
33733        let x_atom = Atom::var(x);
33734        let logarithmic = parse!("log(1+x)");
33735        let multiplier = parse!("x/(1+x^2)");
33736        let expanded = rubi_expand_integrand_product_sum(&logarithmic, &multiplier, x)
33737            .expect("Rubi 3.3 block 29 should split the log-linear rational payload");
33738        let expected = &logarithmic / (Atom::num(2) * (&i + &x_atom))
33739            - &logarithmic / (Atom::num(2) * (&i - x_atom));
33740
33741        assert!(
33742            eqq!(expanded, expected),
33743            "ExpandIntegrand should match Rubi's complex split for Bondarenko line 36; got {expanded}"
33744        );
33745    }
33746
33747    #[test]
33748    fn integrates_bondarenko_38_expanded_negative_log_quadratic_remainder() {
33749        let x = symbol!("x");
33750        let logarithmic = parse!("log(1+x+x^2)");
33751        let negative = parse!("(-2-x)/(1+x+x^2)");
33752        let expanded = rubi_expand_integrand_product_sum(&logarithmic, &negative, x)
33753            .expect("negative log-quadratic remainder should split");
33754        let primitive = integrate_generated_payload(&expanded, x).unwrap_or_else(|| {
33755            panic!("expanded Bondarenko line 38 negative remainder should integrate: {expanded}")
33756        });
33757
33758        assert!(
33759            !rubi_contains_unintegrable(&primitive),
33760            "expanded negative remainder should not return unintegrable: {primitive}"
33761        );
33762    }
33763
33764    #[test]
33765    fn rubi_split_product_sum_base_matches_core_cases() {
33766        assert!(rubi_atom_base_q(&parse!("a")));
33767        assert!(rubi_atom_base_q(&parse!("a^3")));
33768        assert!(!rubi_atom_base_q(&parse!("(a + b)^3")));
33769        assert!(rubi_sum_base_q(&parse!("a + b")));
33770        assert!(rubi_sum_base_q(&parse!("(a + b)^3")));
33771        assert!(!rubi_sum_base_q(&parse!("(a + b)^2")));
33772        assert!(!rubi_sum_base_q(&parse!("a*b")));
33773        assert!(rubi_neg_sum_base_q(&parse!("(-2 + x)^3")));
33774        assert!(!rubi_neg_sum_base_q(&parse!("(2 + x)^3")));
33775        assert!(rubi_all_neg_term_q(&parse!("-2 - x")));
33776        assert!(rubi_some_neg_term_q(&parse!("2 - x")));
33777
33778        let product = parse!("c*(a + b)^3*d");
33779        let (matched, rest) = rubi_split_product(rubi_sum_base_q, &product)
33780            .expect("SplitProduct[SumBaseQ, product] should find the sum-base factor");
33781
33782        assert!(rubi_sum_base_q(&matched));
33783        assert!(
33784            (matched * rest - product).expand().is_zero(),
33785            "SplitProduct should return a factor/rest product"
33786        );
33787        assert!(rubi_atomq_split_product_sum_base(&parse!("a*b")));
33788        assert!(!rubi_atomq_split_product_sum_base(&parse!("a*(b + c)")));
33789    }
33790
33791    #[test]
33792    fn rubi_simp_handles_algebraic_h222_argument() {
33793        let x = symbol!("x");
33794        let a = Atom::var(symbol!("a"));
33795        let b = Atom::var(symbol!("b"));
33796        let c = Atom::var(symbol!("c"));
33797        let d = Atom::var(symbol!("d"));
33798        let det = &b * &c - &a * &d;
33799        let argument = &b * &c / &det + &b * &d * Atom::var(x) / &det;
33800        let simplified = rubi_simp(&argument, x);
33801        let expected = &b * (&c + &d * Atom::var(x)) / det;
33802
33803        assert!(
33804            (simplified - expected).together().is_zero(),
33805            "Simp should preserve Rubi H.2.2.2 affine argument"
33806        );
33807    }
33808
33809    #[test]
33810    fn core_rules_are_inline_rubi_rules() {
33811        assert_derivative_round_trip(parse!("x + x^2"));
33812        assert_derivative_round_trip(parse!("3*x^2"));
33813        assert_derivative_round_trip(parse!("3"));
33814        assert_derivative_round_trip(parse!("x"));
33815    }
33816
33817    #[test]
33818    fn inverse_function_free_q_rejects_rubi_hypergeometric_and_calculus_heads() {
33819        let x = symbol!("x");
33820        let variable_appell = rubi_appell_f1(
33821            Atom::num(1),
33822            Atom::num(2),
33823            Atom::num(3),
33824            Atom::num(4),
33825            Atom::var(x),
33826            Atom::num(0),
33827        );
33828        let constant_appell = rubi_appell_f1(
33829            Atom::num(1),
33830            Atom::num(2),
33831            Atom::num(3),
33832            Atom::num(4),
33833            Atom::num(0),
33834            Atom::num(0),
33835        );
33836
33837        assert!(!rubi_inverse_function_free_q(&variable_appell, x));
33838        assert!(rubi_inverse_function_free_q(&constant_appell, x));
33839        assert!(!rubi_inverse_function_free_q(&parse!("polylog(2,x)"), x));
33840        assert!(!rubi_inverse_function_free_q(
33841            &rubi_unintegrable(parse!("x^m"), x),
33842            x,
33843        ));
33844    }
33845
33846    #[test]
33847    fn unintegrable_detection_visits_nested_function_calls() {
33848        let x = symbol!("x");
33849        let deferred = rubi_unintegrable(parse!("x^m"), x);
33850
33851        assert!(rubi_contains_unintegrable(
33852            &(parse!("a+x") + deferred.pow(2))
33853        ));
33854        assert!(!rubi_contains_unintegrable(&parse!("a+x^2+f(x)")));
33855        assert!(!rubi_contains_unintegrable(&Atom::var(
33856            rubi_symbols().unintegrable
33857        )));
33858    }
33859
33860    #[test]
33861    fn inverse_sine_symbolic_power_follows_rubi_deferred_path() {
33862        let x = symbol!("x");
33863        let integrand = parse!("(d+e*x)^m*(a+b*asin(c*x))^2");
33864        let partial = integrate_deferred(integrand.as_view(), x)
33865            .expect("Rubi rule 5242 should return its partial integration-by-parts result");
33866
33867        assert!(
33868            rubi_contains_unintegrable(&partial),
33869            "Rubi leaves the recursive inverse-sine integral deferred: {partial}"
33870        );
33871    }
33872
33873    #[test]
33874    fn inverse_hyperbolic_sine_symbolic_power_follows_rubi_deferred_path() {
33875        let x = symbol!("x");
33876        let integrand = parse!("(d+e*x)^m*(a+b*asinh(c*x))^2");
33877        let partial = integrate_deferred(integrand.as_view(), x)
33878            .expect("Rubi's ArcSinh integration-by-parts row should return a partial result");
33879
33880        assert!(
33881            rubi_contains_unintegrable(&partial),
33882            "Rubi leaves the recursive inverse-hyperbolic-sine integral deferred: {partial}"
33883        );
33884    }
33885
33886    #[test]
33887    fn skips_opaque_rubi_function_roots() {
33888        let x = symbol!("x");
33889        let hypergeometric =
33890            rubi_hypergeometric2f1(Atom::num(1), Atom::num(2), Atom::num(3), Atom::var(x));
33891        let appell = rubi_appell_f1(
33892            Atom::num(1),
33893            Atom::num(2),
33894            Atom::num(3),
33895            Atom::num(4),
33896            Atom::var(x),
33897            Atom::var(symbol!("y")),
33898        );
33899
33900        assert!(integrate(&hypergeometric, x).is_err());
33901        assert!(integrate(&appell, x).is_err());
33902    }
33903
33904    #[test]
33905    fn differentiates_opaque_hypergeometric2f1_argument() {
33906        let x = symbol!("x");
33907        let expr = rubi_hypergeometric2f1(Atom::num(1), Atom::num(2), Atom::num(3), Atom::var(x));
33908        let expected = Atom::num(2) / Atom::num(3)
33909            * rubi_hypergeometric2f1(Atom::num(2), Atom::num(3), Atom::num(4), Atom::var(x));
33910
33911        assert_eq!(expr.derivative(x), expected);
33912    }
33913
33914    #[test]
33915    fn differentiates_opaque_exponential_integral_and_gamma_arguments() {
33916        let x = symbol!("x");
33917        let x_atom = Atom::var(x);
33918        let ei = rubi_exp_integral_ei(x_atom.to_owned());
33919        let li = rubi_log_integral(x_atom.to_owned());
33920        let product_log = rubi_product_log(x_atom.to_owned());
33921        let gamma = rubi_gamma(Atom::num(3), x_atom.to_owned());
33922        let unary_gamma = rubi_gamma_unary(x_atom.to_owned());
33923
33924        assert_eq!(ei.derivative(x), x_atom.exp() / &x_atom);
33925        assert_eq!(li.derivative(x), Atom::num(1) / x_atom.log());
33926        assert_eq!(
33927            rubi_d(&product_log, x),
33928            product_log.to_owned() / (x_atom.to_owned() * (Atom::num(1) + product_log))
33929        );
33930        assert_eq!(
33931            gamma.derivative(x),
33932            -x_atom.pow(2) * (-x_atom.to_owned()).exp()
33933        );
33934        assert_eq!(
33935            unary_gamma.derivative(x),
33936            rubi_gamma_unary(x_atom.to_owned()) * x_atom.to_owned().polygamma(Atom::num(0))
33937        );
33938        assert_eq!(
33939            rubi_log_gamma(x_atom.to_owned()).derivative(x),
33940            x_atom.polygamma(Atom::num(0))
33941        );
33942    }
33943
33944    #[test]
33945    fn normalizes_unit_order_incomplete_gamma_like_mathematica() {
33946        let z = parse!("a*x");
33947        assert_eq!(rubi_gamma(Atom::num(1), z.to_owned()), (-z).exp());
33948    }
33949
33950    #[test]
33951    fn integrates_unit_order_incomplete_gamma_after_builtin_normalization() {
33952        let x = symbol!("x");
33953        let integrand = rubi_gamma(Atom::num(1), parse!("a*x")) / Atom::var(x);
33954        let primitive = integrate(&integrand, x)
33955            .expect("Gamma[1,a*x]/x should normalize before Rubi rule matching");
33956        assert_eq!(primitive, rubi_exp_integral_ei(parse!("-a*x")));
33957    }
33958
33959    #[test]
33960    fn uses_builtin_imaginary_unit_in_error_function_rules() {
33961        let x = symbol!("x");
33962        let phase = parse!("c") - Atom::i() * parse!("b^2*x^2");
33963        let integrand = phase.sin() * rubi_erfc(parse!("b*x"));
33964        let _primitive = integrate(&integrand, x)
33965            .expect("the Erfc complex-phase rule should reach its downstream Rubi rows");
33966    }
33967
33968    #[test]
33969    fn differentiates_opaque_appell_f1_arguments() {
33970        let x = symbol!("x");
33971        let y = symbol!("y");
33972        let expr = rubi_appell_f1(
33973            Atom::num(1),
33974            Atom::num(2),
33975            Atom::num(3),
33976            Atom::num(4),
33977            Atom::var(x),
33978            Atom::var(y),
33979        );
33980        let expected_x = Atom::num(1) / Atom::num(2)
33981            * rubi_appell_f1(
33982                Atom::num(2),
33983                Atom::num(3),
33984                Atom::num(3),
33985                Atom::num(5),
33986                Atom::var(x),
33987                Atom::var(y),
33988            );
33989        let expected_y = Atom::num(3) / Atom::num(4)
33990            * rubi_appell_f1(
33991                Atom::num(2),
33992                Atom::num(2),
33993                Atom::num(4),
33994                Atom::num(5),
33995                Atom::var(x),
33996                Atom::var(y),
33997            );
33998
33999        assert_eq!(expr.derivative(x), expected_x);
34000        assert_eq!(expr.derivative(y), expected_y);
34001    }
34002
34003    #[test]
34004    fn differentiates_opaque_elliptic_e_amplitude() {
34005        let x = symbol!("x");
34006        let m = Atom::var(symbol!("m"));
34007        let expr = rubi_elliptic_e(Atom::var(x), m.to_owned());
34008        let expected = (Atom::num(1) - m * Atom::var(x).sin().pow(2)).sqrt();
34009
34010        assert_eq!(expr.derivative(x), expected);
34011    }
34012
34013    #[test]
34014    fn differentiates_opaque_elliptic_f_amplitude() {
34015        let x = symbol!("x");
34016        let m = Atom::var(symbol!("m"));
34017        let expr = rubi_elliptic_f(Atom::var(x), m.to_owned());
34018        let expected = Atom::num(1) / (Atom::num(1) - m * Atom::var(x).sin().pow(2)).sqrt();
34019
34020        assert_eq!(expr.derivative(x), expected);
34021    }
34022
34023    #[test]
34024    fn differentiates_opaque_elliptic_pi_amplitude() {
34025        let x = symbol!("x");
34026        let n = Atom::var(symbol!("n"));
34027        let m = Atom::var(symbol!("m"));
34028        let expr = rubi_elliptic_pi(n.to_owned(), Atom::var(x), m.to_owned());
34029        let expected = Atom::num(1)
34030            / ((Atom::num(1) - n * Atom::var(x).sin().pow(2))
34031                * (Atom::num(1) - m * Atom::var(x).sin().pow(2)).sqrt());
34032
34033        assert_eq!(expr.derivative(x), expected);
34034    }
34035
34036    #[test]
34037    fn normalizes_opaque_hypergeometric2f1_special_values() {
34038        let x = symbol!("x");
34039        let z = Atom::var(x);
34040
34041        assert_eq!(
34042            rubi_hypergeometric2f1(Atom::num(0), Atom::num(2), Atom::num(3), z.to_owned()),
34043            Atom::num(1)
34044        );
34045        assert_eq!(
34046            rubi_hypergeometric2f1(Atom::num(2), Atom::num(3), Atom::num(3), z.to_owned()),
34047            (Atom::num(1) - z.to_owned()).pow(-Atom::num(2))
34048        );
34049        assert_eq!(
34050            rubi_hypergeometric2f1(
34051                Atom::num(1),
34052                Atom::num(1) / Atom::num(2),
34053                Atom::num(3) / Atom::num(2),
34054                z.to_owned()
34055            ),
34056            z.sqrt().atanh() / z.sqrt()
34057        );
34058        let terminating = rubi_hypergeometric2f1(
34059            -Atom::num(2),
34060            Atom::num(3) / Atom::num(2),
34061            Atom::num(5) / Atom::num(2),
34062            z.to_owned(),
34063        );
34064        let expected = Atom::num(1) - Atom::num(6) * &z / Atom::num(5)
34065            + Atom::num(3) * z.pow(2) / Atom::num(7);
34066        assert!((terminating - expected).together().is_zero());
34067    }
34068
34069    #[test]
34070    fn integerq_normalizes_symbolic_linear_exponent_sum() {
34071        let exponent = parse!("1/2*(1-n)+1/2*(-3+n)");
34072
34073        assert!(
34074            integer_q(&exponent),
34075            "IntegerQ should recognize normalized exponent {exponent} as integer"
34076        );
34077    }
34078
34079    #[test]
34080    fn integerq_returns_false_for_inexact_float_without_panicking() {
34081        let exponent = parse!("-0.1");
34082
34083        assert!(!integer_q(&exponent));
34084    }
34085
34086    #[test]
34087    fn rationalq_returns_false_for_inexact_float_without_panicking() {
34088        assert!(!rational_q(&parse!("-0.1")));
34089        assert!(rational_q(&parse!("-1/10")));
34090    }
34091
34092    #[test]
34093    fn integrates_numeric_exponential_linear_factor_without_integerq_panic() {
34094        let x = symbol!("x");
34095        let integrand = parse!("x*exp((-0.1)*x)");
34096        let primitive =
34097            integrate(&integrand, x).unwrap_or_else(|_| panic!("rule should apply to {integrand}"));
34098
34099        assert!(
34100            !rubi_contains_unintegrable(&primitive),
34101            "primitive should not be unintegrable: {primitive}"
34102        );
34103    }
34104
34105    #[test]
34106    fn integrates_exponential_quadratic_denominator_by_parts_like_rubi() {
34107        let primitive = integrate(&parse!("f^x*x/(a+b*f^(2*x))^2"), symbol!("x"))
34108            .expect("Rubi DownValues 2675, 215, and 218 should integrate the payload");
34109        assert!(!rubi_contains_unintegrable(&primitive));
34110        assert!(primitive.to_string().contains("polylog"));
34111    }
34112
34113    #[test]
34114    fn exponential_recurrence_star_terms_cancel_like_rubi() {
34115        let x = symbol!("x");
34116        let integrand = parse!("x/sqrt(exp(x)+x)+exp(x)*x/sqrt(exp(x)+x)+2*sqrt(exp(x)+x)");
34117        let primitive =
34118            integrate(&integrand, x).expect("Rubi DownValues 2009, 2692, and 2703 should cancel");
34119        let expected = parse!("2*x*sqrt(exp(x)+x)");
34120
34121        assert!(
34122            rubi_equivalent_q(&primitive, &expected),
34123            "expected {expected}, got {primitive}"
34124        );
34125    }
34126
34127    #[test]
34128    fn borrowed_integer_predicate_handles_numeric_and_symbolic_views() {
34129        for (input, expected) in [
34130            ("3", true),
34131            ("-5/2", false),
34132            ("-0.1", false),
34133            ("y", false),
34134            ("f(y)", false),
34135            ("(x+1)^2-x^2-2*x", true),
34136        ] {
34137            let expression =
34138                Atom::parse(input, "rubi_integer_guard_test", Default::default()).unwrap();
34139            assert_eq!(integer_q_view(expression.as_view()), expected, "{input}");
34140        }
34141    }
34142
34143    #[test]
34144    fn borrowed_integer_conditions_preserve_capture_and_negation_contract() {
34145        use symbolica::atom::SliceType;
34146        use symbolica::id::{Match, MatchStack};
34147
34148        let x = symbol!("x");
34149        let symbols = rubi_symbols();
34150        let x_atom = Atom::var(x);
34151        let coefficient = parse!("y");
34152        let unused = Atom::num(1);
34153        let mut positive = rubi_rule!(
34154            source: "Int[a+n*x+b*x^2,x_Symbol]",
34155            desc: "Borrowed integer guard contract.",
34156            refs: [],
34157            pattern: symbols.a__ + symbols.n_ * symbols.x_ + symbols.b__ * symbols.x_.pow(2),
34158            with: [a__, n_, x_, b__],
34159            when: { freeq!(a__, x_) && integerq!(n_) },
34160            rhs: { Atom::Zero },
34161        );
34162        let negative = rubi_rule!(
34163            source: "Int[a+n*x+b*x^2,x_Symbol]",
34164            desc: "Borrowed noninteger guard contract.",
34165            refs: [],
34166            pattern: symbols.a__ + symbols.n_ * symbols.x_ + symbols.b__ * symbols.x_.pow(2),
34167            with: [a__, n_, x_, b__],
34168            when: { freeq!([a__], x_) && !integerq!(n_) },
34169            rhs: { Atom::Zero },
34170        );
34171        for (integer, expected) in [
34172            (Atom::num(3), true),
34173            (parse!("1/2"), false),
34174            (parse!("-0.1"), false),
34175            (parse!("z"), false),
34176            (parse!("(x+1)^2-x^2-2*x"), true),
34177        ] {
34178            let matches = MatchStack::from(vec![
34179                (symbols.a__, Match::Single(coefficient.as_view())),
34180                (symbols.n_, Match::Single(integer.as_view())),
34181                (symbols.x_, Match::Single(x_atom.as_view())),
34182                (symbols.b__, Match::Single(unused.as_view())),
34183            ]);
34184            assert_eq!(
34185                (positive.condition)(&matches, x, &positive) == ConditionResult::True,
34186                expected,
34187                "{integer}"
34188            );
34189            assert_eq!(
34190                (negative.condition)(&matches, x, &negative) == ConditionResult::True,
34191                !expected,
34192                "{integer}"
34193            );
34194            for omitted in [symbols.a__, symbols.n_, symbols.x_, symbols.b__] {
34195                let incomplete = MatchStack::from(
34196                    matches
34197                        .get_matches()
34198                        .iter()
34199                        .filter(|(wildcard, _)| *wildcard != omitted)
34200                        .cloned()
34201                        .collect::<Vec<_>>(),
34202                );
34203                assert_eq!(
34204                    (positive.condition)(&incomplete, x, &positive),
34205                    ConditionResult::False
34206                );
34207                assert_eq!(
34208                    (negative.condition)(&incomplete, x, &negative),
34209                    ConditionResult::False
34210                );
34211            }
34212        }
34213        let coefficient_sum = parse!("1+y");
34214        let expanded_integer = parse!("(z+1)^2-z^2-2*z");
34215        let multiple = MatchStack::from(vec![
34216            (
34217                symbols.a__,
34218                Match::Multiple(
34219                    SliceType::Add,
34220                    rubi_child_views(coefficient_sum.as_view()).collect(),
34221                ),
34222            ),
34223            (
34224                symbols.n_,
34225                Match::Multiple(
34226                    SliceType::Add,
34227                    rubi_child_views(expanded_integer.as_view()).collect(),
34228                ),
34229            ),
34230            (symbols.x_, Match::Single(x_atom.as_view())),
34231            (symbols.b__, Match::Single(unused.as_view())),
34232        ]);
34233        assert_eq!(
34234            (positive.condition)(&multiple, x, &positive),
34235            ConditionResult::True
34236        );
34237        assert_eq!(
34238            (negative.condition)(&multiple, x, &negative),
34239            ConditionResult::False
34240        );
34241        let dependent = MatchStack::from(vec![
34242            (symbols.a__, Match::Single(x_atom.as_view())),
34243            (symbols.n_, Match::Single(coefficient.as_view())),
34244            (symbols.x_, Match::Single(x_atom.as_view())),
34245            (symbols.b__, Match::Single(unused.as_view())),
34246        ]);
34247        assert_eq!(
34248            (positive.condition)(&dependent, x, &positive),
34249            ConditionResult::False
34250        );
34251        assert_eq!(
34252            (negative.condition)(&dependent, x, &negative),
34253            ConditionResult::False
34254        );
34255        positive.required.pop();
34256        assert_eq!(
34257            (positive.condition)(&multiple, x, &positive),
34258            ConditionResult::False
34259        );
34260    }
34261
34262    #[cfg(feature = "bake-integration-variable")]
34263    #[test]
34264    fn borrowed_integer_condition_uses_only_its_own_baked_variable_context() {
34265        use symbolica::id::{Match, MatchStack};
34266
34267        let x = symbol!("x");
34268        let symbols = rubi_symbols();
34269        let coefficient = parse!("y");
34270        let integer = Atom::num(3);
34271        let row = Box::leak(Box::new(rubi_rule!(
34272            source: "Int[a+n*x,x_Symbol]",
34273            desc: "Baked variable guard contract.",
34274            refs: [],
34275            pattern: symbols.a__ + symbols.n_ * symbols.x_,
34276            with: [a__, n_, x_],
34277            when: { freeq!([a__], x_) && integerq!(n_) },
34278            rhs: { Atom::Zero },
34279        )));
34280        let other_row = Box::leak(Box::new(rubi_rule!(
34281            source: "Int[a+n*x,x_Symbol]",
34282            desc: "Distinct baked variable context.",
34283            refs: [],
34284            pattern: symbols.a__ + symbols.n_ * symbols.x_,
34285            with: [a__, n_, x_],
34286            when: { true },
34287            rhs: { Atom::Zero },
34288        )));
34289        let matches = MatchStack::from(vec![
34290            (symbols.a__, Match::Single(coefficient.as_view())),
34291            (symbols.n_, Match::Single(integer.as_view())),
34292        ]);
34293        assert_eq!((row.condition)(&matches, x, row), ConditionResult::False);
34294        {
34295            let _context = RubiReplacementContext::push(other_row, x);
34296            assert_eq!((row.condition)(&matches, x, row), ConditionResult::False);
34297        }
34298        {
34299            let _context = RubiReplacementContext::push(row, x);
34300            assert_eq!((row.condition)(&matches, x, row), ConditionResult::True);
34301            let incomplete = MatchStack::from(vec![(symbols.n_, Match::Single(integer.as_view()))]);
34302            assert_eq!((row.condition)(&incomplete, x, row), ConditionResult::False);
34303        }
34304        assert_eq!((row.condition)(&matches, x, row), ConditionResult::False);
34305    }
34306
34307    #[test]
34308    fn required_wildcard_captures_preserve_order_and_reject_incomplete_rows() {
34309        use symbolica::atom::SliceType;
34310        use symbolica::id::{Match, MatchStack};
34311
34312        let symbols = rubi_symbols();
34313        let row = rubi_rule!(
34314            source: "Int[a+b*x,x_Symbol]",
34315            desc: "Capture extraction contract.",
34316            refs: [],
34317            pattern: symbols.a__ + symbols.b__ * symbols.x_,
34318            with: [b__, a__, x_],
34319            when: { true },
34320            rhs: { Atom::Zero },
34321        );
34322        let a = parse!("2+y");
34323        let coefficient = Atom::num(3);
34324        let factor = parse!("z");
34325        let x = parse!("x");
34326        // Stack insertion order differs from the row's required capture order.
34327        // The product capture also exercises conversion of a multi-atom match.
34328        let matches = MatchStack::from(vec![
34329            (symbols.a__, Match::Single(a.as_view())),
34330            (symbols.x_, Match::Single(x.as_view())),
34331            (
34332                symbols.b__,
34333                Match::Multiple(
34334                    SliceType::Mul,
34335                    vec![coefficient.as_view(), factor.as_view()],
34336                ),
34337            ),
34338        ]);
34339        assert_eq!(
34340            required_wildcard_atoms_for_rule::<3>(&matches, &row),
34341            Some([parse!("3*z"), a.to_owned(), x.to_owned()])
34342        );
34343        assert!(required_wildcard_atoms_for_rule::<2>(&matches, &row).is_none());
34344        assert!(required_wildcard_atoms_for_rule::<4>(&matches, &row).is_none());
34345
34346        let incomplete = MatchStack::from(vec![(
34347            symbols.b__,
34348            Match::Multiple(
34349                SliceType::Mul,
34350                vec![coefficient.as_view(), factor.as_view()],
34351            ),
34352        )]);
34353        // A heap-owning capture is initialized before the missing capture fails.
34354        assert!(required_wildcard_atoms_for_rule::<3>(&incomplete, &row).is_none());
34355        assert!(required_wildcard_atoms_for_rule::<3>(&MatchStack::new(), &row).is_none());
34356        assert_eq!(wildcard_atoms_for_rule(&matches, [], &row), Some([]));
34357    }
34358
34359    #[test]
34360    fn rubi_rule_marks_optional_wildcards_on_pattern() {
34361        let symbols = rubi_symbols();
34362        let x = symbol!("x");
34363        let row = Box::leak(Box::new(rubi_rule!(
34364            source: "Int[a_.+x_,x_Symbol]",
34365            desc: "Apply the matching Rubi transformation.",
34366            refs: [],
34367            pattern: symbols.a__ + symbols.x_,
34368            with: [a__, x_],
34369            optional: [a__],
34370            x_free: [a__],
34371            when: {
34372                freeq!(a__, x_)
34373            },
34374            rhs: {
34375                a__ * x_ + x_.pow(2) / Atom::num(2)
34376            },
34377        )));
34378        let split_row = Box::leak(Box::new(rubi_rule!(
34379            source: "Int[a_.+x_,x_Symbol]",
34380            desc: "Apply the matching Rubi transformation.",
34381            refs: [],
34382            pattern: symbols.a__ + symbols.v_,
34383            with: [a__, v_, x_],
34384            optional: [a__],
34385            x_free: [a__],
34386            when: {
34387                v_ == x_ && freeq!(a__, x_)
34388            },
34389            rhs: {
34390                a__ * x_ + x_.pow(2) / Atom::num(2)
34391            },
34392        )));
34393
34394        assert_eq!(row.required, vec![symbols.a__, symbols.x_]);
34395        assert!(row.early_x_dependent.is_empty());
34396        assert_eq!(row.early_x_free, vec![symbols.a__]);
34397        assert_eq!(matcher_rule(parse!("y").as_view(), x, row), None);
34398        for integrand in [parse!("x"), parse!("2+x"), parse!("y")] {
34399            assert_eq!(
34400                matcher_rule(integrand.as_view(), x, row),
34401                matcher_rule(integrand.as_view(), x, split_row),
34402                "reserved x_ and guarded v_ must be semantically equivalent for {integrand}"
34403            );
34404        }
34405        assert_eq!(
34406            matcher_rule(parse!("x").as_view(), x, row).map(|expr| expr.expand()),
34407            Some(parse!("x^2/2"))
34408        );
34409        assert_eq!(
34410            matcher_rule(parse!("2+x").as_view(), x, row).map(|expr| expr.expand()),
34411            Some(parse!("2*x+x^2/2"))
34412        );
34413    }
34414
34415    #[test]
34416    fn pattern_shape_bounds_preserve_optional_power_matches() {
34417        let exponent = symbol!("bound_exponent");
34418        let affine = parse!("bound_a+bound_b*bound_x");
34419        let powered = affine.pow(Atom::var(exponent));
34420
34421        assert!(rubi_pattern_can_match_top_level_sum(&powered, &[exponent]));
34422        assert!(!rubi_pattern_can_match_top_level_sum(&powered, &[]));
34423        assert_eq!(
34424            rubi_pattern_max_top_level_term_count(&powered, &[exponent]),
34425            Some(2)
34426        );
34427
34428        let bounded_product = powered * Atom::var(symbol!("bound_v"));
34429        assert_eq!(
34430            rubi_pattern_max_top_level_factor_count(&bounded_product),
34431            Some(2)
34432        );
34433    }
34434
34435    #[test]
34436    fn affine_power_bounds_detect_only_source_compatible_positive_powers() {
34437        let x = symbol!("x");
34438        assert!(
34439            RubiCandidateBounds::new(parse!("(a+b*x)^3/(c+d*x)").as_view(), x)
34440                .has_positive_integer_affine_power
34441        );
34442        assert!(
34443            !RubiCandidateBounds::new(parse!("(a+b*x)^m/(c+d*x)").as_view(), x)
34444                .has_positive_integer_affine_power
34445        );
34446        assert!(
34447            RubiCandidateBounds::new(parse!("(a+b*x)^(-3/2)*(1+x^2)").as_view(), x)
34448                .has_rational_noninteger_affine_power_below_negative_one
34449        );
34450        assert!(
34451            !RubiCandidateBounds::new(parse!("(a+b*x)^m/(c+d*x)").as_view(), x)
34452                .has_rational_noninteger_affine_power_below_negative_one
34453        );
34454        assert!(rubi_has_polynomial_complement_of_affine_power(
34455            parse!("(a+b*x)^m*(1+x+x^2)").as_view(),
34456            x
34457        ));
34458        assert!(!rubi_has_polynomial_complement_of_affine_power(
34459            parse!("(a+b*x)^m*(1+x+x^2)/(c+d*x)").as_view(),
34460            x
34461        ));
34462    }
34463
34464    #[test]
34465    fn rubi_rule_zero_bound_rejects_an_impossible_partial_match() {
34466        let symbols = rubi_symbols();
34467        let x = symbol!("x");
34468        let row = Box::leak(Box::new(rubi_rule!(
34469            order: 0,
34470            source: "Int[a_.+x_,x_Symbol] /; EqQ[a,0]",
34471            desc: "Apply the matching Rubi transformation.",
34472            refs: [],
34473            pattern: symbols.a__ + symbols.x_,
34474            with: [a__, x_],
34475            optional: [a__],
34476            x_free: [a__],
34477            zero: [a__],
34478            when: { freeq!(a__, x_) && eqq!(a__, 0) },
34479            rhs: { x_.pow(2) / Atom::num(2) },
34480        )));
34481
34482        assert_eq!(row.early_zero, vec![symbols.a__]);
34483        assert!(matcher_rule(parse!("x").as_view(), x, row).is_some());
34484        assert_eq!(matcher_rule(parse!("2+x").as_view(), x, row), None);
34485    }
34486
34487    #[test]
34488    fn proportional_affine_prefilter_rejects_only_when_no_factor_pair_can_match() {
34489        let x = symbol!("x");
34490
34491        assert!(rubi_has_proportional_affine_factor_pair(
34492            parse!("q*(1+x)^m*(2+2*x)^n").as_view(),
34493            x,
34494        ));
34495        assert!(!rubi_has_proportional_affine_factor_pair(
34496            parse!("(a+b*x)^m*(c+d*x)^n*(e+f*x)^p").as_view(),
34497            x,
34498        ));
34499    }
34500
34501    #[test]
34502    fn proportional_common_expression_prefilter_handles_trig_binomials() {
34503        let x = symbol!("x");
34504
34505        assert!(rubi_has_proportional_common_expression_factor_pair(
34506            parse!("q*(1+2*sin(x))^m*(2+4*sin(x))^n").as_view(),
34507            x,
34508        ));
34509        assert!(!rubi_has_proportional_common_expression_factor_pair(
34510            parse!("(a+b*sin(x))^m*(c+d*sin(x))^n").as_view(),
34511            x,
34512        ));
34513        assert!(rubi_has_proportional_common_expression_factor_pair(
34514            parse!("(a+b*sin(x)+c*cos(x))^m*(d+e*sin(x))^n").as_view(),
34515            x,
34516        ));
34517    }
34518
34519    #[test]
34520    fn explicit_pattern_polynomial_degree_is_structural() {
34521        let x = symbol!("x");
34522
34523        assert_eq!(
34524            rubi_explicit_pattern_polynomial_degree(parse!("a+b*x").as_view(), x),
34525            Some(1)
34526        );
34527        assert_eq!(
34528            rubi_explicit_pattern_polynomial_degree(parse!("a+b*x+c*x^2").as_view(), x),
34529            Some(2)
34530        );
34531        assert_eq!(
34532            rubi_explicit_pattern_polynomial_degree(parse!("(a+b*x)^3").as_view(), x),
34533            Some(3)
34534        );
34535        assert_eq!(
34536            rubi_explicit_pattern_polynomial_degree(parse!("a+b*x^n").as_view(), x),
34537            None
34538        );
34539        assert_eq!(
34540            rubi_explicit_pattern_polynomial_degree(parse!("a+b*F^(c+d*x)").as_view(), x),
34541            None
34542        );
34543        assert_eq!(
34544            rubi_explicit_pattern_polynomial_degree(parse!("sin(x)").as_view(), x),
34545            None
34546        );
34547        assert_eq!(
34548            rubi_explicit_pattern_polynomial_degree(parse!("f(a)").as_view(), x),
34549            Some(0)
34550        );
34551    }
34552
34553    #[test]
34554    fn explicit_pattern_factor_bounds_separate_two_and_four_factor_rows() {
34555        let _ = symbol!("x");
34556        let two_factor = rubi_rules()
34557            .iter()
34558            .find(|rule| rule.downvalue_order == Some(48))
34559            .expect("Rubi two-affine-factor DownValue 48 should be registered");
34560        let four_factor = rubi_rules()
34561            .iter()
34562            .find(|rule| rule.downvalue_order == Some(172))
34563            .expect("Rubi four-factor DownValue 172 should be registered");
34564
34565        let two_factor_bound = two_factor
34566            .explicit_x_factor_bound
34567            .as_ref()
34568            .expect("two-factor row should have a structural bound");
34569        let four_factor_bound = four_factor
34570            .explicit_x_factor_bound
34571            .as_ref()
34572            .expect("four-factor row should have a structural bound");
34573        assert_eq!(two_factor_bound.factor_count, 2);
34574        assert_eq!(four_factor_bound.factor_count, 4);
34575        assert_eq!(four_factor_bound.affine_base_count, 4);
34576        assert_eq!(
34577            rubi_top_level_x_factor_count(
34578                parse!("(a+b*x)^m*(c+d*x)^n*(e+f*x)^p*(g+h*x)").as_view(),
34579                symbol!("x"),
34580            ),
34581            4,
34582        );
34583    }
34584
34585    #[test]
34586    fn broad_two_affine_dispatcher_rules_are_absent() {
34587        let broad_ids = [
34588            "Rubi 1.1.1.2 two affine powers",
34589            "Rubi 1.1.1.2 reversed two affine powers",
34590        ];
34591        for id in broad_ids {
34592            assert!(
34593                rubi_rules().iter().all(|rule| rule.id != id),
34594                "{id} should stay replaced by row-shaped rules"
34595            );
34596        }
34597    }
34598
34599    #[test]
34600    fn row_shaped_rules_do_not_require_zero_width_sequence_factors() {
34601        for rule in rubi_rules()
34602            .iter()
34603            .filter(|rule| rule.source_pattern.is_some() && !rule.id.starts_with("Core."))
34604        {
34605            assert!(
34606                !rule
34607                    .required
34608                    .iter()
34609                    .any(|wildcard| wildcard.to_string().ends_with("___")),
34610                "{} should not encode required Rubi factors with zero-width sequence wildcards",
34611                rule.id
34612            );
34613        }
34614    }
34615
34616    #[test]
34617    fn detects_functions_of_linear_exponentials() {
34618        let x = symbol!("x");
34619
34620        assert!(rubi_function_of_exponential_q(
34621            parse!("1/(1 + exp(x) + exp(2*x))").as_view(),
34622            x
34623        ));
34624        assert!(rubi_function_of_exponential_q(
34625            parse!("sqrt(1+exp(-x))/sinh(x)").as_view(),
34626            x
34627        ));
34628        assert!(!rubi_function_of_exponential_q(
34629            parse!("x + exp(x)").as_view(),
34630            x
34631        ));
34632        assert!(!rubi_function_of_exponential_q(
34633            parse!("exp(x^2)").as_view(),
34634            x
34635        ));
34636        assert!(!rubi_function_of_exponential_q(
34637            parse!("csch(x)").as_view(),
34638            x
34639        ));
34640        assert!(rubi_function_of_exponential_q(
34641            parse!("sech(exp(x))").as_view(),
34642            x
34643        ));
34644
34645        let exponential_function =
34646            rubi_function_of_exponential(parse!("1/(b*f^(-x)+a*f^x)^3").as_view(), x)
34647                .expect("opposite same-base exponentials should share a basis");
34648        assert!(eqq!(exponential_function.exponential, parse!("f^x")));
34649        assert!(
34650            (exponential_function.function - parse!("x^3/(b+a*x^2)^3"))
34651                .together()
34652                .is_zero()
34653        );
34654
34655        let hyperbolic_exponential_function =
34656            rubi_function_of_exponential(parse!("sqrt(1+exp(-x))/sinh(x)").as_view(), x)
34657                .expect("Bondarenko line 29 should follow Rubi FunctionOfExponentialQ");
34658        assert!(
34659            eqq!(
34660                hyperbolic_exponential_function.exponential,
34661                Atom::var(Symbol::E).pow(Atom::var(x))
34662            ),
34663            "unexpected exponential basis: {}",
34664            hyperbolic_exponential_function.exponential
34665        );
34666        assert!(
34667            (hyperbolic_exponential_function.function - parse!("2*sqrt(1+1/x)*x/(-1+x^2)"))
34668                .together()
34669                .is_zero()
34670        );
34671
34672        let explicit_exponential_function =
34673            rubi_function_of_exponential(parse!("sqrt(1+exp(-x))/(-exp(-x)+exp(x))").as_view(), x)
34674                .expect("Bondarenko line 28 should follow Rubi FunctionOfExponentialQ");
34675        assert!(
34676            eqq!(
34677                explicit_exponential_function.exponential,
34678                Atom::var(Symbol::E).pow(Atom::var(x))
34679            ),
34680            "unexpected exponential basis: {}",
34681            explicit_exponential_function.exponential
34682        );
34683        assert_eq!(
34684            explicit_exponential_function.function,
34685            parse!("x*sqrt(1+1/x)/(-1+x^2)"),
34686            "Bondarenko line 28 FunctionOfExponentialFunction should follow Rubi's SimplifyIntegrand trace"
34687        );
34688
34689        let tanh_exponential_function =
34690            rubi_function_of_exponential(parse!("tanh(x)/sqrt(exp(x)+exp(2*x))").as_view(), x)
34691                .expect("Bondarenko line 33 should follow Rubi FunctionOfExponentialQ");
34692        assert!(
34693            eqq!(
34694                tanh_exponential_function.exponential,
34695                Atom::var(Symbol::E).pow(Atom::var(x))
34696            ),
34697            "unexpected exponential basis: {}",
34698            tanh_exponential_function.exponential
34699        );
34700        assert!(
34701            (tanh_exponential_function.function.to_owned()
34702                - parse!("(-1+x^2)/((1+x^2)*sqrt(x+x^2))"))
34703            .together()
34704            .is_zero(),
34705            "unexpected FunctionOfExponentialFunction: {}",
34706            tanh_exponential_function.function
34707        );
34708
34709        let nested_exponential_function =
34710            rubi_function_of_exponential(parse!("exp(exp(x)+x)").as_view(), x)
34711                .expect("nested exponential should follow Rubi FunctionOfExponentialQ");
34712        assert!(
34713            eqq!(
34714                nested_exponential_function.exponential,
34715                Atom::var(Symbol::E).pow(Atom::var(x))
34716            ),
34717            "unexpected exponential basis: {}",
34718            nested_exponential_function.exponential
34719        );
34720        assert!(
34721            (nested_exponential_function.function.to_owned() - parse!("x*exp(x)"))
34722                .together()
34723                .is_zero(),
34724            "unexpected nested FunctionOfExponentialFunction: {}",
34725            nested_exponential_function.function
34726        );
34727
34728        let logarithmic_exponential_function =
34729            rubi_function_of_exponential(parse!("log(1+exp(x))/(1+exp(2*x))").as_view(), x)
34730                .expect("Bondarenko line 36 should follow Rubi FunctionOfExponentialQ");
34731        assert!(
34732            eqq!(
34733                logarithmic_exponential_function.exponential,
34734                Atom::var(Symbol::E).pow(Atom::var(x))
34735            ),
34736            "unexpected exponential basis: {}",
34737            logarithmic_exponential_function.exponential
34738        );
34739        assert!(
34740            (logarithmic_exponential_function.function.to_owned() - parse!("log(1+x)/(1+x^2)"))
34741                .together()
34742                .is_zero(),
34743            "unexpected logarithmic FunctionOfExponentialFunction: {}",
34744            logarithmic_exponential_function.function
34745        );
34746
34747        let shifted_exponential_function =
34748            rubi_function_of_exponential(parse!("1/(a+b*exp(c+d*x))").as_view(), x)
34749                .expect("Rubi FunctionOfExponentialQ accepts shifted linear exponents");
34750        assert!(
34751            !rubi_function_of_exponential_rule_exclusion_q(
34752                parse!("1/(a+b*exp(c+d*x))").as_view(),
34753                x
34754            ),
34755            "Rubi 2.3.95 excludes explicit scaled powers, not shifted exponential sums"
34756        );
34757        assert!(
34758            eqq!(
34759                shifted_exponential_function.exponential,
34760                parse!("exp(c+d*x)")
34761            ),
34762            "unexpected shifted exponential basis: {}",
34763            shifted_exponential_function.exponential
34764        );
34765        assert_eq!(
34766            shifted_exponential_function.function,
34767            parse!("1/(a+b*x)"),
34768            "FunctionOfExponentialFunction should replace exp(c+d*x) by x"
34769        );
34770
34771        let cubed_denominator_function =
34772            rubi_function_of_exponential(parse!("1/(a+b*(F^(g*(e+f*x)))^n)^3").as_view(), x)
34773                .expect("symbolic exponential powers should follow Rubi FunctionOfExponentialQ");
34774        assert!(
34775            eqq!(
34776                cubed_denominator_function.exponential,
34777                parse!("F^(g*(e+f*x))")
34778            ),
34779            "unexpected symbolic exponential basis: {}",
34780            cubed_denominator_function.exponential
34781        );
34782        assert_eq!(
34783            cubed_denominator_function.function,
34784            parse!("1/(a+b*x^n)^3"),
34785            "FunctionOfExponentialFunction should preserve the Rubi binomial payload"
34786        );
34787
34788        let nested_hyperbolic_exponential_function =
34789            rubi_function_of_exponential(parse!("exp(x)*sech(exp(x))").as_view(), x)
34790                .expect("Stewart line 370 should follow Rubi FunctionOfExponentialQ");
34791        assert!(
34792            eqq!(
34793                nested_hyperbolic_exponential_function.exponential,
34794                Atom::var(Symbol::E).pow(Atom::var(x))
34795            ),
34796            "unexpected exponential basis: {}",
34797            nested_hyperbolic_exponential_function.exponential
34798        );
34799        assert!(
34800            (nested_hyperbolic_exponential_function.function.to_owned() - parse!("x*sech(x)"))
34801                .together()
34802                .is_zero(),
34803            "unexpected nested hyperbolic FunctionOfExponentialFunction: {}",
34804            nested_hyperbolic_exponential_function.function
34805        );
34806    }
34807
34808    #[test]
34809    fn integrates_stewart_370_nested_hyperbolic_exponential_like_rubi() {
34810        assert_derivative_round_trip(parse!("exp(x)*sech(exp(x))"));
34811    }
34812
34813    #[test]
34814    fn downvalue_3113_matches_unified_inert_sine_power() {
34815        let x = symbol!("x");
34816        let integrand = i_sin(parse!("x+1/2*pi")).pow(5);
34817        let rule = rubi_rules()
34818            .iter()
34819            .find(|rule| rule.downvalue_order == Some(3113))
34820            .expect("Rubi DownValue 3113 should be registered");
34821
34822        assert!(
34823            matcher_rule_for_test(&integrand, x, rule).is_some(),
34824            "Rubi DownValue 3113 should match {integrand}; required heads: {:?}; candidate heads: {:?}",
34825            rule.required_function_heads,
34826            rubi_function_heads(integrand.as_view())
34827        );
34828    }
34829
34830    #[test]
34831    fn function_of_trig_of_linear_distinguishes_active_and_inert_heads() {
34832        let x = symbol!("x");
34833        assert!(rubi_function_of_trig_of_linear_q(&parse!("sin(x)^5"), x));
34834        assert!(!rubi_function_of_trig_of_linear_q(
34835            &i_sin(Atom::var(x)).pow(5),
34836            x
34837        ));
34838    }
34839
34840    #[test]
34841    fn integrates_timofeev_111_cosine_power_like_rubi() {
34842        assert_derivative_round_trip(parse!("cos(x)^5"));
34843    }
34844
34845    #[test]
34846    fn pseudo_binomial_parts_rejects_pure_affine_power_like_rubi() {
34847        let x = symbol!("x");
34848        assert!(pseudo_binomial_parts(&parse!("-3+x^27"), x).is_some());
34849        assert!(pseudo_binomial_parts(&parse!("(2+3*x)^25"), x).is_none());
34850    }
34851
34852    #[test]
34853    fn polynomial_eq_rejects_false_affine_power_identity() {
34854        let x = symbol!("x");
34855        let x_atom = Atom::var(x);
34856        let polynomial = parse!("-1/3+4*x^25");
34857        let affine_power =
34858            (rubi_rt(&parse!("-1/3"), 25) + rubi_rt(&Atom::num(4), 25) * x_atom).pow(25);
34859
34860        assert!(
34861            !rubi_polynomial_eq_q(&polynomial, &affine_power, x),
34862            "the affine power has nonzero intermediate polynomial coefficients"
34863        );
34864        assert!(rubi_polynomial_eq_q(
34865            &parse!("1+2*x+x^2"),
34866            &parse!("(1+x)^2"),
34867            x
34868        ));
34869    }
34870
34871    #[test]
34872    fn simplified_quotient_rejects_zero_denominator_without_constructing_infinity() {
34873        assert_eq!(rubi_simplified_quotient(&parse!("n"), &Atom::num(0)), None);
34874    }
34875
34876    #[test]
34877    fn trig_expand_normalizes_integer_multiples_of_arc_tangent() {
34878        let z = symbol!("z");
34879        let z_atom = Atom::var(z);
34880        let expression = Atom::num(2) * (Atom::num(2) * z_atom.atan()).sin()
34881            + (Atom::num(4) * z_atom.atan()).sin();
34882        let normalized = rubi_normalize_inverse_trig_trig(expression.as_view());
34883        let normalized = rubi_simplify(&normalized);
34884        let expected = Atom::num(8) * &z_atom / (Atom::num(1) + z_atom.pow(2)).pow(2);
34885
34886        assert!(
34887            rubi_algebraic_zero_q(&(normalized - expected)),
34888            "TrigExpand equivalent did not normalize the ArcTan multiples"
34889        );
34890    }
34891
34892    #[test]
34893    fn integrates_reciprocal_sine_sum_by_rubi_trig_expand_path() {
34894        assert_derivative_round_trip(parse!("1/(2*sin(x)+sin(2*x))"));
34895    }
34896
34897    #[test]
34898    fn integrates_fractional_binomial_product_without_false_perfect_power_match() {
34899        assert_derivative_round_trip(parse!("(-3*x^(3/5)+x^(3/2))^2*(-1/3*x^(2/3)+4*x^(3/2))"));
34900    }
34901
34902    #[test]
34903    fn integrates_bondarenko_29_function_of_exponential_hyperbolic_like_rubi() {
34904        let x = symbol!("x");
34905        let integrand = parse!("sqrt(1+exp(-x))/sinh(x)");
34906        let primitive =
34907            integrate(&integrand, x).expect("Bondarenko line 29 should follow Rubi 2.3.95");
34908        let expected = parse!("-2*sqrt(2)*atanh(sqrt(1+exp(-x))/sqrt(2))");
34909        let difference = (primitive - expected).expand().cancel();
34910        assert!(
34911            residual_is_zero(&difference),
34912            "primitive should match Rubi trace for Bondarenko line 29; difference: {difference}"
34913        );
34914    }
34915
34916    #[test]
34917    fn integrates_bondarenko_33_tanh_exponential_radical_like_rubi() {
34918        let primitive = integrate(&parse!("tanh(x)/sqrt(exp(x)+exp(2*x))"), symbol!("x"))
34919            .expect("Bondarenko line 33 should follow Rubi 2.3.95");
34920        assert!(
34921            !rubi_contains_unintegrable(&primitive),
34922            "Bondarenko line 33 should return a primitive instead of unintegrable: {primitive}"
34923        );
34924    }
34925
34926    #[test]
34927    fn integrates_bondarenko_36_logarithmic_exponential_like_rubi() {
34928        assert_derivative_round_trip(parse!("log(1+exp(x))/(1+exp(2*x))"));
34929    }
34930
34931    #[test]
34932    fn integrates_exponential_binomial_denominator_by_function_of_exponential_substitution() {
34933        assert_derivative_round_trip(parse!("1/(a+b*exp(c+d*x))"));
34934    }
34935
34936    #[test]
34937    fn integrates_bondarenko_30_trig_subst_for_simplifies_like_rubi() {
34938        assert_derivative_round_trip(parse!("1/(cos(x)+cos(3*x))^5"));
34939    }
34940
34941    #[test]
34942    fn power_variable_expn_substitutes_common_integer_power() {
34943        let x = symbol!("x");
34944        let sub = rubi_symbols().sub1;
34945        let sub_atom = Atom::var(sub);
34946        let (integrand, power) =
34947            rubi_power_variable_expn_subst(&parse!("sin(x^4)"), &Atom::num(2), x, sub)
34948                .expect("sin(x^4) should be a function of x^2 with shift 2");
34949
34950        assert_eq!(power, Atom::num(2));
34951        assert_eq!(integrand, sub_atom.to_owned() * sub_atom.pow(2).sin());
34952    }
34953
34954    #[test]
34955    fn power_variable_expn_rejects_gcd_one_like_mathematica() {
34956        let x = symbol!("x");
34957        let sub = rubi_symbols().sub1;
34958        let expr = parse!("1/(sqrt(1-x^2)*(x^2+sqrt(1-x^2)))");
34959
34960        assert!(
34961            rubi_power_variable_expn_subst(&expr, &Atom::num(3), x, sub).is_none(),
34962            "PowerVariableDegree returns False as soon as GCD[3,2] is not greater than 1"
34963        );
34964    }
34965
34966    #[test]
34967    fn power_variable_expn_handles_normalized_scaled_integer_power() {
34968        let x = symbol!("x");
34969        let sub = rubi_symbols().sub1;
34970        let (integrand, power, scale) =
34971            rubi_power_variable_expn_subst_scaled(&parse!("sin((c*x)^4)"), &Atom::num(2), x, sub)
34972                .expect("PowerVariableDegree should use the common scaled power");
34973
34974        assert_eq!(integrand, parse!("sub1*sin(c^4*sub1^2)"));
34975        assert_eq!(power, Atom::num(2));
34976        assert_eq!(scale, Atom::num(1));
34977    }
34978
34979    #[test]
34980    fn power_variable_expn_substitutes_productlog_integer_power() {
34981        let x = symbol!("x");
34982        let sub = rubi_symbols().sub1;
34983        let data =
34984            rubi_power_variable_expn_subst(&parse!("ProductLog(a*x^2)^p"), &Atom::num(-2), x, sub)
34985                .expect("ProductLog(a*x^2)^p should be a function of x^2");
34986
34987        assert_eq!(data.1, Atom::num(2));
34988        assert_eq!(data.0, parse!("ProductLog(a*sub1)^p/sub1"));
34989    }
34990
34991    #[test]
34992    fn power_variable_expn_rejects_bare_calculus_arguments_like_rubi() {
34993        let x = symbol!("x");
34994
34995        assert!(
34996            rubi_power_variable_expn(&parse!("rubi_tan(x)^3*rubi_sec(x)"), Atom::num(2), x)
34997                .is_none()
34998        );
34999    }
35000
35001    #[test]
35002    fn power_variable_expn_substitutes_symbolic_scaled_power() {
35003        let x = symbol!("x");
35004        let sub = rubi_symbols().sub1;
35005        let (integrand, power, scale) = rubi_power_variable_expn_subst_scaled(
35006            &parse!("1/sqrt(a+b*(c*(d*x)^m)^n)"),
35007            &Atom::num(0),
35008            x,
35009            sub,
35010        )
35011        .expect("nested scaled symbolic power should match PowerVariableExpn");
35012
35013        assert_eq!(power, parse!("m"));
35014        assert_eq!(scale, parse!("d"));
35015        assert_eq!(integrand, parse!("1/sqrt(a+b*(c*sub1)^n)"));
35016    }
35017
35018    #[test]
35019    fn substitution_helpers_reserve_nested_dummy_symbols() {
35020        let x = symbol!("x");
35021        let outer_guard =
35022            fresh_substitution_symbol().expect("the outer substitution should reserve sub1");
35023        assert_eq!(outer_guard.symbol(), rubi_symbols().sub1);
35024
35025        let data = rubi_power_variable_expn(&parse!("sin(x^4)"), Atom::num(2), x)
35026            .expect("the nested substitution should use the next dummy symbol");
35027        assert_eq!(data.substitution_symbol, rubi_symbols().sub2);
35028        assert_eq!(
35029            data.integrand,
35030            parse!("sub2*sin(sub2^2)"),
35031            "the returned payload must retain the reserved nested symbol"
35032        );
35033
35034        drop(data);
35035        drop(outer_guard);
35036        let next_guard =
35037            fresh_substitution_symbol().expect("released substitution symbols should be reusable");
35038        assert_eq!(next_guard.symbol(), rubi_symbols().sub1);
35039    }
35040
35041    #[test]
35042    fn integrate_with_abort_separates_public_api_from_internal_cancellation() {
35043        let x = symbol!("x");
35044        let abort = AtomicBool::new(true);
35045
35046        assert!(integrate_with_abort_impl(&parse!("x"), x, &abort).is_none());
35047
35048        abort.store(false, AtomicOrdering::Relaxed);
35049        let primitive = integrate_with_abort(&parse!("x"), x)
35050            .expect("the internal abort flag should remain unset")
35051            .expect("x should integrate");
35052        assert!((primitive.derivative(x) - parse!("x")).expand().is_zero());
35053        assert_eq!(
35054            integrate_with_abort_impl(parse!("x").as_view(), x, &abort),
35055            Some(Ok(primitive))
35056        );
35057
35058        let unfinished = integrate_with_abort_impl(&parse!("f(x)"), x, &abort)
35059            .expect("an unsupported integrand should not look cancelled");
35060        assert!(unfinished.is_err());
35061    }
35062
35063    #[test]
35064    fn integrate_with_abort_stops_recursive_normalization_loop() {
35065        let x = symbol!("x");
35066        let integrand = parse!(
35067            "(-8-8*x-x^2-3*x^3+7*x^4+4*x^5+2*x^6)/\
35068             ((-1+2*x^2)^2*(1+2*x^2+4*x^3+x^4)^(1/2))"
35069        );
35070        let abort = std::sync::Arc::new(AtomicBool::new(false));
35071        let watchdog_abort = std::sync::Arc::clone(&abort);
35072        let watchdog = std::thread::spawn(move || {
35073            std::thread::sleep(std::time::Duration::from_millis(20));
35074            watchdog_abort.store(true, AtomicOrdering::Relaxed);
35075        });
35076
35077        let started = std::time::Instant::now();
35078        let primitive = integrate_with_abort_impl(&integrand, x, &abort);
35079
35080        watchdog.join().expect("abort watchdog should not panic");
35081        assert!(
35082            abort.load(AtomicOrdering::Relaxed),
35083            "watchdog should have requested abort"
35084        );
35085        assert!(
35086            primitive.is_none(),
35087            "aborted primitive leaked: {primitive:?}"
35088        );
35089        assert!(
35090            started.elapsed() < std::time::Duration::from_secs(60),
35091            "abort should stop at recursive integration boundaries"
35092        );
35093    }
35094
35095    #[test]
35096    fn integrates_bondarenko_39_via_scaled_expand_integrand() {
35097        let x = symbol!("x");
35098        let integrand = parse!("log(x+sqrt(1+x))/(1+x^2)");
35099
35100        let primitive = integrate(&integrand, x)
35101            .expect("Rubi should integrate Bondarenko Problems.input line 39");
35102
35103        assert!(
35104            !rubi_contains_unintegrable(&primitive),
35105            "Bondarenko line 39 should follow the Rubi trace instead of returning unintegrable: {primitive}"
35106        );
35107    }
35108
35109    #[test]
35110    fn evaluates_zero_order_formal_derivatives_like_mathematica() {
35111        let x = symbol!("x");
35112        let f = symbol!("f");
35113
35114        assert_eq!(
35115            rubi_derivative(Atom::num(0), Atom::var(f), x),
35116            f.call(Atom::var(x))
35117        );
35118    }
35119
35120    #[test]
35121    fn evaluates_hyperbolic_downvalue_6154_guard_like_mathematica() {
35122        let x = symbol!("x");
35123        let v = parse!("a+b*x");
35124        let w = parse!("c+b*x");
35125        let difference = &v - &w;
35126
35127        assert!(gtq!(Atom::num(1), 0));
35128        assert!(neq!(w, v));
35129        assert!(
35130            rubi_evaluated_free_q(&difference, x),
35131            "Mathematica evaluates v-w to an x-free expression: {difference}"
35132        );
35133    }
35134
35135    #[test]
35136    fn helper_rules_follow_mathematica_downvalue_order() {
35137        let _ = symbol!("x");
35138
35139        fn orders(rules: &[RubiRule]) -> Vec<u16> {
35140            rules
35141                .iter()
35142                .map(|rule| {
35143                    rule.downvalue_order
35144                        .expect("every helper row must have a Mathematica DownValue order")
35145                })
35146                .collect()
35147        }
35148
35149        let mut expand_expected: Vec<_> = (3..=26).collect();
35150        expand_expected.extend([27, 27, 27]);
35151        expand_expected.extend(28..=38);
35152        expand_expected.extend([39, 39, 39, 39]);
35153        expand_expected.extend(40..=45);
35154
35155        assert_eq!(orders(rubi_expand_integrand_rules()), expand_expected);
35156        assert_eq!(orders(rubi_deactivate_trig_rules()), [1]);
35157        assert_eq!(
35158            orders(rubi_fix_inert_trig_function_rules()),
35159            (1..=60).collect::<Vec<_>>()
35160        );
35161        assert_eq!(
35162            orders(rubi_unify_inert_trig_function_rules()),
35163            (1..=75).collect::<Vec<_>>()
35164        );
35165    }
35166}