2.2.1.2 NLFitSession


Name

NLFitSession

Remark

The NLFitSession is a higher level Origin class, which is available to perform nonlinear fitting by handling the fitting process with a copy of the data while perform iterations. It wraps the NLFit class with a friendly interface to aid in implementing the fitting evaluation procedure. It is the kernel of the NLFit dialog. This class is recommended for coding in Origin C, because it takes care of all the complexities that arise from the process of interfacing to Origin.

Hierarchy

  • NLFitSession

Examples

EX1

Prior to running the following example, the nlsf_utils.c file need to be loaded and compiled. This can be done from script with the command run.LoadOC(Originlab\nlsf_utils.c) or just add this file to your workspace.

#include <..\originlab\NLFitSession.h>
bool NLFitSession_Fit_ex()
{   
    Worksheet   wks;
    wks.Create("origin");
    
    // Prepare worksheet with XYY columns and simulate data for the first two XY columns as Gauss curve
    vector      vX, vY;
    if( !prepare_simulate_data_wks(wks, vX, vY) )
    {
        out_str("Fail to generate simulate data");
        return false;
    }
 
    
    NLFitSession    FitSession;
 
    // Set function
    if( !FitSession.SetFunction("Gauss")) // set function as Gauss, category name can be ignore
    {
        out_str("invalid fit function");
        return false;
    }   
 
    // Set data
    if( !FitSession.SetData(vY, vX))
    {
        out_str("fail to set data");
        return false;
    }
 
    // Parameter initializtion
    if( !FitSession.ParamsInitValues())
    {
        out_str("fail to initialize parameter");
        return false;
    }
 
    out_str("The parameter values before fitting");
    FitSession.GetChiSqr(); // call GetChiSqr in order to set parameter settings on internal fit object
    show_params(FitSession);
 
    // Fit
    int     nOutcome;
    if( !FitSession.Fit(&nOutcome) )
    {
        out_str("Fail to do fitting");
        return false;
    }
 
    out_str("The parameter values after fitting");
    show_params(FitSession);
 
 
    // Calculate fitting Y   
    vector      vFitY(vX.GetSize());
    if( 0 == FitSession.GetYFromX(vX, vFitY, vFitY.GetSize()) )
    {
        out_str("Fail to get Y values");
        return false;
    }        
 
    // Put fitting Y data to worksheet column C.
    XYRange xyFit;
    xyFit.Add(wks, 0, "X");
    xyFit.Add(wks, 2, "Y");     
    xyFit.SetData(&vFitY, &vX);
 
    // Plot input data and fitting data
    GraphPage   gp;
    gp.Create("origin");
    GraphLayer gl = gp.Layers(0);
 
    int nPlot = gl.AddPlot(wks, IDM_PLOT_LINE); // plot input as line
    if( nPlot >= 0)
    {          
        DataPlot dp = gl.DataPlots(1);
        if(dp)
            dp.SetColor(SYSCOLOR_RED); // set fit plot color to read
 
        gl.Rescale();
        legend_update(gl); //refresh graph legend
    }
 
    return true;
}
 
bool prepare_simulate_data_wks(Worksheet& wks, vector& vX, vector& vY)
{
    if( !wks )
    {
        out_str("error in prepare_simulate_data_wks");
        return false;
    }
    
    // Format worksheet
    wks.SetSize(-1, 3);
    wks.SetColDesignations("XYY");
 
    vector<string> vsNames = {"Data X", "Data Y", "Fit Y"};
    int ii = 0;
    foreach(Column col in wks.Columns)
    {
        col.SetLongName(vsNames[ii++]);
    }  
 
    // Generate simulate data  
    string      strFDF = okutil_get_origin_path(ORIGIN_PATH_SYSTEM, "FitFunc")+"Gauss.FDF";
    Tree        trFF;
    if( !nlsf_FDF_to_tree( strFDF, &trFF ))
        return false;
 
    NumericFunction NF;
    NF.SetTree(trFF);
 
    // Initalize the independent data values:
    int         nPts = 500;
    vX.Data(1, nPts, 1);
 
    vector      vParams(4); // 4 is the number of params in the function y0,xc,w,A are parameters for Gauss.    
    vParams[0] = 5;         // y0
    vParams[1] = 250;       // xc
    vParams[2] = 40;        // w
    vParams[3] = 7;         // A
 
    // Vector for the dependent data
    vY.SetSize(nPts);
    BOOL        bb = NF.Evaluate(vParams, vY, vX, NULL, nPts);
    if (!bb)
    {
        out_str("Failed!");
        return false;
    }   
    add_white_noise(vY, 5, NOISE_OVER_DIFFERENCE); // add 5% noise      
 
    // Put data from vectors to worksheet
    DataRange dr;
    dr.Add(wks, 0, "X");
    dr.Add(wks, 1, "Y");
 
    dr.SetData(&vY, &vX);
    return true;
}
 
void show_params(NLFitSession& FitSession)
{
    // get parameter values after initialization
	vector vParamValues, vErrors;
	FitSession.GetFitResultsParams(vParamValues, vErrors);    
 
    // output parameter values with names
    vector<string> vsParamNames;
    FitSession.GetParamNamesInFunction(vsParamNames);   
 
    int         nDataset = 0;
    for( int nParam = 0; nParam < vParamValues.GetSize(); nParam++)
    {
        printf("%s = %f\n", vsParamNames[nParam], vParamValues[nParam]);
    }   
}

Header to Include

Originlab\NLFitSession.h

Reference

Members

Name Brief Example
Fit Perform the fitting. Examples
GetFitOutCome Get fit outcome string. Examples
GetFitResultsParams Get the parameter results after fitting done. Examples
GetFitResultsStats To get the statistics reuslt after fitting done. Examples
GetParamNamesInFunction Get the parameter names defined in function. Examples
GetParamValuesAndOffsets Get parameter values. Examples
GetYFromX Get fitting Y calculated by given X value and parameters. Examples
GetChiSqr Calculate the current reduced Chi-square value. Examples
Iterate Perform iteration. Examples
ParamsInitValues Initialize parameters. Examples
SetData Set input data. Examples
SetFunction Set fitting function. Examples
SetMaxNumIter Set the max number of allowed iterate times when do fitting. Examples
SetParamBounds To set parameter lower/upper bounds. Examples
SetParamFix To set parameter fixed. Examples
SetParamShare To set parameter share Examples
SetParamValues To set all the parameter values. Examples
SetTolerance Set the tolerance value to stop the iterations. Examples