/*
 * Copyright (c) 2018, Linz Center of Mechatronics GmbH (LCM), web: www.lcm.at
 * All rights reserved.
 */
/*
 * This file is licensed according to the BSD 3-clause license as follows:
 * 
 * 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 the name of the "Linz Center of Mechatronics GmbH" and "LCM" 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 "Linz Center of Mechatronics GmbH" 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.
 */
/*
 * This file is part of X2C. web: x2c.lcm.at
 * $LastChangedRevision: 4463 $
 * $LastChangedDate:: 2026-08-17 13:59:56 +0200#$
 */
/* USERCODE-BEGIN:Description */
/* Description: */
/* USERCODE-END:Description */

package at.lcm.x2c.library.filter;

import at.lcm.x2c.core.structure.*;
import at.lcm.bu21.general.dtypes.*;

/* USERCODE-BEGIN:Imports */
import at.lcm.x2c.utils.QFormat;
/* USERCODE-END:Imports */

@SuppressWarnings("unused")
public class ConvFnc_NotchBiQ_FiP16 extends JavaConversionFunction {
    private static final long serialVersionUID = 1L;

    @Override
    public void convertMaskToImplementation() throws Exception {
        MaskComboBox methodMaskVal = (MaskComboBox)this.getMaskParameter("method").getMaskDataType();
        TString methodMaskData = (TString)methodMaskVal.getData();
        String mp_method = methodMaskData.getString();
        MaskDouble fnMaskVal = (MaskDouble)this.getMaskParameter("fn").getMaskDataType();
        TNumeric fnMaskData = (TNumeric)fnMaskVal.getData();
        double mp_fn = fnMaskData.getReal(0, 0);
        MaskDouble QMaskVal = (MaskDouble)this.getMaskParameter("Q").getMaskDataType();
        TNumeric QMaskData = (TNumeric)QMaskVal.getData();
        double mp_Q = QMaskData.getReal(0, 0);
        MaskDouble ts_factMaskVal = (MaskDouble)this.getMaskParameter("ts_fact").getMaskDataType();
        TNumeric ts_factMaskData = (TNumeric)ts_factMaskVal.getData();
        double mp_ts_fact = ts_factMaskData.getReal(0, 0);

        TNumeric b0CtrVal = this.getImplementationParameterData("b0");
        double cp_b0 = Double.NaN;
        TNumeric b1CtrVal = this.getImplementationParameterData("b1");
        double cp_b1 = Double.NaN;
        TNumeric b2CtrVal = this.getImplementationParameterData("b2");
        double cp_b2 = Double.NaN;
        TNumeric a1CtrVal = this.getImplementationParameterData("a1");
        double cp_a1 = Double.NaN;
        TNumeric a2CtrVal = this.getImplementationParameterData("a2");
        double cp_a2 = Double.NaN;
        TNumeric sfrb0CtrVal = this.getImplementationParameterData("sfrb0");
        double cp_sfrb0 = Double.NaN;
        TNumeric sfrb1CtrVal = this.getImplementationParameterData("sfrb1");
        double cp_sfrb1 = Double.NaN;
        TNumeric sfrb2CtrVal = this.getImplementationParameterData("sfrb2");
        double cp_sfrb2 = Double.NaN;
        TNumeric sfra1CtrVal = this.getImplementationParameterData("sfra1");
        double cp_sfra1 = Double.NaN;
        TNumeric sfra2CtrVal = this.getImplementationParameterData("sfra2");
        double cp_sfra2 = Double.NaN;

        /* Check if sample time factor is an integer value */
        if (Math.rint(mp_ts_fact) != mp_ts_fact) {
            throw new Exception("Sample time factor must be a whole number");
        }
        /* Check if sample time factor is within the valid range (upper limit defined by unsigned 16-bit integer range) */
        if ((mp_ts_fact < 1.0) || (mp_ts_fact > 65535.0)) {
            throw new Exception("Sample time factor must be at least 1 and at most 65535");
        }
        /* Block sample time */
        double bp_ts = mp_ts_fact * this.getDedicatedBlock().getModel().getSampleTime();
        /* Check if Block sample time has a valid value */
        if (bp_ts <= 0.0) {
            throw new Exception("Block sample time must be greater than zero");
        }

        /* ATTENTION: */
        /* The M2I conversion function may either use the mp_* or *MaskVal value to get the Mask Parameter value */
        /* For new or updated implementations, the mp_* value shall be used where possible */
        /* Currently, the mp_* value cannot be used for getting non-scalar Mask Parameter data but will return only the first element for these */
        /* The Implementation Parameter assignment variables cp_* can and shall be used for all Implementation Parameter data types */

        /* INFO: Implementation data assignment for array types when using the cp_* variables */
        /* If the cp_* parameter is a FLASH ARRAY, the cp_* variable is assigned an array type but without an actual array */
        /* The M2I conversion function has to assign an array with the correct size and fill it with content */
        /* If the cp_* parameter is a RAM ARRAY, the cp_* variable is assigned an array with the correct size */
        /* The first element is assigned an invalid value while the other elements are (auto)initialized with zero */
        /* The M2I conversion function has to fill the array with content */

        /* Mask parameter values */
        /* mp_method OR methodMaskVal (String) */
        /* mp_fn OR fnMaskVal (Number) */
        /* mp_Q OR QMaskVal (Number) */
        /* mp_ts_fact OR ts_factMaskVal (Number) */

        /* USERCODE-BEGIN:ConvMaskToImplementation */
        /* get mask parameter values */
        double f_n = Double.valueOf(fnMaskVal.getValue()); /* the notch frequency */
        double Q = Double.valueOf(QMaskVal.getValue()); /* Q-factor */
        double ts_fact = Double.valueOf(ts_factMaskVal.getValue()).intValue();

        /* validation */
        if (ts_fact < 1) {
            throw new Exception("Sample time factor must not be smaller than one!");
        }
        /* calculate multiplication factors for filter coefficients */
        double Ts = ts_fact * this.getDedicatedBlock().getModel().getSampleTime();
        double fs = 1 / Ts;

        if (Q < 0.5) {
            throw new Exception("The quality factor must be grater than 0.5.");
        }
        if (f_n > (fs / 2)) {
            throw new Exception("The notch frequency must be lower than fs/2.");
        }
        if (f_n < 0) {
            throw new Exception("The notch frequency must be grater than zero.");
        }

        // Create and initialize the coefficients
        double a0 = 1, a1 = 1, a2 = 1;
        double b0 = 1, b1 = 1, b2 = 1;
        // Calculate angular velocity
        double w0 = f_n * 2.0 * Math.PI;

        if (methodMaskVal.getValue().equals("bilinear")) {
            // warping of freq-axis
            w0 = (2.0 / Ts) * Math.tan((w0 * Ts) / 2.0);
            // Calculate coefficients using bilinear transformation s -> z
            // s = 2/Ts*((z-1)/((z+1)))
            a1 = (((2 * Q * Ts * Ts * w0 * w0) - (8 * Q))) / (((Q * Ts * Ts * w0 * w0) + (2 * Ts * w0) + (4 * Q)));
            b1 = a1;
            a2 = (((Q * Ts * Ts * w0 * w0) - (2 * Ts * w0)) + (4 * Q))
                    / (((Q * Ts * Ts * w0 * w0) + (2 * Ts * w0) + (4 * Q)));
            b0 = (((Q * Ts * Ts * w0 * w0) + (4 * Q))) / (((Q * Ts * Ts * w0 * w0) + (2 * Ts * w0) + (4 * Q)));
            b2 = b0;
        } else if (methodMaskVal.getValue().equals("matched Z-transform")) {
            // Calculate the coefficients using zeros and poles transform
            a0 = 1;
            a1 = -2 * Math.exp((-w0*Ts)/(2*Q)) * Math.cos(((-w0*Ts)/(2*Q)) * Math.sqrt((4*Q*Q) - 1));
            a2 = Math.exp((-2*w0*Ts)/(2*Q));
            b0 = 1;
            b1 = -2 * Math.cos(w0*Ts);
            b2 = 1;
            // Adjust gain:
            double K = (a0 + a1 + a2) / (b0 + b1 + b2);
            b0 *= K;
            b1 *= K;
            b2 *= K;
        }
        else {
            throw new Exception("You must choose one of possible method.");
        }

        /* set block parameter = filter coefficients */
        final int BITS = 16;

        /* determine shift factors */
        int sfrb0 = QFormat.getQFormat(b0, BITS, true);
        int sfrb1 = QFormat.getQFormat(b1, BITS, true);
        int sfrb2 = QFormat.getQFormat(b2, BITS, true);
        int sfra1 = QFormat.getQFormat(a1, BITS, true);
        int sfra2 = QFormat.getQFormat(a2, BITS, true);

        /* get coefficients mantissas */
        long manb0 = QFormat.getQValue(b0, sfrb0, BITS, true);
        long manb1 = QFormat.getQValue(b1, sfrb1, BITS, true);
        long manb2 = QFormat.getQValue(b2, sfrb2, BITS, true);
        long mana1 = QFormat.getQValue(a1, sfra1, BITS, true);
        long mana2 = QFormat.getQValue(a2, sfra2, BITS, true);

        /* Set shift factors */
        sfrb0CtrVal.setReal(0, 0, sfrb0);
        sfrb1CtrVal.setReal(0, 0, sfrb1);
        sfrb2CtrVal.setReal(0, 0, sfrb2);
        sfra1CtrVal.setReal(0, 0, sfra1);
        sfra2CtrVal.setReal(0, 0, sfra2);

        /* set coefficients mantissas */
        b0CtrVal.setReal(0, 0, manb0);
        b1CtrVal.setReal(0, 0, manb1);
        b2CtrVal.setReal(0, 0, manb2);
        a1CtrVal.setReal(0, 0, mana1);
        a2CtrVal.setReal(0, 0, mana2);

        /* USERCODE-END:ConvMaskToImplementation */

        /* Implementation Parameter values */
        /* cp_b0 OR b0CtrVal (Value) */
        /* cp_b1 OR b1CtrVal (Value) */
        /* cp_b2 OR b2CtrVal (Value) */
        /* cp_a1 OR a1CtrVal (Value) */
        /* cp_a2 OR a2CtrVal (Value) */
        /* cp_sfrb0 OR sfrb0CtrVal (Value) */
        /* cp_sfrb1 OR sfrb1CtrVal (Value) */
        /* cp_sfrb2 OR sfrb2CtrVal (Value) */
        /* cp_sfra1 OR sfra1CtrVal (Value) */
        /* cp_sfra2 OR sfra2CtrVal (Value) */

        if (Double.isNaN(cp_b0)) {
            this.setImplementationParameterData("b0", b0CtrVal);
        } else {
            this.setImplementationParameterData("b0", new TNumeric(cp_b0));
        }
        if (Double.isNaN(cp_b1)) {
            this.setImplementationParameterData("b1", b1CtrVal);
        } else {
            this.setImplementationParameterData("b1", new TNumeric(cp_b1));
        }
        if (Double.isNaN(cp_b2)) {
            this.setImplementationParameterData("b2", b2CtrVal);
        } else {
            this.setImplementationParameterData("b2", new TNumeric(cp_b2));
        }
        if (Double.isNaN(cp_a1)) {
            this.setImplementationParameterData("a1", a1CtrVal);
        } else {
            this.setImplementationParameterData("a1", new TNumeric(cp_a1));
        }
        if (Double.isNaN(cp_a2)) {
            this.setImplementationParameterData("a2", a2CtrVal);
        } else {
            this.setImplementationParameterData("a2", new TNumeric(cp_a2));
        }
        if (Double.isNaN(cp_sfrb0)) {
            this.setImplementationParameterData("sfrb0", sfrb0CtrVal);
        } else {
            this.setImplementationParameterData("sfrb0", new TNumeric(cp_sfrb0));
        }
        if (Double.isNaN(cp_sfrb1)) {
            this.setImplementationParameterData("sfrb1", sfrb1CtrVal);
        } else {
            this.setImplementationParameterData("sfrb1", new TNumeric(cp_sfrb1));
        }
        if (Double.isNaN(cp_sfrb2)) {
            this.setImplementationParameterData("sfrb2", sfrb2CtrVal);
        } else {
            this.setImplementationParameterData("sfrb2", new TNumeric(cp_sfrb2));
        }
        if (Double.isNaN(cp_sfra1)) {
            this.setImplementationParameterData("sfra1", sfra1CtrVal);
        } else {
            this.setImplementationParameterData("sfra1", new TNumeric(cp_sfra1));
        }
        if (Double.isNaN(cp_sfra2)) {
            this.setImplementationParameterData("sfra2", sfra2CtrVal);
        } else {
            this.setImplementationParameterData("sfra2", new TNumeric(cp_sfra2));
        }
    }

