/*
*   Reflectivity Class
*
*   Methods for calculating the reflection of light from
*   the surface of a multilayer of dielectic and/or metal layers
*   and of fitting experimental data to a reflectivity, transmissivity
*   or evanescent field strength scan against angle or wavelength
*
*   Methods for fitting data to a reflectivty, transmissivitty or evanescent field
*   scan over a range of incident angles at a single wavelength
*
*   Author:  Dr Michael Thomas Flanagan.
*
*   Created: February/March/April 2006
*   Developed from earlier C++ and Fortran programs
*   Revised  26 April 2006, 5-7 July 2008
*
*   DOCUMENTATION:
*   See Michael Thomas Flanagan's Java library on-line web page:
*   http://www.ee.ucl.ac.uk/~mflanaga/java/Refflectivity.html
*   http://www.ee.ucl.ac.uk/~mflanaga/java/
*
*   Copyright (c) March 2006   Michael Thomas Flanagan
*
*   PERMISSION TO COPY:
*   Permission to use, copy and modify this software and its documentation for
*   NON-COMMERCIAL purposes is granted, without fee, provided that an acknowledgement
*   to the author, Michael Thomas Flanagan at www.ee.ucl.ac.uk/~mflanaga, appears in all copies.
*
*   Dr Michael Thomas Flanagan makes no representations about the suitability
*   or fitness of the software for any or for a particular purpose.
*   Michael Thomas Flanagan shall not be liable for any damages suffered
*   as a result of using, modifying or distributing this software or its derivatives.
*
***************************************************************************************/

package flanagan.optics;

import flanagan.complex.*;
import flanagan.math.Fmath;
import flanagan.math.Conv;
import flanagan.plot.*;
import flanagan.analysis.*;
import java.util.ArrayList;
import java.lang.reflect.Array;

public class Reflectivity{

    // CLASS VARIABLES

    private int numberOfLayers = 0;                 // number of layers including the semi-infinite layer at both outer faces
    private int numberOfInterfaces = 0;             // number of interlayer interfaces, i.e. number of layers minus one

    private Complex[][] refractiveIndices = null;   // refractive indices of the layers at all wavelengths (number of wavelength, number of layers)
    private Complex[] meanRefractiveIndices = null; // mean refractive indices of each layer
    private boolean refractSet = false;             // = true when refractive indices entered
    private boolean[] refractLayerSet = null;       // = true for layer i when refractive indices entered for layer i
    private boolean meanRefractUsed = false;        // = true when mean refractive indices used

    private Complex[][] relativeMagneticPermeabilities = null;  // relative magnetic permeabilities of the layers
                                                                // default values = 1.0
    private Complex[] meanRelativeMagneticPermeabilities = null;// mean relative magnetic permeabilities of the layers
    private boolean magneticSet = false;             // = true when relative magnetic permeabilities entered
    private boolean meanMagneticUsed = false;        // = true when mean relative magnetic permeabilities used

    private double[][] absorptionCoefficients = null;   // absorption coefficents of the layers at all wavelengths
                                                        // default values = 0.0;
    private boolean absorbSet = false;              // = true when absorbtivity or extinction coefficients entered

    private double[] thicknesses = null;            // thicknesses (in metres) of the layers
    private double[] distances = null;              // cumulative thicknesses (in metres)
    private boolean thickSet = false;               // = true when thicknesses entered
    private boolean[] thickLayerSet = null;         // = true for layer i when thicknesses entered for layer i

    private int numberOfWavelengths = 0;            // number of wavelengths in wavelength scan
    private double[] wavelengths = null;            // wavelengths (in metres) in scan
    private double[] frequencies = null;            // frequencies (in Hz) in scan
    private double[] omega = null;                  // radial frequencies (in radians) in scan
    private int[] origWavelIndices = null;          // indices of the wavelengths as entered before sort into lowest to highest
    private boolean wavelSet = false;               // = true when wavelengths entered
    private boolean freqSet = false;                // = true when frequencies entered
    private boolean wavelNumberSet = false;         // = true when number of wavelengths set

