/* TA-LIB Copyright (c) 1999-2025, Mario Fortier
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in
 *   the documentation and/or other materials provided with the
 *   distribution.
 *
 * - Neither name of author nor the names of its contributors
 *   may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/* Important:
 *  This file is automatically generated by the utility ta_codegen.
 *  Any modifications will be lost on next execution of ta_codegen.
 *
 *  Modifications should instead be done with the "C" source file
 *  in ta-lib\src\ta_func
 */

/* List of contributors:
 *
 *  Initial  Name/description
 *  -------------------------------------------------------------------
 *  MF       Mario Fortier
 *
 *
 * Change history:
 *
 *  MMDDYY BY   Description
 *  -------------------------------------------------------------------
 *  120802 MF   Template creation.
 *  101003 MF   Initial Coding
 *  062804 MF   Resolve div by zero bug on limit case.
 */

// Import types from parent module
use super::*;

// Allow non-snake-case names to maintain TA-Lib API compatibility
#[allow(non_snake_case)]
#[allow(unused_variables)]
#[allow(dead_code)]
#[allow(unused_mut)]
#[allow(unused_assignments)]
impl Core {
    /// Lookback period for [`Core::correl`]: the number of leading input values consumed before the
    /// first output value can be produced.
    ///
    /// # Arguments
    ///
    /// * `optInTimePeriod` — Rolling window length (default 30, range 1..=100000)
    ///
    /// Returns `usize::MAX` when a parameter is out of range. Integer parameters accept `i32::MIN`
    /// to select their default value.
    #[inline]
    pub fn correl_lookback(&self, mut optInTimePeriod: i32) -> usize {
        if ((optInTimePeriod) as i32) == (i32::MIN) {
            optInTimePeriod = 30;
        } else if (((optInTimePeriod) as i32) < 1) || (((optInTimePeriod) as i32) > 100000) {
            return usize::MAX;
        }
        return (optInTimePeriod - 1) as usize;
    }
    /// Pearson's correlation coefficient (r) between two input series over a rolling window of
    /// optInTimePeriod bars. Measures how linearly the two series move together. r near +1: strong
    /// positive co-movement; near -1: strong inverse; near 0: no linear relationship.
    ///
    /// # Formula
    ///
    /// ```text
    /// r = (sumXY - sumX*sumY/n) / sqrt((sumX2 - sumX^2/n) * (sumY2 - sumY^2/n)),  n = optInTimePeriod, sums over the window
    /// ```
    ///
    /// # Notes
    ///
    /// * When the correlation is undefined for a window (for example a constant series), the output
    ///   is 0 rather than an error or NaN.
    ///
    /// # Arguments
    ///
    /// * `startIdx` — Start index of the requested calculation range.
    /// * `endIdx` — End index of the requested calculation range (inclusive).
    /// * `inReal0` — First data series (X)
    /// * `inReal1` — Second data series (Y)
    /// * `optInTimePeriod` — Rolling window length (default 30, range 1..=100000)
    /// * `outBegIdx` — Set to the input index of the first output value.
    /// * `outNBElement` — Set to the number of output values written.
    /// * `outReal` — Correlation coefficient r in \[-1, 1].
    ///
    /// Integer parameters accept `i32::MIN` to select their default value.
    ///
    /// # Errors
    ///
    /// Returns [`RetCode::OutOfRangeStartIndex`] when `endIdx < startIdx`, and
    /// [`RetCode::BadParam`] when an optional parameter is outside its documented range.
    ///
    /// # Panics
    ///
    /// Input slices must cover `startIdx..=endIdx` and output slices must hold the number of values
    /// produced for that range: undersized slices panic or, for functions that forward to unchecked
    /// internals, cause undefined behavior. Sizing every output slice to the input length is always
    /// sufficient.
    ///
    /// # Examples
    ///
    /// ```
    /// use ta_lib::{Core, RetCode};
    ///
    /// let data0: Vec<f64> = (0..252).map(|i| 100.0 + 10.0 * (0.1 * i as f64).sin()).collect();
    /// let data1: Vec<f64> = (0..252).map(|i| 100.0 + 10.0 * (0.1 * i as f64 + 0.7).sin()).collect();
    ///
    /// let core = Core::new();
    /// let mut out_beg = 0;
    /// let mut out_nb = 0;
    /// let mut out = vec![0.0; 252];
    ///
    /// let ret = core.correl(
    ///     0, data0.len() - 1, &data0, &data1, 30,
    ///     &mut out_beg, &mut out_nb, &mut out,
    /// );
    /// assert_eq!(ret, RetCode::Success);
    /// assert!(out_nb > 0);
    /// ```
    ///
    /// # See also
    ///
    /// [`Core::beta`] · [`Core::stddev`] · [`Core::var`]
    ///
    /// # References
    ///
    /// * Karl Pearson
    ///
    /// Further reading: [ta-lib.org/functions/correl](https://ta-lib.org/functions/correl/)
    #[doc(alias = "PearsonCorrelation")]
    #[doc(alias = "CorrelationCoefficient")]
    #[doc(alias = "r")]
    pub fn correl(
        &self,
        startIdx: usize,
        endIdx: usize,
        inReal0: &[f64],
        inReal1: &[f64],
        mut optInTimePeriod: i32,
        outBegIdx: &mut usize,
        outNBElement: &mut usize,
        outReal: &mut [f64],
    ) -> RetCode {
        if endIdx < startIdx {
            return RetCode::OutOfRangeStartIndex;
        }
        if ((optInTimePeriod) as i32) == (i32::MIN) {
            optInTimePeriod = 30;
        } else if (((optInTimePeriod) as i32) < 1) || (((optInTimePeriod) as i32) > 100000) {
            return RetCode::BadParam;
        }
        let mut startIdx = startIdx;
        let mut sumXY: f64 = 0.0_f64;
        let mut sumX: f64 = 0.0_f64;
        let mut sumY: f64 = 0.0_f64;
        let mut sumX2: f64 = 0.0_f64;
        let mut sumY2: f64 = 0.0_f64;
        let mut x: f64 = 0.0_f64;
        let mut y: f64 = 0.0_f64;
        let mut trailingX: f64 = 0.0_f64;
        let mut trailingY: f64 = 0.0_f64;
        let mut tempReal: f64 = 0.0_f64;
        let mut lookbackTotal: usize = 0_usize;
        let mut today: usize = 0_usize;
        let mut trailingIdx: usize = 0_usize;
        let mut outIdx: usize = 0_usize;
        // Move up the start index if there is not
        // enough initial data.
        lookbackTotal = (optInTimePeriod - 1) as usize;
        if startIdx < lookbackTotal {
            startIdx = lookbackTotal;
        }
        // Make sure there is still something to evaluate.
        if startIdx > endIdx {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return RetCode::Success;
        }
        (*outBegIdx) = startIdx;
        trailingIdx = startIdx - lookbackTotal;
        // Calculate the initial values.
        sumY2 = 0.0;
        sumX2 = sumY2;
        sumY = sumX2;
        sumX = sumY;
        sumXY = sumX;
        for today in (trailingIdx as usize)..(startIdx as usize) + 1 {
            x = inReal0[today];
            sumX += x;
            sumX2 += x * x;
            y = inReal1[today];
            sumXY += x * y;
            sumY += y;
            sumY2 += y * y;
        }
        today = (startIdx as usize) + 1;
        // Write the first output.
        // Save first the trailing values since the input
        // and output might be the same array,
        trailingX = inReal0[trailingIdx];
        trailingY = inReal1[{ let _v = trailingIdx; trailingIdx += 1; _v }];
        tempReal = (sumX2 - sumX * sumX / ((optInTimePeriod) as f64)) * (sumY2 - sumY * sumY / ((optInTimePeriod) as f64));
        if !((tempReal) < 1e-14) {
            outReal[0] = (sumXY - sumX * sumY / ((optInTimePeriod) as f64)) / (tempReal).sqrt();
        } else {
            outReal[0] = 0.0;
        }
        // Tight loop to do subsequent values.
        outIdx = 1;
        while today <= endIdx {
            // Remove trailing values
            sumX -= trailingX;
            sumX2 -= trailingX * trailingX;
            sumXY -= trailingX * trailingY;
            sumY -= trailingY;
            sumY2 -= trailingY * trailingY;
            // Add new values
            x = inReal0[today];
            sumX += x;
            sumX2 += x * x;
            y = inReal1[{ let _v = today; today += 1; _v }];
            sumXY += x * y;
            sumY += y;
            sumY2 += y * y;
            // Output new coefficient.
            // Save first the trailing values since the input
            // and output might be the same array,
            trailingX = inReal0[trailingIdx];
            trailingY = inReal1[{ let _v = trailingIdx; trailingIdx += 1; _v }];
            tempReal = (sumX2 - sumX * sumX / ((optInTimePeriod) as f64)) * (sumY2 - sumY * sumY / ((optInTimePeriod) as f64));
            if !((tempReal) < 1e-14) {
                outReal[outIdx] = (sumXY - sumX * sumY / ((optInTimePeriod) as f64)) / (tempReal).sqrt();
                outIdx += 1;
            } else {
                outReal[outIdx] = 0.0;
                outIdx += 1;
            }
        }
        (*outNBElement) = outIdx;
        return RetCode::Success;
    }
    /// Unchecked variant of [`Core::correl`], used for internal cross-indicator calls.
    ///
    /// Skips parameter validation and uses unchecked indexing internally. Every argument must
    /// satisfy the constraints documented on [`Core::correl`]; an out-of-range parameter, an input
    /// slice not covering `startIdx..=endIdx`, or an undersized output slice may panic or cause
    /// undefined behavior. Prefer [`Core::correl`].
    #[inline]
    pub fn correl_unguarded(
        &self,
        mut startIdx: usize,
        endIdx: usize,
        inReal0: &[f64],
        inReal1: &[f64],
        mut optInTimePeriod: i32,
        outBegIdx: &mut usize,
        outNBElement: &mut usize,
        outReal: &mut [f64],
    ) -> RetCode {
        let mut sumXY: f64 = 0.0_f64;
        let mut sumX: f64 = 0.0_f64;
        let mut sumY: f64 = 0.0_f64;
        let mut sumX2: f64 = 0.0_f64;
        let mut sumY2: f64 = 0.0_f64;
        let mut x: f64 = 0.0_f64;
        let mut y: f64 = 0.0_f64;
        let mut trailingX: f64 = 0.0_f64;
        let mut trailingY: f64 = 0.0_f64;
        let mut tempReal: f64 = 0.0_f64;
        let mut lookbackTotal: usize = 0_usize;
        let mut today: usize = 0_usize;
        let mut trailingIdx: usize = 0_usize;
        let mut outIdx: usize = 0_usize;
        unsafe {
        assert!(endIdx < inReal0.len());
        assert!(endIdx < inReal1.len());
        let _assertLb = self.correl_lookback(optInTimePeriod);
        let _assertStart = if startIdx > _assertLb { startIdx } else { _assertLb };
        assert!(_assertStart > endIdx || endIdx - _assertStart < outReal.len());
        lookbackTotal = (optInTimePeriod - 1) as usize;
        if startIdx < lookbackTotal {
            startIdx = lookbackTotal;
        }
        if startIdx > endIdx {
            (*outBegIdx) = 0;
            (*outNBElement) = 0;
            return RetCode::Success;
        }
        (*outBegIdx) = startIdx;
        trailingIdx = startIdx - lookbackTotal;
        sumY2 = 0.0;
        sumX2 = sumY2;
        sumY = sumX2;
        sumX = sumY;
        sumXY = sumX;
        for today in (trailingIdx as usize)..(startIdx as usize) + 1 {
            x = *inReal0.as_ptr().add(today);
            sumX += x;
            sumX2 += x * x;
            y = *inReal1.as_ptr().add(today);
            sumXY += x * y;
            sumY += y;
            sumY2 += y * y;
        }
        today = (startIdx as usize) + 1;
        trailingX = *inReal0.as_ptr().add(trailingIdx);
        trailingY = *inReal1.as_ptr().add({ let _v = trailingIdx; trailingIdx += 1; _v });
        tempReal = (sumX2 - sumX * sumX / ((optInTimePeriod) as f64)) * (sumY2 - sumY * sumY / ((optInTimePeriod) as f64));
        if !((tempReal) < 1e-14) {
            *outReal.as_mut_ptr().add(0) = (sumXY - sumX * sumY / ((optInTimePeriod) as f64)) / (tempReal).sqrt();
        } else {
            *outReal.as_mut_ptr().add(0) = 0.0;
        }
        outIdx = 1;
        while today <= endIdx {
            sumX -= trailingX;
            sumX2 -= trailingX * trailingX;
            sumXY -= trailingX * trailingY;
            sumY -= trailingY;
            sumY2 -= trailingY * trailingY;
            x = *inReal0.as_ptr().add(today);
            sumX += x;
            sumX2 += x * x;
            y = *inReal1.as_ptr().add({ let _v = today; today += 1; _v });
            sumXY += x * y;
            sumY += y;
            sumY2 += y * y;
            trailingX = *inReal0.as_ptr().add(trailingIdx);
            trailingY = *inReal1.as_ptr().add({ let _v = trailingIdx; trailingIdx += 1; _v });
            tempReal = (sumX2 - sumX * sumX / ((optInTimePeriod) as f64)) * (sumY2 - sumY * sumY / ((optInTimePeriod) as f64));
            if !((tempReal) < 1e-14) {
                *outReal.as_mut_ptr().add(outIdx) = (sumXY - sumX * sumY / ((optInTimePeriod) as f64)) / (tempReal).sqrt();
                outIdx += 1;
            } else {
                *outReal.as_mut_ptr().add(outIdx) = 0.0;
                outIdx += 1;
            }
        }
        (*outNBElement) = outIdx;
        return RetCode::Success;
        } // unsafe
    }
}
/***************/
/* End of File */
/***************/
