/*
 * 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 */
/* USERCODE-END:Imports */

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

    @Override
    public void convertMaskToImplementation() throws Exception {
        MaskDouble CoeffBMaskVal = (MaskDouble)this.getMaskParameter("CoeffB").getMaskDataType();
        TNumeric CoeffBMaskData = (TNumeric)CoeffBMaskVal.getData();
        double mp_CoeffB = CoeffBMaskData.getReal(0, 0);
        MaskDouble CoeffAMaskVal = (MaskDouble)this.getMaskParameter("CoeffA").getMaskDataType();
        TNumeric CoeffAMaskData = (TNumeric)CoeffAMaskVal.getData();
        double mp_CoeffA = CoeffAMaskData.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 coeffBCtrVal = this.getImplementationParameterData("coeffB");
        double[] cp_coeffB = new double[32];
        cp_coeffB[0] = Double.NaN;
        TNumeric coeffACtrVal = this.getImplementationParameterData("coeffA");
        double[] cp_coeffA = new double[31];
        cp_coeffA[0] = Double.NaN;
        TNumeric orderNCtrVal = this.getImplementationParameterData("orderN");
        double cp_orderN = Double.NaN;
        TNumeric orderDCtrVal = this.getImplementationParameterData("orderD");
        double cp_orderD = 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_CoeffB OR CoeffBMaskVal (Number) */
        /* mp_CoeffA OR CoeffAMaskVal (Number) */
        /* mp_ts_fact OR ts_factMaskVal (Number) */

        /* USERCODE-BEGIN:ConvMaskToImplementation */
        final int SIZE_COL = 32; /* maximum order */
        final int SIZE_ROW = 1;

        /* get order of numerator and denominator */
        int orderN = CoeffBMaskData.getNumColumns();
        int orderD = CoeffAMaskData.getNumColumns();

        /* check numerator input for correct size */
        if ((orderN > SIZE_COL) || (CoeffBMaskData.getNumRows() != SIZE_ROW)) {
            throw new Exception("Numerator size mismatch in column: expected=(" + SIZE_ROW + ", " + SIZE_COL + ") "
                    + "got=(" + CoeffBMaskData.getNumRows() + "," + orderN + ")");
        }
        /* check denominator input for correct size */
        if ((orderD > SIZE_COL) || (CoeffAMaskData.getNumRows() != SIZE_ROW)) {
            throw new Exception("Numerator size mismatch in column: expected=(" + SIZE_ROW + ", " + SIZE_COL + ") "
                    + "got=(" + CoeffAMaskData.getNumRows() + "," + orderD + ")");
        }
        /* check relation of order number between numerator and denominator */
        if (orderN > orderD) {
            throw new Exception("Order of numerator must not be higher than order of denominator!");
        }

        /* get coefficient a0 for normalization purposes */
        double a0 = CoeffAMaskData.getReal(0, 0);
        if (a0 == 0) {
            throw new Exception("Coefficient a0 must not be zero!");
        }

        /* get numerator coefficients */
        Double[] coeffB = new Double[SIZE_COL];
        for (int i = 0; i < orderN; i++) {
            coeffB[i] = CoeffBMaskData.getReal(0, orderN - i - 1); /* read coefficients in reversed order */
            coeffB[i] = coeffB[i] / a0; /* normalization */
        }
        for (int i = orderN; i < SIZE_COL; i++) {
            coeffB[i] = 0.0;
        }

        /* get denominator coefficients */
        Double[] coeffA = new Double[SIZE_COL - 1];
        for (int i = 0; i < (orderD - 1); i++) {
            coeffA[i] = CoeffAMaskData.getReal(0, orderD - i - 1); /* read coefficients in reversed order and omit a0 */
            coeffA[i] = coeffA[i] / a0; /* normalization */
        }
        for (int i = orderD - 1; i < (SIZE_COL - 1); i++) {
            coeffA[i] = 0.0;
        }

        /* set implementation parameter values */
        coeffBCtrVal = new TNumeric(coeffB);
        coeffACtrVal = new TNumeric(coeffA);
        orderNCtrVal.setReal(0, 0, orderN);
        orderDCtrVal.setReal(0, 0,
                orderD - 1); /* due to normalization a0 is always 1 and hence doesn't have to be transfered */

        /* USERCODE-END:ConvMaskToImplementation */

        /* Implementation Parameter values */
        /* cp_coeffB OR coeffBCtrVal (RAM array) */
        /* cp_coeffA OR coeffACtrVal (RAM array) */
        /* cp_orderN OR orderNCtrVal (Value) */
        /* cp_orderD OR orderDCtrVal (Value) */

        if (Double.isNaN(cp_coeffB[0])) {
            this.setImplementationParameterData("coeffB", coeffBCtrVal);
        } else {
            this.setImplementationParameterData("coeffB", new TNumeric(cp_coeffB));
        }
        if (Double.isNaN(cp_coeffA[0])) {
            this.setImplementationParameterData("coeffA", coeffACtrVal);
        } else {
            this.setImplementationParameterData("coeffA", new TNumeric(cp_coeffA));
        }
        if (Double.isNaN(cp_orderN)) {
            this.setImplementationParameterData("orderN", orderNCtrVal);
        } else {
            this.setImplementationParameterData("orderN", new TNumeric(cp_orderN));
        }
        if (Double.isNaN(cp_orderD)) {
            this.setImplementationParameterData("orderD", orderDCtrVal);
        } else {
            this.setImplementationParameterData("orderD", new TNumeric(cp_orderD));
        }
    }

    @Override
    public void convertImplementationToMask() throws Exception {
        MaskDouble CoeffBMaskVal = (MaskDouble)this.getMaskParameter("CoeffB").getMaskDataType();
        TNumeric CoeffBMaskData = (TNumeric)CoeffBMaskVal.getData();
        double mp_CoeffB = Double.NaN;
        MaskDouble CoeffAMaskVal = (MaskDouble)this.getMaskParameter("CoeffA").getMaskDataType();
        TNumeric CoeffAMaskData = (TNumeric)CoeffAMaskVal.getData();
        double mp_CoeffA = 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 coeffBCtrVal = this.getImplementationParameterData("coeffB");
        double[] cp_coeffB = coeffBCtrVal.getRealMatrix().getColumn(0);
        TNumeric coeffACtrVal = this.getImplementationParameterData("coeffA");
        double[] cp_coeffA = coeffACtrVal.getRealMatrix().getColumn(0);
        TNumeric orderNCtrVal = this.getImplementationParameterData("orderN");
        double cp_orderN = orderNCtrVal.getReal(0, 0);
        TNumeric orderDCtrVal = this.getImplementationParameterData("orderD");
        double cp_orderD = orderDCtrVal.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_coeffB OR coeffBCtrVal (RAM array) */
        /* cp_coeffA OR coeffACtrVal (RAM array) */
        /* cp_orderN OR orderNCtrVal (Value) */
        /* cp_orderD OR orderDCtrVal (Value) */

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

        /* Mask parameter values */
        /* mp_CoeffB OR CoeffBMaskVal (Number) */
        /* mp_CoeffA OR CoeffAMaskVal (Number) */
        /* mp_ts_fact OR ts_factMaskVal (Number) */

        if (Double.isNaN(mp_CoeffB)) {
            this.getMaskParameter("CoeffB").setValue(CoeffBMaskData.toFullString());
        } else {
            this.getMaskParameter("CoeffB").setValue(new TNumeric(mp_CoeffB).toFullString());
        }
        if (Double.isNaN(mp_CoeffA)) {
            this.getMaskParameter("CoeffA").setValue(CoeffAMaskData.toFullString());
        } else {
            this.getMaskParameter("CoeffA").setValue(new TNumeric(mp_CoeffA).toFullString());
        }
    }
}