    private double[] incidentAngleDeg = null;       // incident angles measured from the normal in degrees
    private double[] incidentAngleRad = null;       // incident angles measured from the normal in radians
    private int[] incidentAngleIndices = null;      // indices of original incident angles after sorting into ascending order
    private int numberOfIncidentAngles = 0;         // number of incident angles in angular scan
    private boolean incidentAngleSet = false;       // = true when the incident angles have been entered

    private String mode = null;                     // polarisation mode: TE, TM,  unpolarised or mixed
    private double eVectorAngleDeg = 0.0D;          // angle between the electric vector of the incident light and
                                                    // the plane normal to the reflecting surfac in degrees
    private double eVectorAngleRad = 0.0D;          // angle between the electric vector of the incident light and
                                                    // the plane normal to the reflecting surfac in radians
    private double teFraction = 0.0D;               // fraction of light in the TE mode
    private double tmFraction = 0.0D;               // fraction of light in the TM mode
    private boolean modeSet = false;                // = true when mode set

    private Complex[][][] koVector = null;          // ko vector [wavelength] [incident angle] [layer]
    private Complex[][][] kVector = null;           // k vector  [wavelength] [incident angle] [layer]
    private Complex[][][] kxVector = null;          // kx vector [wavelength] [incident angle] [layer]
    private Complex[][][] kzVector = null;          // kz vector [wavelength] [incident angle] [layer]

    private double[][] reflectivities = null;       // reflectivities   [wavelength] [incident angle]
    private double[][] transmissivities = null;     // transmissivities [wavelength] [incident angle]
    private double[][] powerLosses = null;          // power loss on transmission relative to an input power of 1mW over 1 sq. metre [wavelength] [incident angle]
    private Complex[][] reflectCoeffTE = null;      // TE reflection coefficient [wavelength] [incident angle]
    private Complex[][] reflectCoeffTM = null;      // TM reflection coefficient [wavelength] [incident angle]
    private Complex[][] transmitCoeffTE = null;     // TE transmission coefficient [wavelength] [incident angle]
    private Complex[][] transmitCoeffTM = null;     // TM transmissiom coefficient [wavelength] [incident angle]

    private double[][] reflectPhaseShiftRadTE = null;   // TE reflection phase shift (radians) [wavelength] [incident angle]
    private double[][] reflectPhaseShiftRadTM = null;   // TM reflection phase shift (radians) [wavelength] [incident angle]
    private double[][] transmitPhaseShiftRadTE = null;  // TE transmission phase shift (radians) [wavelength] [incident angle]
    private double[][] transmitPhaseShiftRadTM = null;  // TM transmissiom phase shift (radians) [wavelength] [incident angle]
    private double[][] reflectPhaseShiftDegTE = null;   // TE reflection phase shift (degrees) [wavelength] [incident angle]
    private double[][] reflectPhaseShiftDegTM = null;   // TM reflection phase shift (degrees) [wavelength] [incident angle]
    private double[][] transmitPhaseShiftDegTE = null;  // TE transmission phase shift (degrees) [wavelength] [incident angle]
    private double[][] transmitPhaseShiftDegTM = null;  // TM transmissiom phase shift (degrees) [wavelength] [incident angle]

    private double[][] evanescentFields = null;     // integrated evanescent fields [wavelength] [incident angle]
    private double fieldDistance = Double.POSITIVE_INFINITY;    // distance into evanescent field over which intensity is integrated
    private boolean fieldIntensityCalc= false;      // = true when field intensity calculated for non-infinite field distance
    private double[][] penetrationDepths= null;     // Evanescent field penetration depth [wavelength] [incident angle]
    private double[][] transmitAnglesRad = null;    // transmitted angles in radians [wavelength] [incident angle]
    private double[][] transmitAnglesDeg = null;    // transmitted angles in degrees [wavelength] [incident angle]

