Weighted Fitting

Version Info

Minimum Origin Version Required: Origin 8.1 SR0

Need to do before Running Examples

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 following command or just add this file to your workspace.



The following code shows how to use NLFitSesssion to fit with weighted data.

  1. Create a new worksheet and import the data <Origin Installation Directory>\Samples\Curve Fitting\Gaussian.dat.
  2. Copy and compile the following codes in Code Builder, and then run "Weighted_Fitting" in Command Window.
#include <..\originlab\NLFitSession.h>

void Weighted_Fitting()
	// get the active worksheet
	Worksheet wks = Project.ActiveLayer();
		out_str("Not a valid worksheet!");
		return; // need to activate a worksheet with data
	NLFitSession FitSession;
	// 1. set function
		out_str("Set fitting function error!");
	// get parameter names and number
	vector<string> vsParamNames;
	int nNumParamsInFunction = FitSession.GetParamNamesInFunction(vsParamNames);
	// get data range
	DataRange drInputData;
	drInputData.Add(wks, 0, "X");  // x column
	drInputData.Add(wks, 1, "Y");  // y column
	drInputData.Add(wks, 2, "ED");  // weight column
	// 2. set the dataset
	vector vX, vY, vW;
	drInputData.GetData(&vX, 0);
	drInputData.GetData(&vY, 1);
	drInputData.GetData(&vW, 2);
	if(!FitSession.SetData(vY, vX, NULL, 0, 1, DATA_MODE_INDEP_CONSOLID, vW))
		out_str("Set data error!");
	// 3. set parameter init values
		out_str("Init values error!");
	// 4. set weight method, WEIGHT_NONE = no weight, WEIGHT_INSTRUMENTAL = instrumental
	// WEIGHT_STATISTICAL = statistics
	if(!FitSession.SetWeightData(WEIGHT_INSTRUMENTAL, 0.0, 0.0, 0.0))
		out_str("Set weight method error!");
	// 5. start fitting	
	int nFitOutcome;
		string strOutcome = FitSession.GetFitOutCome(nFitOutcome);
		out_str("Fit error! "+strOutcome);
	// 6. success, get results	
	RegStats fitStats;
	NLSFFitInfo fitInfo;
	vector vParamValues, vErrors;
	FitSession.GetFitResultsStats(&fitStats, &fitInfo, false, 0);
	FitSession.GetFitResultsParams(vParamValues, vErrors);
	printf("# Iterations = %d, Reduced Chisqr = %g\n", fitInfo.Iterations, fitStats.ReducedChiSq);
	for(int nParam=0; nParam<vParamValues.GetSize(); nParam++)
		printf("# %s = %f, %s_error = %f\n", vsParamNames[nParam], vParamValues[nParam], vsParamNames[nParam], vErrors[nParam]);