How to pass all variables at once to SetParameter()....PyRoot

I am having trouble passing parameters to the .SetParameters() function in PyROOT.
When passing these parameters (which are in a numpy array) it spits out an error something like this

File "/run/media/user1/Seagate/ORNL_DATA/droc_epical/PhotFIT.py", line 130, in <module> CLA_GetData() File "/run/media/user1/Seagate/ORNL_DATA/droc_epical/PhotFIT.py", line 126, in __init__ CLA_HistoFit(hist_init[k],name[k]) File "/run/media/user1/Seagate/ORNL_DATA/droc_epical/PhotFIT.py", line 95, in __init__ multi.SetParameters(*par) TypeError: none of the 2 overloaded methods succeeded. Full details: void TF1::SetParameters(const Double_t* params) => TypeError: takes at most 1 arguments (3000 given) void TF1::SetParameters(double p0, double p1 = TMath::QuietNaN(), double p2 = TMath::QuietNaN(), double p3 = TMath::QuietNaN(), double p4 = TMath::QuietNaN(), double p5 = TMath::QuietNaN(), double p6 = TMath::QuietNaN(), double p7 = TMath::QuietNaN(), double p8 = TMath::QuietNaN(), double p9 = TMath::QuietNaN(), double p10 = TMath::QuietNaN()) => TypeError: takes at most 11 arguments (3000 given)
I know that the error messages are quite clear but does anyone know how i can give it all the parameters needed to fit a Gauss with multiple peaks.

I can give the source code but this website will not let a new user like me post a link.

Dear Cordney,

I am sorry to read you are facing this issue.

I think what you are trying to do, and pleas correct me if I am wrong, is to set parameters to a TF1 instance. What you can do is the following:

import ROOT
import array

# Example tf1 instance with parameters
f = ROOT.TF1("fa3","TMath::Landau(x,[0],[1],0)",-5,10) 
p = array.array('d',[1,2])
f.SetParameters(p)
f.Draw()

I hope this helps.

Cheers,
D

unfortunately using

p = array.array( ‘d’, [1,2] )
OR IN MY CASE
p = array.array( ‘d’, [0] *300 )

did not work for me, since I can’t hyperlink my code I will copy and paste my code here

import sys
import ROOT
import uproot4
import math
from tqdm import tqdm
import numpy as np
import array

print("Beginning...")

#Defining usage
if len(sys.argv) != 3:
    print (" USAGE : %s <input file> <run identifier>"%( sys.argv[0]))
    sys.exit(1)

#Function designed for saving histograms 
def savehist(hist, histname):
    """At the end of the function, there are no more references to `file`.                                          
    The `TFile` object gets deleted, which in turn saves and closes                                                 
    the ROOT file."""
    myfile.WriteObject(hist, histname)
#Opening .root file to save histograms 
myfile = ROOT.TFile.Open("../droc_epical/plots/"+sys.argv[2]+"_histograms.root", "RECREATE")

class CLA_buffer:
    def __init__(self,data: int):
        # self._data = bytes(data,encoding="utf-8")
        self._data = bytes(data)
        self._view=None
        
    def __buffer__(self,flags=None) -> memoryview:
        self._view = memoryview(self._data)
        return self._view
class CLA_MultiGauss:
    def __call__(self, t, para):
        height = para[0]
        mean = para[1]
        sig = para[2] 
        x = t[0]
        results = height * ROOT.TMath.Gaus(x,mean,sig)
        # tmp = -1.0 * ((x - mean)*(x - mean))/(2.0 * (sig * sig))
        return results
        # return height * math.exp(tmp) 

class CLA_HistoFit(object):
    def __init__(self,histogram,histo_identifier):
        c0 = ROOT.TCanvas()
        c1 = ROOT.TSpectrum(20)
        self.CLA_HistoFit = histogram
        self.CLA_HistoFit = histo_identifier
        
        c0.Update()
        
       # The code snippet you provided is performing background subtraction on a histogram using the
       # TSpectrum class in ROOT. Here is a breakdown of the steps:
        histogram_BG = c1.Background(histogram,14,"smooting3")
        histogram_SUBT_BG = histogram.Clone()
        histogram_SUBT_BG.Sumw2()
        histogram_SUBT_BG.Add(histogram_BG, -1)
        c1.Search(histogram_SUBT_BG,1,"",0.005)
        
        # c1.Search(histogram,1,"",0.005)
        x_peak, y_peak = c1.GetPositionX(), c1.GetPositionY()
        nPeaks = 0
        pos = [] 
        par = array.array('d',[0]*3000)
        # par = np.zeros(3000)
        # multi = [0] * c1.GetNPeaks()
        multi = 0
        sigma = 0.005
        par[0] = 0
        par[1] = 0
        
        
        for j in range(c1.GetNPeaks()):
            par[3*nPeaks +2] = y_peak[j]   #height
            par[3*nPeaks +3] = x_peak[j]   #mean
            par[3*nPeaks +4] = sigma
            nPeaks += 1
        print("Number of peaks found for CH" + histo_identifier + ": " + str(nPeaks) )
        
        for i in range(c1.GetNPeaks()):
            pos.append([x_peak[i],y_peak[i], sigma])
            pos.sort()
            
        
        # for i, entry in enumerate(pos):
        #     multi[i] = ROOT.TF1("MULTIFIT"+str(i), CLA_MultiGauss(), (entry[0] - 20), (entry[0] + 20),3)
        #     multi[i].SetParameters(entry[1],entry[0],entry[2])
        #     multi[i].FixParameter(3, multi[i].GetParameter(3))
        #     multi[i].SetNpx(1000)
        #     histogram.Fit(multi[i],"QMR+")
        
        
        multi = ROOT.TF1("MULTIFIT", CLA_MultiGauss(), 0, 4096 ,3 * nPeaks + 2)
        multi.SetParameters(*par)
        
        for j in range(c1.GetNPeaks()):
            multi.FixParameter(3 * j + 3, multi.GetParameter(3 * j + 3))
            
        multi.SetNpx(1000)
        histogram.Fit(multi,"QMR+")
            
        histogram.Draw()
        c0.Print("../droc_epical/plots/"+sys.argv[2]+"_CH"+ histo_identifier +".png")
        savehist(histogram,"histHGFIT_CH"+str(i))
        myfile.Write()
        c0.Clear()


class CLA_GetData():
    def __init__(self): 
        file = uproot4.open(sys.argv[1])
        channelref = file["tree/channel"].array(library="np")
        HGref =  file["tree/HG"].array(library="np")
        hist_init = [0] * len(channelref[0])
        name = [0] *len(channelref[0])
        print("Number of Channels: " + str(len(channelref[0])) )
        
        for j, val in enumerate(channelref):
            for k in tqdm(range(len(val)) ): #Progression Bar ON
            # for k in range( len(val) ): # Progression Bar OFF
                hist_init[k] =  ROOT.TH1F("Channel" + str(k), "HG Channel"+ str(k), 300, 0, 1500)  
                name[k] = str(val[k])  
                for i, entry in enumerate(HGref):
                    hist_init[k].Fill(entry[k])
                CLA_HistoFit(hist_init[k],name[k])
            break


CLA_GetData()


print("Done!")

To be clear I am making 3000 “slots” for the possibility of having x amount of peaks

Hi,

Thanks for the code. I was using ROOT 6.32.02.

Cheers,
Danilo