    private boolean singleReflectCalculated = false;            // = true when only a single angular relectivity has been calculated
    private boolean angularReflectCalculated = false;           // = true when an angular relectivity scan has been calculated
    private boolean wavelengthReflectCalculated = false;        // = true when an wavelength relectivity scan has been calculated
    private boolean wavelengthAndAngularReflectCalculated = false;  // = true when angular for each wavelength relectivity scan has been calculated

    private double mu0overEps0 = Fmath.MU_0/Fmath.EPSILON_0;    // permeability of free space over permittivity of free space
    private double impedance = Math.sqrt(mu0overEps0);          // characteristic impedance of free space

    private int wavelengthAxisOption = 1;           // = 1 when wavelength/frequency x-axis in plotting methods = wavelength
                                                    // = 2 when wavelength/frequency x-axis in plotting methods = frequency, Hz
                                                    // = 3 when wavelength/frequency x-axis in plotting methods = radians

    private double[] experimentalData = null;       // experimental data [incident angle]
    private double[] experimentalWeights = null;    // error in each experimental point [incident angle]
    private double[] calculatedData = null;         // calculated data [incident angle]

    private int numberOfDataPoints = 0;             // number of experimental data points
    private boolean experimentalDataSet = false;    // = true when experimental data entered
    private boolean weightingOption = false;        // = true if experimental weightings (other than unity) entered

    private int numberOfEstimatedParameters = 0;            // number of parameters to be estimated in non-linear regression method
    private int[] thicknessEstimateIndices = null;          // indices of the thicknesses to be estimated by non-linear regression
    private int[] refractIndexRealEstimateIndices = null;   // indices of the Real[refractive indices] to be estimated by non-linear regression
    private int[] refractIndexImagEstimateIndices = null;   // indices of the Imag[refractive indices] to be estimated by non-linear regression
    private int[] absorptionCoeffEstimateIndices = null;    // indices of the absorption coefficients to be estimated by non-linear regression
    private int[] magneticPermRealEstimateIndices = null;   // indices of the Real[relative magnetic permeability] to be estimated by non-linear regression
    private int[] magneticPermImagEstimateIndices = null;   // indices of the Imag[relative magnetic permeability] to be estimated by non-linear regression

    private boolean refractIndexImagEstimateSet = false;    // = true when indices of the Imag[refractive indices] set
    private boolean absorptionCoeffEstimateSet = false;     // = true when indices of the absorption coefficients set

    private int thicknessEstimateNumber = 0;        // number of the thicknesses to be estimated by non-linear regression
    private int refractIndexRealEstimateNumber = 0; // number of the Real[refractive indices] to be estimated by non-linear regression
    private int refractIndexImagEstimateNumber = 0; // number of the Imag[refractive indices] to be estimated by non-linear regression
    private int absorptionCoeffEstimateNumber = 0;  // number of the absorption coefficients to be estimated by non-linear regression
    private int magneticPermRealEstimateNumber = 0; // number of the Real[relative magnetic permeabilities] to be estimated by non-linear regression
    private int magneticPermImagEstimateNumber = 0; // number of the Imag[relative magnetic permeabilities] to be estimated by non-linear regression

    private double fieldScalingFactor = 0.0D;       // scaling factor between calculated and experimental field values

    public int regressionOption = 0;                // Regression option
                                                    // = 1; reflectivity versus angle
                                                    // = 2; transmissivity versus angle
                                                    // = 3; evanescent field versus angle
    public int degreesOfFreedom = 0;                // degrees of freedom (non-linear regression method)

    // CONSTRUCTOR

