-
Notifications
You must be signed in to change notification settings - Fork 67
Advanced Fitting
gavalian edited this page Aug 1, 2018
·
6 revisions
This example will show you how to extend Func1D and override the function evaluation method as well as the initial parameter estimation method.
First, Define your custom function by extending Func1D and overriding the evaluate(double x) method.
import org.jlab.groot.math.Func1D;
public class CustomFunction extends Func1D{
public CustomFunction(String name, double min, double max) {
super(name, min, max);
// user should add parameters to the function so the
// getNPars() function will now how many parameters
// the function has
addParameter("p0"); // adding a parameter with name "p0"
addParameter("p1"); // adding a parameter with name "p1"
addParameter("p2"); // adding a parameter with name "p2"
addParameter("p3"); // adding a parameter with name "p3"
}
//Simple polynomial function of any order
@Override
public double evaluate(double x){
double sum = 0.0;
for(int i=0; i<this.getNPars(); i++){
sum += this.getParameter(i)*Math.pow(x,i);
}
return sum;
}
}
After you have defined your custom function, now you can use it the same way you would use a Func1D. This includes the RandomFunction for randomly filling histograms and also you can use it with the DataFitter class.
import javax.swing.JFrame;
import org.jlab.groot.data.H1F;
import org.jlab.groot.fitter.DataFitter;
import org.jlab.groot.graphics.EmbeddedCanvas;
import org.jlab.groot.math.RandomFunc;
public class CustomFunctionDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Basic GROOT Demo");
EmbeddedCanvas canvas = new EmbeddedCanvas();
frame.setSize(800,500);
H1F histogram = new H1F("histogram",100,-5.0,5.0);
CustomFunction f1 = new CustomFunction("CustomFunction", -5.1, 5.1);
f1.setParameter(0, 30.0);
f1.setParameter(1, -6.0);
f1.setParameter(2, 1.8);
f1.setParameter(3, .0001);
RandomFunc rndm = new RandomFunc(f1);
for (int j = 0; j < 64000; j++) {
histogram.fill(rndm.random());
}
histogram.setTitleX("Randomly Generated Function");
histogram.setTitleY("Counts");
canvas.getPad(0).setTitle("CustomFunction Example");
histogram.setLineWidth(2);
histogram.setLineColor(21);
histogram.setFillColor(34);
histogram.setOptStat(10);
f1.setLineColor(5);
f1.setLineWidth(7);
f1.setOptStat(111110);
DataFitter.fit(f1, histogram, "Q");
canvas.draw(histogram);
canvas.setFont("Avenir");
canvas.setTitleSize(32);
canvas.setAxisTitleSize(24);
canvas.setAxisLabelSize(18);
canvas.setStatBoxFontSize(18);
frame.add(canvas);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}