    @Override
    public void convertImplementationToMask() throws Exception {
        MaskComboBox methodMaskVal = (MaskComboBox)this.getMaskParameter("method").getMaskDataType();
        TString methodMaskData = (TString)methodMaskVal.getData();
        String mp_method = null;
        MaskDouble fnMaskVal = (MaskDouble)this.getMaskParameter("fn").getMaskDataType();
        TNumeric fnMaskData = (TNumeric)fnMaskVal.getData();
        double mp_fn = Double.NaN;
        MaskDouble QMaskVal = (MaskDouble)this.getMaskParameter("Q").getMaskDataType();
        TNumeric QMaskData = (TNumeric)QMaskVal.getData();
        double mp_Q = Double.NaN;
        MaskDouble ts_factMaskVal = (MaskDouble)this.getMaskParameter("ts_fact").getMaskDataType();
        TNumeric ts_factMaskData = (TNumeric)ts_factMaskVal.getData();
        double mp_ts_fact = ts_factMaskData.getReal(0, 0);

        TNumeric b0CtrVal = this.getImplementationParameterData("b0");
        double cp_b0 = b0CtrVal.getReal(0, 0);
        TNumeric b1CtrVal = this.getImplementationParameterData("b1");
        double cp_b1 = b1CtrVal.getReal(0, 0);
        TNumeric b2CtrVal = this.getImplementationParameterData("b2");
        double cp_b2 = b2CtrVal.getReal(0, 0);
        TNumeric a1CtrVal = this.getImplementationParameterData("a1");
        double cp_a1 = a1CtrVal.getReal(0, 0);
        TNumeric a2CtrVal = this.getImplementationParameterData("a2");
        double cp_a2 = a2CtrVal.getReal(0, 0);
        TNumeric sfrb0CtrVal = this.getImplementationParameterData("sfrb0");
        double cp_sfrb0 = sfrb0CtrVal.getReal(0, 0);
        TNumeric sfrb1CtrVal = this.getImplementationParameterData("sfrb1");
        double cp_sfrb1 = sfrb1CtrVal.getReal(0, 0);
        TNumeric sfrb2CtrVal = this.getImplementationParameterData("sfrb2");
        double cp_sfrb2 = sfrb2CtrVal.getReal(0, 0);
        TNumeric sfra1CtrVal = this.getImplementationParameterData("sfra1");
        double cp_sfra1 = sfra1CtrVal.getReal(0, 0);
        TNumeric sfra2CtrVal = this.getImplementationParameterData("sfra2");
        double cp_sfra2 = sfra2CtrVal.getReal(0, 0);

        /* Check if sample time factor is an integer value */
        if (Math.rint(mp_ts_fact) != mp_ts_fact) {
            throw new Exception("Sample time factor must be a whole number");
        }
        /* Check if sample time factor is within the valid range (upper limit defined by unsigned 16-bit integer range) */
        if ((mp_ts_fact < 1.0) || (mp_ts_fact > 65535.0)) {
            throw new Exception("Sample time factor must be at least 1 and at most 65535");
        }
        /* Block sample time */
        double bp_ts = mp_ts_fact * this.getDedicatedBlock().getModel().getSampleTime();
        /* Check if Block sample time has a valid value */
        if (bp_ts <= 0.0) {
            throw new Exception("Block sample time must be greater than zero");
        }

        /* ATTENTION: */
        /* The I2M conversion function may either use the cp_* or *CtrlVal value to get the Implementation Parameter value */
        /* For new or updated implementations, the cp_* value shall be used for all Implementation Parameter data types */
        /* The Mask Parameter assignment variables cp_* shall be used where possible */
        /* Currently, the mp_* variable assignment value cannot be used for setting non-scalar Mask Parameter data */

        /* Implementation Parameter values */
        /* cp_b0 OR b0CtrVal (Value) */
        /* cp_b1 OR b1CtrVal (Value) */
        /* cp_b2 OR b2CtrVal (Value) */
        /* cp_a1 OR a1CtrVal (Value) */
        /* cp_a2 OR a2CtrVal (Value) */
        /* cp_sfrb0 OR sfrb0CtrVal (Value) */
        /* cp_sfrb1 OR sfrb1CtrVal (Value) */
        /* cp_sfrb2 OR sfrb2CtrVal (Value) */
        /* cp_sfra1 OR sfra1CtrVal (Value) */
        /* cp_sfra2 OR sfra2CtrVal (Value) */

        /* USERCODE-BEGIN:ConvImplementationToMask */
        if (true) {
            throw new Exception(
                    "Implementation-to-Mask conversion not implemented for Block 'NotchBiQ', Implementation 'FiP16' in Library 'Filter'");
        }
        /* USERCODE-END:ConvImplementationToMask */

        /* Mask parameter values */
        /* mp_method OR methodMaskVal (String) */
        /* mp_fn OR fnMaskVal (Number) */
        /* mp_Q OR QMaskVal (Number) */
        /* mp_ts_fact OR ts_factMaskVal (Number) */

        if (mp_method == null) {
            this.getMaskParameter("method").setValue(methodMaskData.getString());
        } else {
            this.getMaskParameter("method").setValue(mp_method);
        }
        if (Double.isNaN(mp_fn)) {
            this.getMaskParameter("fn").setValue(fnMaskData.toFullString());
        } else {
            this.getMaskParameter("fn").setValue(new TNumeric(mp_fn).toFullString());
        }
        if (Double.isNaN(mp_Q)) {
            this.getMaskParameter("Q").setValue(QMaskData.toFullString());
        } else {
            this.getMaskParameter("Q").setValue(new TNumeric(mp_Q).toFullString());
        }
    }
}