    public Reflectivity(int n){
        this.numberOfLayers = n;
        this.numberOfInterfaces = n-1;
        if(n<2)throw new IllegalArgumentException("There must be at least two layers, i.e. at least one interface");

        this.meanRelativeMagneticPermeabilities = Complex.oneDarray(this.numberOfLayers, 1.0D, 0.0D);

        this.meanRefractiveIndices = Complex.oneDarray(this.numberOfLayers);
        this.refractLayerSet = new boolean[this.numberOfLayers];
        for(int i=0; ithis.numberOfLayers)throw new IllegalArgumentException("Layer number, " + layerNumber + ", must be in the range 1 to "+this.numberOfLayers);
        this.thicknesses[layerNumber-1] = thickness;

        // Recalculate distances
        this.distances[0] = 0.0D;
        for(int i=1; i1){
            // test if not in order
            boolean test0 = true;
            boolean test1 = false;
            int ii = 1;
            while(test0){
                if(this.wavelengths[ii]=this.numberOfWavelengths)test0 = false;
                }
            }
            if(test1){
                // reorder
                ArrayList arrayl = Fmath.selectSortArrayList(wavelengths);
                this.wavelengths = (double[])arrayl.get(1);
                this.origWavelIndices = (int[])arrayl.get(2);

                Complex[][] tempC = new Complex[this.numberOfWavelengths][this.numberOfLayers];
                for(int i=0; ithis.numberOfLayers)throw new IllegalArgumentException("Layer number, " + layerNumber + ", must be in the range 1 to " + this.numberOfLayers);
        int n = refractiveIndices.length;
        if(this.wavelNumberSet){
            if(n!=this.numberOfWavelengths)throw new IllegalArgumentException("The number of refractive index wavelength values, " + n + ", does not match the number of wavelengths already entered, " + this.numberOfWavelengths);

        }
        else{
            // Give dimensions to refractive index arrays - fill with mean if known
            this.numberOfWavelengths = n;
            this.wavelNumberSet = true;
            this.refractiveIndices = Complex.twoDarray(this.numberOfLayers, this.numberOfWavelengths);
            if(this.meanRefractUsed){
                for(int i=0; ithis.numberOfLayers)throw new IllegalArgumentException("Layer number, " + layerNumber + ", must be in the range 1 to " + this.numberOfLayers);
        int n = refractiveIndices.length;
        if(this.wavelNumberSet){
            if(n!=this.numberOfWavelengths)throw new IllegalArgumentException("The number of refractive index wavelength values, " + n + ", does not match the number of wavelengths already entered, " + this.numberOfWavelengths);
        }
        Complex[] complexRefractiveIndices = Complex.oneDarray(n);
        for(int i=0; i1)this.sortWavelengths();

            // Calculate ko, k, kx and kz vectors
            // redundant arrays included for ease of programming
            this.koVector = Complex.threeDarray(this.numberOfWavelengths, this.numberOfIncidentAngles, this.numberOfLayers);
            this.kzVector = Complex.threeDarray(this.numberOfWavelengths, this.numberOfIncidentAngles, this.numberOfLayers);
            this.kVector  = Complex.threeDarray(this.numberOfWavelengths, this.numberOfIncidentAngles, this.numberOfLayers);
            this.kxVector = Complex.threeDarray(this.numberOfWavelengths, this.numberOfIncidentAngles, this.numberOfLayers);

            for(int i=0; i0.0D)this.kxVector[i][j][k] = this.kxVector[i][j][k].times(Complex.minusOne());

                    }
                }
            }

            // Arrays for calculated parameters
            this.reflectivities = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.transmissivities = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.powerLosses = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.reflectCoeffTE = Complex.twoDarray(this.numberOfWavelengths, this.numberOfIncidentAngles);
            this.reflectCoeffTM = Complex.twoDarray(this.numberOfWavelengths, this.numberOfIncidentAngles);
            this.transmitCoeffTE = Complex.twoDarray(this.numberOfWavelengths, this.numberOfIncidentAngles);
            this.transmitCoeffTM = Complex.twoDarray(this.numberOfWavelengths, this.numberOfIncidentAngles);
            this.evanescentFields = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.penetrationDepths = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.transmitAnglesRad = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.transmitAnglesDeg = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.reflectPhaseShiftRadTE = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.reflectPhaseShiftRadTM = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.reflectPhaseShiftDegTE = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.reflectPhaseShiftDegTM = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.transmitPhaseShiftRadTE = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.transmitPhaseShiftRadTM = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.transmitPhaseShiftDegTE = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];
            this.transmitPhaseShiftDegTM = new double[this.numberOfWavelengths][this.numberOfIncidentAngles];

            // Perform scan over angles and wavelengths
            this.scan();
        }
    }

    // Calculation of the reflection coefficient for a single or multiple wavelengths and a single or range of incident angles entered
    public void scan(){
        if(!this.wavelSet)throw new IllegalArgumentException("No wavelength has been entered");
        if(!this.refractSet)throw new IllegalArgumentException("No, or not all, refractive indices have been entered");
        if(!this.thickSet)throw new IllegalArgumentException("No, or not all, layer thicknesses have been entered");
        if(!this.incidentAngleSet)throw new IllegalArgumentException("No incident angle has been entered");
        if(!this.modeSet)throw new IllegalArgumentException("No polaristaion mode (TE, TM, unpolarised or mixed[angle to be entered]) has been entered");

        this.singleReflectCalculated = false;
        this.angularReflectCalculated = false;
        this.wavelengthReflectCalculated = false;
        this.wavelengthAndAngularReflectCalculated = false;

        for(int i=0; i0.0D){
            ret1 = this.calcTEreflectivity(wavelengthIndex, angleIndex);
        }
        if(this.tmFraction>0.0D){
            double[] ret2 = this.calcTMreflectivity(wavelengthIndex, angleIndex);
            ret1[0] = this.teFraction*ret1[0] + this.tmFraction*ret2[0];
            ret1[1] = this.teFraction*ret1[1] + this.tmFraction*ret2[1];
            ret1[2] = this.teFraction*ret1[2] + this.tmFraction*ret2[2];
            ret1[3] = this.teFraction*ret1[3] + this.tmFraction*ret2[3];
            ret1[4] = this.teFraction*ret1[4] + this.tmFraction*ret2[4];
            ret1[5] = this.teFraction*ret1[5] + this.tmFraction*ret2[5];
        }

        this.reflectivities[wavelengthIndex][angleIndex] = ret1[0];
        this.transmissivities[wavelengthIndex][angleIndex]= ret1[1];
        this.transmitAnglesRad[wavelengthIndex][angleIndex] = ret1[2];
        this.transmitAnglesDeg[wavelengthIndex][angleIndex] = Math.toDegrees(ret1[2]);
        this.evanescentFields[wavelengthIndex][angleIndex] = ret1[3];
        this.penetrationDepths[wavelengthIndex][angleIndex] = ret1[4];
        this.powerLosses[wavelengthIndex][angleIndex] = ret1[5];

    }

    // Calculate the reflectivities for the TE mode
    public double[] calcTEreflectivity(int wavelengthIndex, int angleIndex){

        Complex tempc1 = Complex.zero();  // temporary variable for calculations
        Complex tempc2 = Complex.zero();  // temporary variable for calculations
        Complex tempc3 = Complex.zero();  // temporary variable for calculations
        Complex tempc4 = Complex.zero();  // temporary variable for calculations

        double penetrationDepth = 0.0D;

        if(this.numberOfLayers==2){
            tempc1 = this.relativeMagneticPermeabilities[wavelengthIndex][1].times(this.kxVector[wavelengthIndex][angleIndex][0]);
            tempc2 = this.relativeMagneticPermeabilities[wavelengthIndex][0].times(this.kxVector[wavelengthIndex][angleIndex][1]);
            tempc3 = tempc1.minus(tempc2);
            tempc4 = tempc1.plus(tempc2);
            this.reflectCoeffTE[wavelengthIndex][angleIndex] = tempc3.over(tempc4);

            tempc3 = tempc1.times(2.0D);
            this.transmitCoeffTE[wavelengthIndex][angleIndex] = tempc3.over(tempc4);
        }
        else{
            // Create instance of Matrix Mi
            ComplexMatrix mati = new ComplexMatrix(2, 2);

            // Create instance of Complex array Mi
            Complex[][] matic = Complex.twoDarray(2, 2);

            // Calculate cos(theta[1]), beta[1], cos[beta[1]], sin[beta[1]], p[1]
            Complex costheta = this.kxVector[wavelengthIndex][angleIndex][1].over(this.kVector[wavelengthIndex][angleIndex][1]);
            Complex pTerm = (this.refractiveIndices[wavelengthIndex][1].over(this.impedance)).over(Complex.sqrt(this.relativeMagneticPermeabilities[wavelengthIndex][1]));
            pTerm = pTerm.times(costheta);
            Complex beta = this.kxVector[wavelengthIndex][angleIndex][1].times(this.thicknesses[1]);
            matic[0][0] = Complex.cos(beta);
            matic[1][1] = matic[0][0];
            tempc1 = Complex.sin(beta);
            tempc1 = tempc1.times(Complex.minusJay());
            matic[0][1] = tempc1.over(pTerm);
            matic[1][0] = tempc1.times(pTerm);

            if(this.numberOfLayers>3){

                // Create instance of Matrix M
                ComplexMatrix mat = new ComplexMatrix(Complex.copy(matic));

                for(int i=2; i3){
                // Create instance of Matrix M
                ComplexMatrix mat = new ComplexMatrix(Complex.copy(matic));

                for(int i=2; i=this.numberOfDataPoints)test=false;
            }
        }

        // Create an instance of Regression
        Regression regr = null;
        if(this.weightingOption){
            regr = new Regression(this.incidentAngleDeg, this.experimentalData, this.experimentalWeights);
        }
        else{
            regr = new Regression(this.incidentAngleDeg, this.experimentalData);
        }

        // Create instance of regression function
        RegressFunct funct0 = new RegressFunct();

        // Transfer values to function
        funct0.numberOfLayers = this.numberOfLayers;
        funct0.mode = this.mode;
        funct0.eVectorAngleDeg = this.eVectorAngleDeg;
        funct0.thicknesses = this.thicknesses;
        funct0.refractiveIndices = this.refractiveIndices;
        funct0.relativeMagneticPermeabilities = this.relativeMagneticPermeabilities;
        funct0.regressionOption = this.regressionOption;
        funct0.thicknessEstimateIndices = this.thicknessEstimateIndices;
        funct0.refractIndexRealEstimateIndices = this.refractIndexRealEstimateIndices;
        funct0.refractIndexImagEstimateIndices = this.refractIndexImagEstimateIndices;
        funct0.magneticPermRealEstimateIndices = this.magneticPermRealEstimateIndices;
        funct0.magneticPermImagEstimateIndices = this.magneticPermImagEstimateIndices;

        // Number of estimated parameters
        this.numberOfEstimatedParameters = this.thicknessEstimateNumber;
        this.numberOfEstimatedParameters += this.refractIndexRealEstimateNumber;
        this.numberOfEstimatedParameters += this.refractIndexImagEstimateNumber;
        this.numberOfEstimatedParameters += this.magneticPermRealEstimateNumber;
        this.numberOfEstimatedParameters += this.magneticPermImagEstimateNumber;
        if(this.regressionOption==3)this.numberOfEstimatedParameters++;

        this.degreesOfFreedom = this.numberOfDataPoints - this.numberOfEstimatedParameters;
        if(this.degreesOfFreedom<1)throw new IllegalArgumentException("Number of parameters to be estimated, " + this.numberOfEstimatedParameters + ", is greater than or equal to the number of data points, " + this.numberOfDataPoints + ".");

        // Fill initial estimate arrays
        double[] start = new double[this.numberOfEstimatedParameters];
        double[] init = new double[this.numberOfEstimatedParameters];
        double[] step = new double[this.numberOfEstimatedParameters];

        int pIndex = 0;
        for(int i=0; i 

Ads help maintain this website.