def est_angles(patch,
               spec='EB',
               bn=50,
               spc='',
               lmin=200,
               lmax=2048,
               doreal='True',
               dearot='False',
               sn=200,
               nobb=False,
               diag=False,
               disp=''):
    if spec == 'TB': m = 5
    if spec == 'EB': m = 6
    __, f = filename_init(doreal=doreal, PSA='s14&15_' + patch, dearot=dearot)
    mb = bins.multipole_binning(bn, spc=spc, lmin=lmin, lmax=lmax)
    scl = np.array([
        np.loadtxt(f.cli[i], unpack=True, usecols=(2, 3, 4, m))
        for i in range(1, sn + 1)
    ])
    scb = bins.binning(scl, mb)
    ocl = np.loadtxt(f.cli[0], unpack=True, usecols=(2, 3, 4, m))
    ocb = bins.binning(ocl, mb)

    if spec == 'TB':
        st = ana.est_absangle(ocb[3, :],
                              scb[:, 3, :],
                              ocb[2, :],
                              scb[:, 2, :],
                              diag=diag,
                              x2pte=False)

    if spec == 'EB':
        if nobb:
            st = ana.est_absangle(ocb[3, :],
                                  scb[:, 3, :],
                                  ocb[0, :],
                                  scb[:, 0, :] - scb[:, 1, :],
                                  diag=diag,
                                  x2pte=False)
        else:
            st = ana.est_absangle(ocb[3, :],
                                  scb[:, 3, :],
                                  ocb[0, :] - ocb[1, :],
                                  scb[:, 0, :] - scb[:, 1, :],
                                  diag=diag,
                                  x2pte=False)

    #print(disp+', obs:',np.around(-st.oA,decimals=3),'[deg]', 'std', np.around(st.sA,decimals=3), '[deg]')
    print(disp + ', obs:', np.around(st.oA, decimals=3), '[deg]', 'std',
          np.around(st.sA, decimals=3), '[deg]', 'PTE',
          np.around(st.p, decimals=3))
示例#2
0
def load_binned_tt(mb,
                   dtype='dr2_smica',
                   fltr='cinv',
                   cmask='Lmask',
                   bhe=['lens'],
                   snmax=100):

    # filename
    d = prjlib.data_directory()
    p = prjlib.init_analysis(snmax=snmax, dtype=dtype, fltr=fltr, wtype=cmask)
    qobj = quad_func.quad(stag=p.stag,
                          root=d['root'],
                          ids=p.ids,
                          qtype='tau',
                          bhe=bhe,
                          rlmin=100,
                          rlmax=2048)

    # optimal filter
    al = (np.loadtxt(qobj.f['TT'].al)).T[1]
    vl = al / np.sqrt(qobj.l + 1e-30)

    # binned spectra
    mtt, __, stt, ott = bn.binned_spec(mb,
                                       qobj.f['TT'].cl,
                                       cn=1,
                                       doreal=True,
                                       opt=True,
                                       vl=vl)

    # noise bias
    nb = bn.binning((np.loadtxt(qobj.f['TT'].n0bs)).T[1], mb, vl=vl)
    rd = np.array([(np.loadtxt(qobj.f['TT'].rdn0[i])).T[1] for i in p.rlz])
    rb = bn.binning(rd, mb, vl=vl)

    # debias
    ott = ott - rb[0] - nb / (qobj.mfsim)
    stt = stt - rb[1:, :] - nb / (qobj.mfsim - 1)

    # sim mean and std
    mtt = mtt - np.mean(rb[1:, :], axis=0) - nb / (qobj.mfsim - 1)
    vtt = np.std(stt, axis=0)

    # subtract average of sim
    ott = ott - mtt

    return mtt, vtt, stt, ott
示例#3
0
 def __init__(self, all_data, ins, oot, columnX, columnY):
     self.fi = feature_inspection.feature_inspection()
     self.bi = binning.binning()
     self.mi = model_inspection.model_inspection()
     self.all_data = all_data
     self.ins = ins
     self.oot = oot
     self.columnX = columnX
     self.columnY = columnY
示例#4
0
def spike_matrix(spt_mat,trig,time_window,cluster_list=None,dmr=1,shuffled=False):
    if cluster_list is not None:
        N_clu_list=len(cluster_list)
    else:
        N_clu_list=spt_mat.shape[0]
    spike_mat=[]
    if cluster_list is None:
        for c in range(N_clu_list):
            spike_mat.append(binning(spt_mat,trig,time_window,spt_mat[c][0][0][0],dmr))

    else:
        for c in range(N_clu_list):
            spike_mat.append(binning(spt_mat,trig,time_window,cluster_list[c],dmr))


    spike_mat=np.array(spike_mat)
    #Shuffle spike_matrix
    if shuffled==True:
        for c in range(N_clu_list):
            perm=np.random.permutation(spike_mat.shape[1])
            spike_mat[c,:]=spike_mat[c,perm]

    return spike_mat
示例#5
0
def load_spec(qobj, mb, rlz=None, cn=1, outN0=False):
    # load data
    l, al = (np.loadtxt(qobj.f['TT'].al, usecols=(0, cn))).T
    l, n0 = (np.loadtxt(qobj.f['TT'].n0bs, usecols=(0, cn))).T
    if rlz is None:
        #rd = n0.copy()
        rd = (np.loadtxt(qobj.f['TT'].rdn0[0])).T[cn]
        fcl = qobj.f['TT'].cl[:101]
    else:
        rd = np.array([(np.loadtxt(qobj.f['TT'].rdn0[i])).T[cn] for i in rlz])
        fcl = [qobj.f['TT'].cl[i] for i in rlz]
    # binning
    vl = al / np.sqrt(l + .5 + 1e-30)
    nb = bn.binning(n0, mb, vl=vl)
    rb = bn.binning(rd, mb, vl=vl)
    mkk, __, skk, okk = bn.binned_spec(mb,
                                       fcl,
                                       cn=cn,
                                       doreal=True,
                                       opt=True,
                                       vl=vl)
    # obs and sim kk
    if rlz is None:
        Okk = okk - rb - mkk / 100.
        Skk = skk - nb - mkk / 99.
    else:
        Okk = okk - rb[0] - mkk / 100.
        Skk = skk - rb[1:, :] - mkk / 99.
    # mean and var of sim kk
    Mkk = np.mean(Skk, axis=0)
    Vkk = np.std(Skk, axis=0)
    # output
    if outN0:
        return Mkk, Vkk, Skk, Okk, nb
    else:
        return Mkk, Vkk, Skk, Okk
示例#6
0
def exp_xsec():
    # prepare the set of bin boundaries to run over, only 1 bin in case of the inclusive measurement
    observableBins, doubleDiff = binning(opt.OBSNAME)
    ## Run for the given observable
    obsName = opt.OBSNAME
    _th_MH = opt.THEORYMASS
    print 'Running Fiducial XS computation - '+obsName+' - bin boundaries: ', observableBins, '\n'
    print 'Theory xsec and BR at MH = '+_th_MH

    _temp = __import__('higgs_xsbr_13TeV', globals(), locals(), ['higgs_xs','higgs4l_br'], -1)
    higgs_xs = _temp.higgs_xs
    higgs4l_br = _temp.higgs4l_br
    fname = 'inputs_sig_'+obsName+'_'+opt.YEAR
    if opt.DOHIG: fname = fname + '_HIG19001'
    _temp = __import__(fname, globals(), locals(), ['acc'], -1)
    acc = _temp.acc
    XH = []
    nBins = len(observableBins)
    xs = {}
    for obsBin in range(nBins-1):
        XH.append(0.0)
        # if('mass4l' not in obsName):
        for channel in ['4e','4mu','2e2mu']:
            XH_fs = higgs_xs['ggH_'+opt.THEORYMASS]*higgs4l_br[opt.THEORYMASS+'_'+channel]*acc['ggH125_'+channel+'_'+obsName+'_genbin'+str(obsBin)+'_recobin'+str(obsBin)]
            XH_fs += higgs_xs['VBF_'+opt.THEORYMASS]*higgs4l_br[opt.THEORYMASS+'_'+channel]*acc['VBFH125_'+channel+'_'+obsName+'_genbin'+str(obsBin)+'_recobin'+str(obsBin)]
            XH_fs += higgs_xs['WH_'+opt.THEORYMASS]*higgs4l_br[opt.THEORYMASS+'_'+channel]*acc['WH125_'+channel+'_'+obsName+'_genbin'+str(obsBin)+'_recobin'+str(obsBin)]
            XH_fs += higgs_xs['ZH_'+opt.THEORYMASS]*higgs4l_br[opt.THEORYMASS+'_'+channel]*acc['ZH125_'+channel+'_'+obsName+'_genbin'+str(obsBin)+'_recobin'+str(obsBin)]
            XH_fs += higgs_xs['ttH_'+opt.THEORYMASS]*higgs4l_br[opt.THEORYMASS+'_'+channel]*acc['ttH125_'+channel+'_'+obsName+'_genbin'+str(obsBin)+'_recobin'+str(obsBin)]
            XH[obsBin]+=XH_fs
        # else:
        #     XH_fs = higgs_xs['ggH_'+opt.THEORYMASS]*higgs4l_br[opt.THEORYMASS+'_'+'4l']*acc['ggH125_4l_'+obsName+'_genbin'+str(obsBin)+'_recobin'+str(obsBin)]
        #     XH_fs += higgs_xs['VBF_'+opt.THEORYMASS]*higgs4l_br[opt.THEORYMASS+'_'+'4l']*acc['VBFH125_4l_'+obsName+'_genbin'+str(obsBin)+'_recobin'+str(obsBin)]
        #     XH_fs += higgs_xs['WH_'+opt.THEORYMASS]*higgs4l_br[opt.THEORYMASS+'_'+'4l']*acc['WH125_4l_'+obsName+'_genbin'+str(obsBin)+'_recobin'+str(obsBin)]
        #     XH_fs += higgs_xs['ZH_'+opt.THEORYMASS]*higgs4l_br[opt.THEORYMASS+'_'+'4l']*acc['ZH125_4l_'+obsName+'_genbin'+str(obsBin)+'_recobin'+str(obsBin)]
        #     XH_fs += higgs_xs['ttH_'+opt.THEORYMASS]*higgs4l_br[opt.THEORYMASS+'_'+'4l']*acc['ttH125_4l_'+obsName+'_genbin'+str(obsBin)+'_recobin'+str(obsBin)]
        #     XH[obsBin]+=XH_fs

        _obsxsec = XH[obsBin]

        print 'Bin ', obsBin, '\t SigmaBin', obsBin, ' = ', _obsxsec
        xs['SigmaBin'+str(obsBin)] = _obsxsec

    with open('../inputs/xsec_'+obsName+'.py', 'w') as f:
        f.write('xsec = '+str(xs)+' \n')
示例#7
0
def n0_template(aobj,
                iobj,
                mb,
                quad=['TB', 'EB', 'BB']):  # template for non-zero biref
    bobj = local.init_analysis(freq=aobj.freq,
                               dtype=aobj.dtype,
                               wind=aobj.wind,
                               fltr=aobj.fltr,
                               biref=1.)
    robj = init_quad(bobj.snmax,
                     ids=bobj.ids,
                     rlz=bobj.rlz,
                     stag=bobj.stag,
                     qtypes=['ilens'],
                     rlmin=100,
                     rlmax=2048)
    yobj = cross(robj['ilens'], iobj, bobj.ids)
    Mkk = bn.binning(aobj.ckk, mb) * np.pi / 180.
    tcb = binned_spec(mb, bobj, robj, yobj, 3, doreal=False)[0]
    for q in quad:
        tcb[q] = (tcb[q] - Mkk) * .4
    return tcb
def NLSADmg(ea_t,k_t,H,m,n_l,dmax,theta_crit):
    #normalize
    ea = ea_t/n_l
    k = k_t/n_l
    
    #convert theta to radians
    theta_crit = theta_crit*math.pi/180
    
    #generate list of random numbers
    R = [random() for x in range(n_l)]
    #for testing purposes
    #R = linspace(.3,.9,n_l)
    #pseudo-random 5-link
    #R = [0.1406236293192208, 0.557452455836349, 0.4018884612118805, 0.8610494090625574, 0.005928894753714831]
    
    
    #create length distribution
    def length_distribution(r):
        l = [H*((math.log(1/num)/math.log(2))**(1.0/m)) for num in r]
        L = [H*(1-math.exp(-num)) for num in l]
        return L
    
    #if binning is applied
    if bing:
        #apply binning
        W_b,r_b,n = binning.binning(R,i_max)
        #find length distribution
        L = length_distribution(r_b)
        #find average length
        l_avg = length_distribution(R)
        L_avg = mean(l_avg)
    #if binning is not applied
    else:
        #find length distribution
        L = length_distribution(R)
        #find average length
        L_avg = mean(L)
        n = n_l
    
    
    #setup for force calculations
    
    #initialize displacement list
    d = [0]
    ldng = 1 #set whether loading (1) or unloading (0)
    #initialize y-values
    y = [[0]*n]
    y_avg = [0]
    #initialize total force list
    P = [0]
    P_avg = [0]
    
    #set indicator for whether links have buckled broken: 0 = no, 1 = buckling, 2 = completely collapsed
    c = [0]*n
    c_avg = 0
    #set indicator for whether links have broken: 0 = no, 1 = yes
    b = [0]*n
    b_avg = 0
    
    #find critical buckling values
    F_crit = [k*Li/4 for Li in L]
    F_crit_avg = k*L_avg/4
    
    #define stuff for the newton function
    F_old = F_crit #initial guesses
    F_old_avg = F_crit_avg #initial guess for average
    #define function
    def g(f,d,L,k,H,ea):
        return L*(1-(4*f)/(k*L)) + (H-L)*math.tanh(f/ea) - d
    #define derivative of function
    def gprime(f,d,L,k,H,ea):
        return -4/k + ((H-L)/ea)*(1-(math.tanh(f/ea))**2)
    
    
    #calculate force at each displacement value (except the last, because that one's infinity)
    i = 1 #set counter
    #loop will continue until d comes back up to its starting position, or until it goes through 100000 iterations
    #(to make sure it'll stop even if it screws up)
    while i <= 100000:
        #set new d value (incrementing by thousandths of H)
        #if not enough links have broken yet:
        if d[i-1] >= dmax:
            ldng = 0
        if save_ani:
            if ldng == 1: #if loading    
                #increment d forward
                d.append(i*.005*H)
            else: #if unloading
                #increment d backward
                d.append(d[i-1]-.005*H)
        else:
            if ldng == 1: #if loading    
                #increment d forward
                d.append(i*.001*H)
            else: #if unloading
                #increment d backward
                d.append(d[i-1]-.001*H)
        #stop if d has displaced further than H
        if d[i] >= H:
            #make d the same length as the force lists
            d.pop()
            break
        #stop if d becomes negative
        if d[i] < 0:
            #make d the same length as the force lists
            d.pop()
            break
        #add next list of y-values
        y.append([])        
        #initialize force list
        F = [0]*n
        #for each link
        for j in range(n):
            #if link hasn't broken:
            if b[j] == 0:
                #if the link hasn't buckled:
                #check to see if displacement is past top of link
                if c[j] == 0 and d[i] >= (H-L[j]):
                    #if so, set indicator to buckling
                    c[j] = 1
                
                #if it hasn't buckled
                if c[j] == 0:
                    #calculate force in link
                    F[j] = ea*math.atanh(d[i]/(H-L[j]))
                    y[i].append(0)
                    #check to see if link has buckled
                    if F[j] >= F_crit[j]:
                        c[j] = 1 #set indicator
                #if it's currently buckling
                elif c[j] == 1:
                    #numerically calculate link force
                    guess = F_old[j]
                              
                    F[j] = MyRootFinding.newton_raphson(g,guess,gprime,args=(d[i],L[j],k,H,ea),tol=.001,Imax=10*len(d),zerotol=.01)
                    #assign current value as next guess value
                    F_old[j] = F[j]         
                    #find and store y value
                    y[i].append(L[j] - 4*F[j]/k)
                    if y[i][j] > L[j]:
                        y[i][j] = L[j]
                    #if still loading
                    #(if not, d is decreasing, and the remaining links aren't going to break and don't need to be checked)
                    if ldng == 1:
                        #check if link has broken
                        #small links will have very large jumps in y, so only calculate acos if theta < 90 degrees
                        if (L[j]-y[i][j])/L[j] <= 1 and (L[j]-y[i][j])/L[j] >= -1:
                            theta = math.acos((L[j]-y[i][j])/L[j])
                        else: #otherwise theta should be 90 degrees
                            theta = math.pi/2 
                               
                        if theta >= theta_crit:
                            b[j] = 1
                            #check whether top spring has enough room to extend fully
                            if d[i]>L[j]:
                                c[j] = 2
                        #check if link has completely collapsed
                        if y[i][j] >= L[j]:
                            c[j] = 2 #set indicator
                            F[j] = ea*math.atanh((d[i] - L[j])/(H - L[j]))       
                    else: #if unloading
                        #check if the links have unbent again
                        if y[i][j] < 0:
                            y[i][j] = 0
                            #set force correctly
                            F[j] = ea*math.atanh(d[i]/(H-L[j]))
                            c[j] = 0        
                #if it's completely collapsed
                else:
                    #calculate link force
                    F[j] = ea*math.atanh((d[i] - L[j])/(H - L[j]))
                    #store y
                    y[i].append(L[j])
            else: #if link has broken
                #if top spring is not fully extended
                if c[j] == 2:
                    #calculate link force
                    F[j] = ea*math.atanh((d[i] - L[j])/(H - L[j]))
                    #store y
                    y[i].append(L[j])
                    #check if spring has fully extended
                    if d[i]<=L[j]:
                        #set indicator
                        c[j] = 1
                elif c[j] == 1: #if top spring is fully extended
                    #force is zero
                    F[j] = 0
                    #store y value
                    y[i].append(d[i])
                    #see if spring is being compressed
                    if d[i] > L[j]:
                        #set indicator
                        c[j] = 2
                else:
                    print "spring %d is extending" % j         
        
    
        #sum forces to find total force
        #if binning is applied
        if bing:
            Psum = 0 #initialize force sum
            for j in range(n):
                Psum += F[j]*W_b[j]*n_l #sum weighted forces
            P.append(Psum)    
        #if binning is not applied        
        else:    
            P.append(sum(F))
            
        #increment counter
        i += 1    
        
    return d,P,F_crit_avg    
示例#9
0
def book(out_name, hs=[]):
    bins = binning()
    h = ROOT.TH1F(out_name, '', len(bins)-1, bins)
    hs.append(h)
    return h
def binned_cl_rlz(fcl, sn0, sn1, mb0, mb1=None, cn=1):
    scl = np.array(
        [np.loadtxt(fcl[i], unpack=True)[cn] for i in range(sn0, sn1 + 1)])
    return bins.binning(scl, mb0, mb1)
def NLSA(ea_t, k_t, H, m, n_l):
    #normalize
    ea = ea_t / n_l
    k = k_t / n_l

    #generate list of random numbers
    if testing:
        #for testing purposes
        R = linspace(.3, .8, n_l)
        #pseudo-random 5-link
        #R = [0.1406236293192208, 0.557452455836349, 0.4018884612118805, 0.8610494090625574, 0.005928894753714831]
    else:
        #generate list of random numbers
        R = [random() for x in range(n_l)]

    #create length distribution
    def length_distribution(r):
        l = [H * ((math.log(1 / num) / math.log(2))**(1.0 / m)) for num in r]
        L = [H * (1 - math.exp(-num)) for num in l]
        return L

    #if binning is applied
    if bing:
        #apply binning
        W_b, r_b, n = binning.binning(R, i_max)
        #find length distribution
        L = length_distribution(r_b)
        #find average length
        l_avg = length_distribution(R)
        L_avg = mean(l_avg)
    #if binning is not applied
    else:
        #find length distribution
        L = length_distribution(R)
        #L=[.5]
        #find average length
        L_avg = mean(L)
        n = n_l

    #setup for force calculations

    #make displacement distribution
    if save_ani:
        d = linspace(0, H, 200)
    else:
        d = linspace(0, H, 1000)
    #initialize y-values
    y = [[0] * n for x in range(len(d) - 1)]
    y_avg = [0] * (len(d) - 1)
    #initialize total force list
    P = [0] * (len(d) - 1)
    P_avg = [0] * (len(d) - 1)
    #set indicator for whether links have buckled: 0 = no, 1 = in progress, 2 = yes
    c = [0] * n
    c_avg = 0

    #find critical buckling values
    F_crit = [k * Li / 4 for Li in L]
    F_crit_avg = k * L_avg / 4

    #define stuff for the newton function
    F_old = F_crit  #initial guesses
    F_old_avg = F_crit_avg  #initial guess for average

    #define function
    def g(f, d, L, k, H, ea):
        return L * (1 - (4 * f) / (k * L)) + (H - L) * math.tanh(f / ea) - d

    #define derivative of function
    def gprime(f, d, L, k, H, ea):
        return -4 / k + ((H - L) / ea) * (1 - (math.tanh(f / ea))**2)

    #calculate force at each displacement value (except the last, because that one's infinity)
    for i in range(len(d) - 1):
        #initialize force list
        F = [0] * n
        #for each link
        for j in range(n):
            #if the link hasn't buckled:
            #check to see if displacement is past top of link
            if c[j] == 0 and d[i] >= (H - L[j]):
                #if so, set indicator to buckling
                c[j] = 1

            #if it hasn't buckled
            if c[j] == 0:
                #calculate force in link
                F[j] = ea * math.atanh(d[i] / (H - L[j]))
                y[i][j] = 0
                #check to see if link has buckled
                if F[j] >= F_crit[j]:
                    c[j] = 1  #set indicator
            #if it's currently buckling
            elif c[j] == 1:
                #numerically calculate link force
                guess = F_old[j]

                F[j] = MyRootFinding.newton_raphson(g,
                                                    guess,
                                                    gprime,
                                                    args=(d[i], L[j], k, H,
                                                          ea),
                                                    tol=.001,
                                                    Imax=10 * len(d),
                                                    zerotol=.01)
                #assign current value as next guess value
                F_old[j] = F[j]
                #find and store y value
                y[i][j] = L[j] - 4 * F[j] / k
                #check if link has completely collapsed
                if y[i][j] >= L[j]:
                    c[j] = 2  #set indicator
                    F[j] = ea * math.atanh((d[i] - L[j]) / (H - L[j]))
            #if it's completely collapsed
            else:
                #calculate link force
                F[j] = ea * math.atanh((d[i] - L[j]) / (H - L[j]))
                #store y
                y[i][j] = L[j]

        #sum forces to find total force
        #if binning is applied
        if bing:
            P[i] = 0  #initialize force sum
            for j in range(n):
                P[i] += F[j] * W_b[j] * n_l  #sum weighted forces
        #if binning is not applied
        else:
            P[i] = sum(F)

    return d, P, F_crit_avg
示例#12
0
    signals_original = [root+opt.HYP for root in signals_original]
    signals = [root+opt.HYP for root in signals]
else:
    signals_original = ['VBFH125', 'ggH125', 'ttH125', 'WminusH125', 'WplusH125', 'ZH125']
    signals = ['ggH125', 'VBFH125', 'WH125', 'ZH125', 'ttH125']
eos_path_sig = path['eos_path_sig']
key = 'candTree'
key_failed = 'candTree_failed'

if (opt.YEAR == '2016'): years = ['2016post']
if (opt.YEAR == '2017'): years = ['2017']
if (opt.YEAR == '2018'): years = ['2018']
if (opt.YEAR == 'Full'): years = ['2016post','2017','2018']


obs_bins, doubleDiff = binning(opt.OBSNAME)
if doubleDiff:
    obs_name = opt.OBSNAME.split(' vs ')[0]
    obs_name_2nd = opt.OBSNAME.split(' vs ')[1]
    obs_name_2d = opt.OBSNAME
else:
    obs_name = opt.OBSNAME

_temp = __import__('observables', globals(), locals(), ['observables'], -1)
observables = _temp.observables
print(observables)
if doubleDiff:
    obs_reco = observables[obs_name_2d]['obs_reco']
    obs_reco_2nd = observables[obs_name_2d]['obs_reco_2nd']
    obs_gen = observables[obs_name_2d]['obs_gen']
    obs_gen_2nd = observables[obs_name_2d]['obs_gen_2nd']
示例#13
0
lumidict2['qqH_hww'] = 4.2e-08
lumidict2['LFV200'] = 1.694e-06
lumidict2['LFV300'] = 1.33345743863e-07
lumidict2['LFV450'] = 4.65541809702e-08
lumidict2['LFV600'] = 2.04664734848e-08
lumidict2['LFV750'] = 9.93800000005e-09
lumidict2['LFV900'] = 5.37000000001e-09
lumidict2['QCD_mc'] = 0.013699241892

lumidict2['WG'] = 1.56725042226e-06
lumidict2['W'] = 1.56725042226e-06
lumidict2['T'] = 5.23465826064e-06
lumidict2['QCD'] = float(1.0) / float(args.Lumi)

#col_vis_mass_binning=array.array('d',(range(0,190,20)+range(200,480,30)+range(500,990,50)+range(1000,1520,100)))
col_vis_mass_binning = binning.binning('colmass')
met_vars_binning = binning.binning('met')
pt_vars_binning = binning.binning('pt')

variable_list = [
    ('BDT_value', 'BDT_value', 1),
    ('h_collmass_pfmet', 'M_{coll}(e#mu) (GeV)', col_vis_mass_binning),
    ('mPt', 'p_{T}(mu) (GeV)', pt_vars_binning),
    ('mEta', 'eta(mu)', 1),
    ('mPhi', 'phi(mu)', 2),
    ('ePt', 'p_{T}(e) (GeV)', pt_vars_binning),
    ('eEta', 'eta(e)', 1),
    ('ePhi', 'phi(e)', 2),
    ('em_DeltaPhi', 'emu Deltaphi', 1),
    ('em_DeltaR', 'emu Delta R', 1),
    ('h_vismass', 'M_{vis} (GeV)', col_vis_mass_binning),
    0.1406236293192208, 0.557452455836349, 0.4018884612118805,
    0.8610494090625574, 0.005928894753714831
]


#create length distribution
def length_distribution(r):
    l = [H * ((math.log(1 / num) / math.log(2))**(1.0 / m)) for num in r]
    L = [H * (1 - math.exp(-num)) for num in l]
    return L


#if binning is applied
if bing:
    #apply binning
    W_b, r_b, n = binning.binning(R, i_max)
    #find length distribution
    L = length_distribution(r_b)
    #find average length
    l_avg = length_distribution(R)
    L_avg = mean(l_avg)
#if binning is not applied
else:
    #find length distribution
    L = length_distribution(R)
    #find average length
    L_avg = mean(L)
    n = n_l

#setup for force calculations
def Analysis(ea_t, k_t, H, Wm, n_l, d, i_max, theta_crit, F_slide, c_dash, m,
             g, dt, t_stop, dyn, damage, plasticity, dashpot_par, dashpot_ser,
             bing, testing):
    #This function performs the main analysis
    #inputs: all basic, damage, and dynamic parameters, except steps.
    #        list of displacements (d)
    #        all model options
    #outputs: list of force values (P)
    #         list of average force values (P_avg)
    #         list of displacements for the top of the link (y)
    #         critical force for the averate length (F_crit_avg)
    #         list of link lengths (L)

    #normalize ea and k
    ea = ea_t / n_l
    k = k_t / n_l

    #generate random numbers

    if testing:
        #for testing purposes
        R = [
            0.1406236293192208, 0.557452455836349, 0.4018884612118805,
            0.8610494090625574, 0.005928894753714831
        ]
        #R = linspace(.3*H,.8*H,n_l)
        #R = [0.1406236293192208]
    else:
        #generate list of random numbers
        R = [random() for x in range(n_l)]

    #create list of link lengths

    #function to create length distribution
    def length_distribution(r):
        #apply Weibull distribution
        l = [((math.log(1 / num) / math.log(2))**(1.0 / Wm)) for num in r]
        #apply exponential distribution to Weibull distribution
        L = [H * (1 - math.exp(-num)) for num in l]
        return L

    #if binning is applied
    if bing:
        #apply binning to the random number distribution, set number of links to calculate to the new binned number
        W_b, r_b, n = binning.binning(R, i_max)
        #find length distribution
        L = length_distribution(r_b)
        #find average length
        l_avg = length_distribution(R)
        L_avg = mean(l_avg)
    #if binning is not applied
    else:
        #find length distribution
        L = length_distribution(R)
        #find average length
        L_avg = mean(L)
        #set number of links to calculate to the number of links specified
        n = n_l

    #initialize lists

    #y lists
    y = [[0] * n for x in range(len(d))]
    y_avg = [0] * (len(d))

    #P lists
    P = [0] * (len(d))
    P_avg = [0] * (len(d))

    #indicators
    #for buckling: 0 = unbuckled, 1 = buckling, 2 = collapsed
    c = [0] * n
    c_avg = 0
    #for breaking: 0 = unbroken, 1 = broken
    b = [0] * n
    b_avg = 0

    #find critical buckling values
    F_crit = [k * Li / 4 for Li in L]
    F_crit_avg = k * L_avg / 4

    #convert theta_crit to radians
    theta_crit = theta_crit * math.pi / 180.0

    #find critical distance for sliding for plasticity
    if plasticity:
        x_crit = F_slide / k
        #initialize distances for plasticity
        x_plas = [0] * n
        x = [0] * n
        x_avg = 0
        x_plas_avg = 0
    elif dashpot_par:
        #initialize x distance
        x = [0] * n
        x_avg = 0
        #initialize x rate of change
        dx = [0] * n
        dx_avg = 0
    elif dashpot_ser:
        #initialize x distance
        x = [0] * n
        x_avg = 0
        #initialize the displacement of the dashpot
        x_dash = [0] * n
        x_dash_avg = 0

    #set up stuff for root finding if not using dynamic analysis
    if not dyn:
        #if plasticity is not applied
        if not plasticity:
            #set initial root guesses
            F_old = F_crit  #initial guesses
            F_old_avg = F_crit_avg  #initial guess for average

            #define function to find root of
            def root_g(f, d, L, k, H, ea):
                return L * (1 - (4 * f) /
                            (k * L)) + (H - L) * math.tanh(f / ea) - d

            #define derivative of function
            def root_gprime(f, d, L, k, H, ea):
                return -4 / k + ((H - L) / ea) * (1 - (math.tanh(f / ea))**2)

        #if placticity is applied
        else:
            #define function to find root of
            def root_g(y, d, L, k, H, ea, x_plas):
                return -ea * math.atanh(
                    (d - y) /
                    (H - L)) + k * (L -
                                    y) * (.25 - x_plas /
                                          (2 * math.sqrt(2 * L * y - y**2)))

    #set up stuff for ODE solving if using dynamic analysis
    else:
        #initialize velocity
        v = [0] * n
        v_avg = 0

    #calculate force at each displacement value
    for i in range(len(d)):

        #initialize list of link forces for this displacement
        F = [0] * n

        #for each link-------------------------------------------------------------------------------
        for j in range(n):

            #if the link isn't buckled, check to see if the displacement has jumped past the top of the link
            if c[j] == 0 and d[i] >= H - L[j]:
                #if so, change the link to buckling
                c[j] = 1

            #if the link isn't buckled
            if c[j] == 0:  #-----------------------------------------------------

                #calculate the force in the link
                F[j] = ea * math.atanh(d[i] / (H - L[j]))
                #set y
                y[i][j] = 0

                #check if the link has buckled
                #if not broken
                if b[j] == 0:
                    #for dynamics
                    if F[j] + m * g >= F_crit[j] and dyn:

                        #set indicator to buckling
                        c[j] = 1
                    #for quasistatic
                    elif F[j] >= F_crit[j] and (not dyn):

                        #set indicator to buckling
                        c[j] = 1
                #if broken
                else:
                    #for dynamics
                    if F[j] + m * g >= 0 and dyn:
                        #set indicator to buckling
                        c[j] = 1
                    #for quasistatic
                    elif F[j] >= 0 and (not dyn):
                        #set indicator to buckling
                        c[j] = 1

            #if the link is buckling
            elif c[j] == 1:  #--------------------------------------------------------

                #calculate the force in the link
                #for quasistatic
                if not dyn:
                    #if the link isn't broken
                    if b[j] == 0:

                        #set zerotol
                        if L[j] < .3:
                            ztol = .1
                        else:
                            ztol = .01

                        #find the root
                        if not plasticity:
                            #set function arguments
                            args = (d[i], L[j], k, H, ea)
                            #find root
                            F[j] = MyRootFinding.newton_raphson(root_g,
                                                                F_old[j],
                                                                root_gprime,
                                                                args=args,
                                                                tol=.001,
                                                                Imax=10 *
                                                                len(d),
                                                                zerotol=ztol)
                        else:
                            #find spring displacement
                            d_s = x[j] - x_plas[j]
                            #set function arguments
                            args = (d[i], L[j], k, H, ea, x_plas[j])
                            #find boundaries for bisection method
                            #set lower boundary to either 0 or the smallest number for atanh
                            if d[i] - H + L[j] < 0:
                                b_low = .0001
                            else:
                                b_low = (d[i] - H + L[j]) * 1.0001
                            #set upper boundary to the largest number for atanh
                            b_high = (H - L[j] + d[i]) * .9999
                            y[i][j] = MyRootFinding.bisection(root_g,
                                                              b_low,
                                                              b_high,
                                                              args=args)

                        #Find other required values
                        if plasticity:
                            #store y value
                            #find force
                            F[j] = ea * math.atanh(
                                (d[i] - y[i][j]) / (H - L[j]))
                            #find new x
                            x[j] = math.sqrt(2 * L[j] * y[i][j] -
                                             y[i][j]**2) / 2
                            #find new x_plas if x_plas is changing
                            if d_s > x_crit:
                                x_plas[j] = x[j] - x_crit
                            elif d_s < -x_crit:
                                x_plas[j] = x[j] + x_crit
                        else:
                            #assign current value as next guess value, to be more accurate and help prevent diverging
                            F_old[j] = F[j]
                            #find and store y value
                            y[i][j] = L[j] - 4 * F[j] / k

                    #if the link is broken
                    else:
                        #the side spring force is 0, so the applied force is also 0
                        F[j] = 0
                        #set y value
                        y[i][j] = d[i]

                #for dynamic
                else:
                    #solve ODE for y with 4th order Runge Kutta method

                    #if the link isn't broken
                    if b[j] == 0:
                        if dashpot_par:
                            #save previous x value
                            xold = x[j]
                            #find final argument value
                            fin_arg = -c_dash * dx[j] / k
                            #run Runge Kutta method for plasticity with fin_arg instead of x_plas to find y and the velocity
                            y[i][j], v[j] = RK4Dyn.RK4_plaslink(
                                dt, d[i - 1], d[i], y[i - 1][j], v[j], H, L[j],
                                k, ea, m, g, fin_arg)
                            #find new x
                            if y[i][j] < 0:
                                x[j] = 0
                            elif y[i][j] > L[j]:
                                x[j] = L[j] / 2
                            else:
                                x[j] = math.sqrt(2 * L[j] * y[i][j] -
                                                 y[i][j]**2) / 2
                            #find new dx
                            dx[j] = (x[j] - xold) / dt

                        elif dashpot_ser:
                            #run Runge Kutta method for plasticity with x_dash instead of x_plas to find y and the velocity
                            y[i][j], v[j] = RK4Dyn.RK4_plaslink(
                                dt, d[i - 1], d[i], y[i - 1][j], v[j], H, L[j],
                                k, ea, m, g, x_dash[j])
                            #get new x
                            if y[i][j] < 0:
                                x[j] = 0
                            elif y[i][j] > L[j]:
                                x[j] = L[j] / 2
                            else:
                                x[j] = math.sqrt(2 * L[j] * y[i][j] -
                                                 y[i][j]**2) / 2
                            #use Runge Kutta method to get new x_dash
                            x_dash[j] = RK4Dyn.RK4_dashser(
                                x_dash[j], dt, k, x[j], c_dash)

                        elif plasticity:
                            #find spring displacement
                            d_s = x[j] - x_plas[j]
                            #run Runge Kutta method for plasticity to find y and the velocity
                            y[i][j], v[j] = RK4Dyn.RK4_plaslink(
                                dt, d[i - 1], d[i], y[i - 1][j], v[j], H, L[j],
                                k, ea, m, g, x_plas[j])
                            #find new x
                            if y[i][j] < 0:
                                x[j] = 0
                            elif y[i][j] > L[j]:
                                x[j] = L[j] / 2
                            else:
                                x[j] = math.sqrt(2 * L[j] * y[i][j] -
                                                 y[i][j]**2) / 2
                            #find new x_plas if x_plas is changing
                            if d_s > x_crit:
                                x_plas[j] = x[j] - x_crit
                            elif d_s < -x_crit:
                                x_plas[j] = x[j] + x_crit
                        else:
                            #run regular Runge Kutta method to find y and the velocity
                            y[i][j], v[j] = RK4Dyn.RK4_link(
                                dt, d[i - 1], d[i], y[i - 1][j], v[j], H, L[j],
                                k, ea, m, g)

                    else:
                        #run Runge Kutta method to find y and the velocity, with k=0 for breakage
                        y[i][j], v[j] = RK4Dyn.RK4_link(
                            dt, d[i - 1], d[i], y[i - 1][j], v[j], H, L[j], 0,
                            ea, m, g)
                    #correct v value if necessary to prevent divergence
                    if v[j] > 1000 or math.isnan(v[j]):
                        v[j] = 1000

                    #correct y value if necessary
                    #make sure the displacement doesn't pass the top of the link
                    if d[i] - y[i][j] >= H - L[j]:
                        y[i][j] = d[i] - (H - L[j]) * .999999
                    #make sure the spring doesn't stretch too long
                    if d[i] - y[i][j] <= L[j] - H:
                        y[i][j] = d[i] - (L[j] - H) * .999999

                    #calculate force
                    F[j] = ea * math.atanh((d[i] - y[i][j]) / (H - L[j]))

                #if damage is turned on and the link hasn't broken, check to see if it has
                if b[j] == 0 and damage:
                    #calculate theta
                    #if y steps below zero, making the argument for acos > 1, make sure theta is zero
                    if y[i][j] < 0:
                        theta = 0
                    else:
                        theta = math.acos((L[j] - y[i][j]) / L[j])
                    #check if theta is larger than the breaking angle
                    if theta >= theta_crit:
                        #set to broken
                        b[j] = 1

                #check to see if the link has completely collapsed
                if y[i][j] >= L[j]:
                    #set y correctly
                    y[i][j] = L[j]

                    #set indicator to collapsed
                    c[j] = 2
                    #recalculate force to reflect collapse
                    F[j] = ea * math.atanh((d[i] - L[j]) / (H - L[j]))
                    #set velocity to zero if running dynamics
                    if dyn:
                        v[j] = 0

                #check to see if the link has unbuckled
                if not plasticity:
                    if y[i][j] <= 0:
                        #set y correctly
                        y[i][j] = 0
                        #set indicator to unbuckled
                        c[j] = 0
                        #recalculate force to reflect unbuckling
                        #if the atanh argument is >= 1
                        if d[i] >= (H - L[j]):
                            #make the force as large as it can be
                            F[j] = ea * math.atanh(.9999999999999999)
                        #otherwise calculate the force normally
                        else:
                            F[j] = ea * math.atanh(d[i] / (H - L[j]))
                else:
                    if (y[i][j] > 10 * y[i - 1][j] and y[i - 1][j] != 0
                            and not dyn) or (y[i][j] < 0 and dyn):
                        #set y correctly
                        y[i][j] = 0
                        #set indicator to unbuckled
                        c[j] = 0
                        #recalculate force to reflect unbuckling
                        #if the atanh argument is >= 1
                        if d[i] >= (H - L[j]):
                            #make the force as large as it can be
                            F[j] = ea * math.atanh(.9999999999999999)
                        #otherwise calculate the force normally
                        else:
                            F[j] = ea * math.atanh(d[i] / (H - L[j]))

            #if the link is completely collapsed
            elif c[j] == 2:  #------------------------------------------------------------------

                #store y
                y[i][j] = L[j]

                #calculate the force in the link
                #if the atanh argument <= -1
                if (d[i] - L[j]) / (H - L[j]) <= -1:
                    #make the force as small as possible
                    F[j] = ea * math.atanh(-.9999999999999999)
                #otherwise calculate normally
                else:
                    F[j] = ea * math.atanh((d[i] - L[j]) / (H - L[j]))

                #check to see if the link is uncollapsing
                #for dynamics, check if the spring force will overcome gravity
                if F[j] < -m * g and dyn:
                    #set indicator to buckling
                    c[j] = 1
                #for quasistatic, check if the spring force < 0
                elif F[j] < 0 and (not dyn):
                    #set indicator to buckling
                    c[j] = 1

        #calculate total force

        #if binning is applied
        if bing:
            P[i] = 0  #initialize force sum
            for j in range(n):
                P[i] += F[j] * W_b[j] * n_l  #sum weighted forces
        #if binning is not applied
        else:
            P[i] = sum(F)

        #for the average force------------------------------------------------------------------------------------

        #if the link isn't buckled, check to see if the displacement has jumped past the top of the link
        if c_avg == 0 and d[i] >= H - L_avg:
            #if so, change the link to buckling
            c_avg = 1

        #if the link isn't buckled
        if c_avg == 0:  #-----------------------------------------------------

            #calculate the force in the link
            F_avg = ea * math.atanh(d[i] / (H - L_avg))
            #set y
            y_avg[i] = 0

            #check if the link has buckled
            #for dynamics
            if F_avg + m * g >= F_crit_avg and dyn:
                #set indicator to buckling
                c_avg = 1
            #for quasistatic
            elif F_avg >= F_crit_avg and (not dyn):
                #set indicator to buckling
                c_avg = 1

        #if the link is buckling
        elif c_avg == 1:  #---------------------------------------------------

            #calculate the force in the link
            #for quasistatic
            if not dyn:
                #if the link isn't broken
                if b_avg == 0:

                    #set the guess
                    if plasticity:
                        if y_avg[i - 1] == 0:
                            guess = .00001
                        else:
                            guess = y_avg[i - 1]
                    else:
                        guess = F_old_avg

                    #find the root
                    if not plasticity:
                        #set function arguments
                        args = (d[i], L_avg, k, H, ea)
                        #find root
                        F_avg = MyRootFinding.newton_raphson(root_g,
                                                             guess,
                                                             root_gprime,
                                                             args=(d[i], L_avg,
                                                                   k, H, ea),
                                                             tol=.001,
                                                             Imax=10 * len(d),
                                                             zerotol=.01)
                    else:
                        #find spring displacement
                        d_s_avg = x_avg - x_plas_avg
                        #set function arguments
                        args_avg = (d[i], L_avg, k, H, ea, x_plas_avg)
                        #find boundaries for bisection method
                        #set lower boundary to either 0 or the smallest number for atanh
                        if d[i] - H + L_avg < 0:
                            b_low_avg = .0001
                        else:
                            b_low_avg = (d[i] - H + L_avg) * 1.0001
                        #set upper boundary to the largest number for atanh
                        b_high_avg = (H - L_avg + d[i]) * .9999
                        y_avg[i] = MyRootFinding.bisection(root_g,
                                                           b_low_avg,
                                                           b_high_avg,
                                                           args=args_avg)

                    #Find other required values
                    if plasticity:
                        #store y value
                        #find force
                        F_avg = ea * math.atanh(
                            (d[i] - y_avg[i]) / (H - L_avg))
                        #find new x
                        x_avg = math.sqrt(2 * L_avg * y_avg[i] -
                                          y_avg[i]**2) / 2
                        #find new x_plas if x_plas is changing
                        if d_s_avg > x_crit:
                            x_plas_avg = x_avg - x_crit
                        elif d_s_avg < -x_crit:
                            x_plas_avg = x_avg + x_crit
                    else:
                        #assign current value as next guess value, to be more accurate and help prevent diverging
                        F_old_avg = F_avg
                        #find and store y value
                        y_avg[i] = L_avg - 4 * F_avg / k

                #if the link is broken
                else:
                    #the side spring force is 0, so the applied force is also 0
                    F_avg = 0
                    #set y value
                    y_avg[i] = d[i]

            #for dynamic
            else:
                #solve ODE for y with 4th order Runge Kutta method

                #if the link isn't broken
                if b[j] == 0:
                    if dashpot_par:
                        #save previous x value
                        xold_avg = x_avg
                        #find final argument value
                        fin_arg_avg = -c_dash * dx_avg / k
                        #run Runge Kutta method for plasticity with fin_arg instead of x_plas to find y and the velocity
                        y_avg[i], v_avg = RK4Dyn.RK4_plaslink(
                            dt, d[i - 1], d[i], y_avg[i - 1], v_avg, H, L_avg,
                            k, ea, m, g, fin_arg_avg)
                        #find new x
                        if y_avg[i] < 0:
                            x_avg = 0
                        elif y_avg[i] > L_avg:
                            x_avg = L_avg / 2
                        else:
                            x_avg = math.sqrt(2 * L_avg * y_avg[i] -
                                              y_avg[i]**2) / 2
                        #find new dx
                        dx_avg = (x_avg - xold_avg) / dt

                    elif dashpot_ser:
                        #run Runge Kutta method for plasticity with x_dash instead of x_plas to find y and the velocity
                        y_avg[i], v_avg = RK4Dyn.RK4_plaslink(
                            dt, d[i - 1], d[i], y_avg[i - 1], v_avg, H, L_avg,
                            k, ea, m, g, x_dash_avg)
                        #get new x
                        if y_avg[i] < 0:
                            x_avg = 0
                        elif y_avg[i] > L_avg:
                            x_avg = L_avg / 2
                        else:
                            x_avg = math.sqrt(2 * L_avg * y_avg[i] -
                                              y_avg[i]**2) / 2
                        #use Runge Kutta method to get new x_dash
                        x_dash_avg = RK4Dyn.RK4_dashser(
                            x_dash_avg, dt, k, x_avg, c_dash)

                    elif plasticity:
                        #find spring displacement
                        d_s_avg = x_avg - x_plas_avg
                        #run Runge Kutta method for plasticity to find y and the velocity
                        y_avg[i], v_avg = RK4Dyn.RK4_plaslink(
                            dt, d[i - 1], d[i], y_avg[i - 1], v_avg, H, L_avg,
                            k, ea, m, g, x_plas_avg)
                        #find new x
                        if y_avg[i] < 0:
                            x_avg = 0
                        elif y_avg[i] > L_avg:
                            x_avg = L_avg / 2
                        else:
                            x_avg = math.sqrt(2 * L_avg * y_avg[i] -
                                              y_avg[i]**2) / 2
                        #find new x_plas if x_plas is changing
                        if d_s_avg > x_crit:
                            x_plas_avg = x_avg - x_crit
                        elif d_s_avg < -x_crit:
                            x_plas_avg = x_avg + x_crit
                    else:
                        #run Runge Kutta method to find y and the velocity
                        y_avg[i], v_avg = RK4Dyn.RK4_link(
                            dt, d[i - 1], d[i], y_avg[i - 1], v_avg, H, L_avg,
                            k, ea, m, g)

                else:
                    #run Runge Kutta method to find y and the velocity, with k=0 for breakage
                    y_avg[i], v_avg = RK4Dyn.RK4_link(dt, d[i - 1], d[i],
                                                      y_avg[i - 1], v_avg, H,
                                                      L_avg, 0, ea, m, g)

                #correct v value if necessary to prevent divergence
                if v_avg > 1000 or math.isnan(v_avg):
                    v_avg = 1000

                #correct y value if necessary
                #make sure the displacement doesn't pass the top of the link
                if d[i] - y_avg[i] >= H - L_avg:
                    y_avg[i] = d[i] - (H - L_avg) * .999999
                #make sure the spring doesn't stretch too long
                if d[i] - y_avg[i] <= L_avg - H:
                    y_avg[i] = d[i] - (L_avg - H) * .999999

                #calculate force using the calculated y value
                F_avg = ea * math.atanh((d[i] - y_avg[i]) / (H - L_avg))

            #if damage is on and the link hasn't broken, check to see if it has
            if b_avg == 0 and damage:
                #calculate theta
                #if y steps below zero, making the argument for acos > 1, make sure theta is zero
                if y_avg[i] < 0:
                    theta = 0
                else:
                    theta = math.acos((L_avg - y_avg[i]) / L_avg)
                #check if theta is larger than the breaking angle
                if theta >= theta_crit:
                    #set to broken
                    b_avg = 1

            #check to see if the link has completely collapsed
            if y_avg[i] >= L_avg:
                #set y correctly
                y_avg[i] = L_avg
                #set indicator to collapsed
                c_avg = 2
                #recalculate force to reflect collapse
                F_avg = ea * math.atanh((d[i] - L_avg) / (H - L_avg))
                #set velocity to zero if running dynamics
                if dyn:
                    v_avg = 0

            #check to see if the link has unbuckled
            if not plasticity:
                if y_avg[i] < 0:
                    #set y correctly
                    y_avg[i] = 0
                    #set indicator to unbuckled
                    c_avg = 0
                    #recalculate force to reflect unbuckling
                    F_avg = ea * math.atanh(d[i] / (H - L_avg))
            else:
                if (y_avg[i] > 10 * y_avg[i - 1] and y_avg[i - 1] != 0
                        and not dyn) or (y_avg[i] < 0 and dyn):
                    #set y correctly
                    y_avg[i] = 0
                    #set indicator to unbuckled
                    c_avg = 0
                    #recalculate force to reflect unbuckling
                    #if the atanh argument is >= 1
                    if d[i] >= (H - L_avg):
                        #make the force as large as it can be
                        F_avg = ea * math.atanh(.9999999999999999)
                    #otherwise calculate the force normally
                    else:
                        F_avg = ea * math.atanh(d[i] / (H - L_avg))

        #if the link is completely collapsed
        elif c_avg == 2:  #-----------------------------------------------------------

            #store y
            y_avg[i] = L_avg

            #calculate the force in the link
            #if the atanh argument is <= -1
            if (d[i] - L_avg) / (H - L_avg) <= -1:
                #make force as small as possible
                F_avg = ea * math.atanh(-.9999999999999999)
            #otherwise calculate force normally
            else:
                F_avg = ea * math.atanh((d[i] - L_avg) / (H - L_avg))

            #check to see if the link is uncollapsing
            #for dynamics, check if the spring force will overcome gravity
            if F_avg < -m * g and dyn:
                #set indicator to buckling
                c_avg = 1
            #for quasistatic, check if the spring force < 0
            elif F_avg < 0 and (not dyn):
                #set indicator to buckling
                c_avg = 1

        #calculate total average force
        P_avg[i] = F_avg * n_l

    return P, P_avg, y, F_crit_avg, L
#for testing purposes
#R = linspace(.3,.9,n_l)
#pseudo-random 5-link
R = [0.1406236293192208, 0.557452455836349, 0.4018884612118805, 0.8610494090625574, 0.005928894753714831]


#create length distribution
def length_distribution(r):
    l = [H*((math.log(1/num)/math.log(2))**(1.0/m)) for num in r]
    L = [H*(1-math.exp(-num)) for num in l]
    return L

#if binning is applied
if bing:
    #apply binning
    W_b,r_b,n = binning.binning(R,i_max)
    #find length distribution
    L = length_distribution(r_b)
    #find average length
    l_avg = length_distribution(R)
    L_avg = mean(l_avg)
#if binning is not applied
else:
    #find length distribution
    L = length_distribution(R)
    #find average length
    L_avg = mean(L)
    n = n_l


#setup for force calculations
示例#17
0
if doubleDiff:
    obs_reco_2nd = observables[obsname]['obs_reco_2nd']

obs_reco = observables[obsname]['obs_reco']

year    = opt.YEAR
if (opt.YEAR == '2016'): years = [2016]
if (opt.YEAR == '2017'): years = [2017]
if (opt.YEAR == '2018'): years = [2018]
if (opt.YEAR == 'Full'): years = [2016,2017,2018]

m4l_low = opt.LOWER_BOUND
m4l_high = opt.UPPER_BOUND

obs_bins, doubleDiff = binning(opt.OBSBINS)


# if not doubleDiff: #It is not a double-differential analysis
#     obs_bins = {0:(opt.OBSBINS.split("|")[1:(len(opt.OBSBINS.split("|"))-1)]),1:['0','inf']}[opt.OBSBINS=='inclusive']
#     obs_bins = [float(i) for i in obs_bins] #Convert a list of str to a list of float
#     print 'It is a single-differential measurement, binning', obs_bins
# else: #It is a double-differential analysis
#     # Implementing only the first one as it will be used only for jet-related measurements
#     if opt.OBSBINS.count('vs')==1 and opt.OBSBINS.count('/')>=1:
#         obs_bins_tmp = opt.OBSBINS.split(" vs ")
#         obs_bins_1st = obs_bins_tmp[0].split('|')[1:len(obs_bins_tmp[0].split('|'))-1] #['0', '1', '2', '3', '20']
#         obs_bins_1st = [float(i) for i in obs_bins_1st] #Convert a list of str to a list of float
#         obs_bins_tmp = obs_bins_tmp[1].split(' / ') #['|0|10|20|45|90|250|', '|0|10|20|80|250|', '|0|20|90|250|', '|0|25|250|']
#         obs_bins_2nd = {}
#         for i in range(len(obs_bins_tmp)): #At the end of the loop -> obs_bins_2nd {0: ['0', '10', '20', '45', '90', '250'], 1: ['0', '10', '20', '80', '250'], 2: ['0', '20', '90', '250'], 3: ['0', '25', '250']}
示例#18
0
from JMTucker.Tools.ROOTTools import *
from binning import binning

fn = sys.argv[1]
out_name = sys.argv[2]
print fn

set_style()
ps = plot_saver(plot_dir('overlay/%s' % out_name), size=(600, 600), log=False)
f = ROOT.TFile(fn)

h = f.Get('mfvOverlayHistos/h_dz_true')
h.Draw()
ps.save('h_dz_true')

bins, avgs = binning(out_name)


def rebin(h):
    #return h
    return h.Rebin(len(bins) - 1, h.GetName() + '_rebin', bins)


def get_h(n):
    h = rebin(f.Get('mfvOverlayHistos/%s' % n))
    h.SetLineWidth(2)
    s = 'VV' if 'dvv' in n else '3D'
    h.GetXaxis().SetTitle('d_{%s} (cm)' % s)
    h.GetYaxis().SetTitle('efficiency')
    return h
def Analysis(ea_t, k_t, H, Wm, n_l, d, i_max, theta_crit, F_slide, c_dash, m, g, dt, t_stop, dyn, damage, plasticity, dashpot_par, dashpot_ser, bing, testing):
    #This function performs the main analysis
    #inputs: all basic, damage, and dynamic parameters, except steps.
    #        list of displacements (d)
    #        all model options
    #outputs: list of force values (P)
    #         list of average force values (P_avg)
    #         list of displacements for the top of the link (y)
    #         critical force for the averate length (F_crit_avg)
    #         list of link lengths (L)
    
    
    #normalize ea and k
    ea = ea_t/n_l
    k = k_t/n_l
    
    
    #generate random numbers
    
    if testing:
        #for testing purposes
        R = [0.1406236293192208, 0.557452455836349, 0.4018884612118805, 0.8610494090625574, 0.005928894753714831]
        #R = linspace(.3*H,.8*H,n_l)
        #R = [0.1406236293192208]
    else:
        #generate list of random numbers
        R = [random() for x in range(n_l)]
    
    
    #create list of link lengths
    
    #function to create length distribution
    def length_distribution(r):
        #apply Weibull distribution
        l = [((math.log(1/num)/math.log(2))**(1.0/Wm)) for num in r]
        #apply exponential distribution to Weibull distribution
        L = [H*(1-math.exp(-num)) for num in l]
        return L
    
    #if binning is applied
    if bing:
        #apply binning to the random number distribution, set number of links to calculate to the new binned number
        W_b,r_b,n = binning.binning(R,i_max)
        #find length distribution
        L = length_distribution(r_b)
        #find average length
        l_avg = length_distribution(R)
        L_avg = mean(l_avg)   
    #if binning is not applied
    else:
        #find length distribution
        L = length_distribution(R)
        #find average length
        L_avg = mean(L)
        #set number of links to calculate to the number of links specified
        n = n_l
    
    
    #initialize lists
    
    #y lists
    y = [[0]*n for x in range(len(d))]
    y_avg = [0]*(len(d))
    
    #P lists
    P = [0]*(len(d))
    P_avg = [0]*(len(d))
    
    #indicators
    #for buckling: 0 = unbuckled, 1 = buckling, 2 = collapsed
    c = [0]*n
    c_avg = 0
    #for breaking: 0 = unbroken, 1 = broken
    b = [0]*n
    b_avg = 0
    
    
    #find critical buckling values
    F_crit = [k*Li/4 for Li in L]
    F_crit_avg = k*L_avg/4
    
    
    #convert theta_crit to radians
    theta_crit = theta_crit*math.pi/180.0
    
    
    #find critical distance for sliding for plasticity
    if plasticity:
        x_crit = F_slide/k
        #initialize distances for plasticity
        x_plas = [0]*n
        x = [0]*n
        x_avg = 0
        x_plas_avg = 0
    elif dashpot_par:
        #initialize x distance
        x = [0]*n
        x_avg = 0
        #initialize x rate of change
        dx = [0]*n
        dx_avg = 0
    elif dashpot_ser:
        #initialize x distance
        x = [0]*n
        x_avg = 0
        #initialize the displacement of the dashpot
        x_dash = [0]*n
        x_dash_avg = 0
        
    
    #set up stuff for root finding if not using dynamic analysis
    if not dyn:
        #if plasticity is not applied 
        if not plasticity:
            #set initial root guesses
            F_old = F_crit #initial guesses
            F_old_avg = F_crit_avg #initial guess for average
            
            #define function to find root of
            def root_g(f,d,L,k,H,ea):
                return L*(1-(4*f)/(k*L)) + (H-L)*math.tanh(f/ea) - d
            
            #define derivative of function
            def root_gprime(f,d,L,k,H,ea):
                return -4/k + ((H-L)/ea)*(1-(math.tanh(f/ea))**2)
            
        #if placticity is applied    
        else:
            #define function to find root of
            def root_g(y,d,L,k,H,ea,x_plas):
                return -ea*math.atanh((d-y)/(H-L)) + k*(L-y)*(.25 - x_plas/(2*math.sqrt(2*L*y-y**2)))
            
            
            
    #set up stuff for ODE solving if using dynamic analysis
    else:
        #initialize velocity
        v = [0]*n
        v_avg = 0
    
    #calculate force at each displacement value
    for i in range(len(d)):
        
        
        #initialize list of link forces for this displacement
        F = [0]*n
        
        
        #for each link-------------------------------------------------------------------------------
        for j in range(n):
               
            
            #if the link isn't buckled, check to see if the displacement has jumped past the top of the link
            if c[j] == 0 and d[i] >= H - L[j]:
                #if so, change the link to buckling
                c[j] = 1 
                
            #if the link isn't buckled
            if c[j] == 0:#-----------------------------------------------------
                   
                #calculate the force in the link
                F[j] = ea*math.atanh(d[i]/(H-L[j]))
                #set y
                y[i][j] = 0
                
                #check if the link has buckled
                #if not broken
                if b[j] == 0:
                    #for dynamics
                    if F[j] + m*g >= F_crit[j] and dyn:
                        
                        #set indicator to buckling
                        c[j] = 1
                    #for quasistatic
                    elif F[j] >= F_crit[j] and (not dyn):
                        
                        #set indicator to buckling
                        c[j] = 1
                #if broken
                else:
                    #for dynamics
                    if F[j] + m*g >= 0 and dyn:
                        #set indicator to buckling
                        c[j] = 1
                    #for quasistatic
                    elif F[j] >= 0 and (not dyn):
                        #set indicator to buckling
                        c[j] = 1
                    
            #if the link is buckling
            elif c[j] == 1:#--------------------------------------------------------
                
                #calculate the force in the link
                #for quasistatic
                if not dyn:
                    #if the link isn't broken
                    if b[j] == 0:
                    
                        #set zerotol
                        if L[j] < .3:
                            ztol = .1
                        else:
                            ztol = .01
                        
                            
                        #find the root
                        if not plasticity:
                            #set function arguments
                            args = (d[i],L[j],k,H,ea)
                            #find root
                            F[j] = MyRootFinding.newton_raphson(root_g,F_old[j],root_gprime,args=args,tol=.001,Imax=10*len(d),zerotol=ztol)
                        else:
                            #find spring displacement
                            d_s = x[j] - x_plas[j]
                            #set function arguments
                            args = (d[i],L[j],k,H,ea,x_plas[j])
                            #find boundaries for bisection method
                            #set lower boundary to either 0 or the smallest number for atanh
                            if d[i]-H+L[j] < 0:
                                b_low = .0001
                            else:
                                b_low = (d[i]-H+L[j])*1.0001
                            #set upper boundary to the largest number for atanh
                            b_high = (H-L[j]+d[i])*.9999
                            y[i][j] = MyRootFinding.bisection(root_g,b_low,b_high,args=args)
                        
                        #Find other required values
                        if plasticity:
                            #store y value
                            #find force
                            F[j] = ea*math.atanh((d[i]-y[i][j])/(H-L[j]))
                            #find new x
                            x[j] = math.sqrt(2*L[j]*y[i][j]-y[i][j]**2)/2
                            #find new x_plas if x_plas is changing
                            if d_s > x_crit:
                                x_plas[j] = x[j] - x_crit
                            elif d_s < -x_crit:
                                x_plas[j] = x[j] + x_crit
                        else:
                            #assign current value as next guess value, to be more accurate and help prevent diverging
                            F_old[j] = F[j]
                            #find and store y value
                            y[i][j] = L[j] - 4*F[j]/k
                        
                    #if the link is broken
                    else:
                        #the side spring force is 0, so the applied force is also 0
                        F[j] = 0
                        #set y value
                        y[i][j] = d[i]
                    
                #for dynamic
                else:
                    #solve ODE for y with 4th order Runge Kutta method
                    
                    #if the link isn't broken
                    if b[j] == 0:
                        if dashpot_par:
                            #save previous x value
                            xold = x[j]
                            #find final argument value
                            fin_arg = -c_dash*dx[j]/k
                            #run Runge Kutta method for plasticity with fin_arg instead of x_plas to find y and the velocity
                            y[i][j],v[j] = RK4Dyn.RK4_plaslink(dt,d[i-1],d[i],y[i-1][j],v[j],H,L[j],k,ea,m,g,fin_arg)
                            #find new x
                            if y[i][j] < 0:
                                x[j] = 0
                            elif y[i][j] > L[j]:
                                x[j] = L[j]/2
                            else:
                                x[j] = math.sqrt(2*L[j]*y[i][j]-y[i][j]**2)/2
                            #find new dx
                            dx[j] = (x[j] - xold)/dt
                            
                        elif dashpot_ser:
                            #run Runge Kutta method for plasticity with x_dash instead of x_plas to find y and the velocity
                            y[i][j],v[j] = RK4Dyn.RK4_plaslink(dt,d[i-1],d[i],y[i-1][j],v[j],H,L[j],k,ea,m,g,x_dash[j])
                            #get new x
                            if y[i][j] < 0:
                                x[j] = 0
                            elif y[i][j] > L[j]:
                                x[j] = L[j]/2
                            else:
                                x[j] = math.sqrt(2*L[j]*y[i][j]-y[i][j]**2)/2
                            #use Runge Kutta method to get new x_dash
                            x_dash[j] = RK4Dyn.RK4_dashser(x_dash[j],dt,k,x[j],c_dash)
                            
                        elif plasticity:
                            #find spring displacement
                            d_s = x[j] - x_plas[j]
                            #run Runge Kutta method for plasticity to find y and the velocity
                            y[i][j],v[j] = RK4Dyn.RK4_plaslink(dt,d[i-1],d[i],y[i-1][j],v[j],H,L[j],k,ea,m,g,x_plas[j])
                            #find new x
                            if y[i][j] < 0:
                                x[j] = 0
                            elif y[i][j] > L[j]:
                                x[j] = L[j]/2
                            else:
                                x[j] = math.sqrt(2*L[j]*y[i][j]-y[i][j]**2)/2
                            #find new x_plas if x_plas is changing
                            if d_s > x_crit:
                                x_plas[j] = x[j] - x_crit
                            elif d_s < -x_crit:
                                x_plas[j] = x[j] + x_crit
                        else:
                            #run regular Runge Kutta method to find y and the velocity
                            y[i][j],v[j] = RK4Dyn.RK4_link(dt,d[i-1],d[i],y[i-1][j],v[j],H,L[j],k,ea,m,g)
                        
                        
                    else:
                        #run Runge Kutta method to find y and the velocity, with k=0 for breakage
                        y[i][j],v[j] = RK4Dyn.RK4_link(dt,d[i-1],d[i],y[i-1][j],v[j],H,L[j],0,ea,m,g)
                    #correct v value if necessary to prevent divergence
                    if v[j] > 1000 or math.isnan(v[j]):
                        v[j] = 1000
                    
                    #correct y value if necessary
                    #make sure the displacement doesn't pass the top of the link
                    if d[i]-y[i][j] >= H-L[j]:
                        y[i][j] = d[i] - (H-L[j])*.999999
                    #make sure the spring doesn't stretch too long
                    if d[i]-y[i][j] <= L[j]-H:
                        y[i][j] = d[i] - (L[j]-H)*.999999
                    
                    #calculate force
                    F[j] = ea*math.atanh((d[i]-y[i][j])/(H-L[j]))
                
                #if damage is turned on and the link hasn't broken, check to see if it has
                if b[j] == 0 and damage:
                    #calculate theta
                    #if y steps below zero, making the argument for acos > 1, make sure theta is zero
                    if y[i][j] < 0:
                        theta = 0
                    else:
                        theta = math.acos((L[j]-y[i][j])/L[j])
                    #check if theta is larger than the breaking angle
                    if theta >= theta_crit:
                        #set to broken
                        b[j] = 1
                
                #check to see if the link has completely collapsed
                if y[i][j] >= L[j]:
                    #set y correctly
                    y[i][j] = L[j]
                    
                    #set indicator to collapsed
                    c[j] = 2
                    #recalculate force to reflect collapse
                    F[j] = ea*math.atanh((d[i] - L[j])/(H - L[j]))
                    #set velocity to zero if running dynamics
                    if dyn:
                        v[j] = 0
                
                #check to see if the link has unbuckled
                if not plasticity:
                    if y[i][j] <= 0:
                        #set y correctly
                        y[i][j] = 0
                        #set indicator to unbuckled
                        c[j] = 0
                        #recalculate force to reflect unbuckling
                        #if the atanh argument is >= 1
                        if d[i] >= (H-L[j]):
                            #make the force as large as it can be
                            F[j] = ea*math.atanh(.9999999999999999)
                        #otherwise calculate the force normally
                        else:
                            F[j] = ea*math.atanh(d[i]/(H - L[j]))
                else:
                    if (y[i][j] > 10*y[i-1][j] and y[i-1][j] != 0 and not dyn) or (y[i][j] < 0 and dyn):
                        #set y correctly
                        y[i][j] = 0
                        #set indicator to unbuckled
                        c[j] = 0
                        #recalculate force to reflect unbuckling
                        #if the atanh argument is >= 1
                        if d[i] >= (H-L[j]):
                            #make the force as large as it can be
                            F[j] = ea*math.atanh(.9999999999999999)
                        #otherwise calculate the force normally
                        else:
                            F[j] = ea*math.atanh(d[i]/(H - L[j]))
            
            #if the link is completely collapsed
            elif c[j] == 2:#------------------------------------------------------------------
                 
                #store y
                y[i][j] = L[j]

                #calculate the force in the link
                #if the atanh argument <= -1
                if (d[i] - L[j])/(H - L[j]) <= -1:
                    #make the force as small as possible
                    F[j] = ea*math.atanh(-.9999999999999999)
                #otherwise calculate normally
                else:
                    F[j] = ea*math.atanh((d[i] - L[j])/(H - L[j]))
                
                #check to see if the link is uncollapsing
                #for dynamics, check if the spring force will overcome gravity
                if F[j] < -m*g and dyn:
                    #set indicator to buckling
                    c[j] = 1
                #for quasistatic, check if the spring force < 0
                elif F[j] < 0 and (not dyn):
                    #set indicator to buckling
                    c[j] = 1
                    
        
        #calculate total force
        
        #if binning is applied
        if bing:
            P[i] = 0 #initialize force sum
            for j in range(n):
                P[i] += F[j]*W_b[j]*n_l #sum weighted forces
        #if binning is not applied        
        else:    
            P[i] = sum(F)
            
            
            
        #for the average force------------------------------------------------------------------------------------
        
        
        #if the link isn't buckled, check to see if the displacement has jumped past the top of the link
        if c_avg == 0 and d[i] >= H - L_avg:
            #if so, change the link to buckling
            c_avg = 1
            
            
        #if the link isn't buckled
        if c_avg == 0:#-----------------------------------------------------
            
            #calculate the force in the link
            F_avg = ea*math.atanh(d[i]/(H-L_avg))
            #set y
            y_avg[i] = 0
            
            #check if the link has buckled
            #for dynamics
            if F_avg + m*g >= F_crit_avg and dyn:
                #set indicator to buckling
                c_avg = 1
            #for quasistatic
            elif F_avg >= F_crit_avg and (not dyn):
                #set indicator to buckling
                c_avg = 1
                
                
        #if the link is buckling
        elif c_avg == 1:#---------------------------------------------------
            
            #calculate the force in the link
            #for quasistatic
            if not dyn:
                #if the link isn't broken
                if b_avg == 0:
                
                    #set the guess
                    if plasticity:
                        if y_avg[i-1] == 0:
                            guess = .00001
                        else:
                            guess = y_avg[i-1]
                    else:
                        guess = F_old_avg
                    
                    #find the root
                    if not plasticity:
                            #set function arguments
                            args = (d[i],L_avg,k,H,ea)
                            #find root
                            F_avg = MyRootFinding.newton_raphson(root_g,guess,root_gprime,args=(d[i],L_avg,k,H,ea),tol=.001,Imax=10*len(d),zerotol=.01)
                    else:
                        #find spring displacement
                        d_s_avg = x_avg - x_plas_avg
                        #set function arguments
                        args_avg = (d[i],L_avg,k,H,ea,x_plas_avg)
                        #find boundaries for bisection method
                        #set lower boundary to either 0 or the smallest number for atanh
                        if d[i]-H+L_avg < 0:
                            b_low_avg = .0001
                        else:
                            b_low_avg = (d[i]-H+L_avg)*1.0001
                        #set upper boundary to the largest number for atanh
                        b_high_avg = (H-L_avg+d[i])*.9999
                        y_avg[i] = MyRootFinding.bisection(root_g,b_low_avg,b_high_avg,args=args_avg)
                        
                    #Find other required values
                    if plasticity:
                        #store y value
                        #find force
                        F_avg = ea*math.atanh((d[i]-y_avg[i])/(H-L_avg))
                        #find new x
                        x_avg = math.sqrt(2*L_avg*y_avg[i]-y_avg[i]**2)/2
                        #find new x_plas if x_plas is changing
                        if d_s_avg > x_crit:
                            x_plas_avg = x_avg - x_crit
                        elif d_s_avg < -x_crit:
                            x_plas_avg = x_avg + x_crit
                    else:
                        #assign current value as next guess value, to be more accurate and help prevent diverging
                        F_old_avg = F_avg
                        #find and store y value
                        y_avg[i] = L_avg - 4*F_avg/k
                        
                        
                #if the link is broken
                else:
                    #the side spring force is 0, so the applied force is also 0
                    F_avg = 0
                    #set y value
                    y_avg[i] = d[i]
                
            #for dynamic
            else:
                #solve ODE for y with 4th order Runge Kutta method
                    
                #if the link isn't broken
                if b[j] == 0:
                    if dashpot_par:
                        #save previous x value
                        xold_avg = x_avg
                        #find final argument value
                        fin_arg_avg = -c_dash*dx_avg/k
                        #run Runge Kutta method for plasticity with fin_arg instead of x_plas to find y and the velocity
                        y_avg[i],v_avg = RK4Dyn.RK4_plaslink(dt,d[i-1],d[i],y_avg[i-1],v_avg,H,L_avg,k,ea,m,g,fin_arg_avg)
                        #find new x
                        if y_avg[i] < 0:
                            x_avg = 0
                        elif y_avg[i] > L_avg:
                            x_avg = L_avg/2
                        else:
                            x_avg = math.sqrt(2*L_avg*y_avg[i]-y_avg[i]**2)/2
                        #find new dx
                        dx_avg = (x_avg - xold_avg)/dt
                        
                    elif dashpot_ser:
                        #run Runge Kutta method for plasticity with x_dash instead of x_plas to find y and the velocity
                        y_avg[i],v_avg = RK4Dyn.RK4_plaslink(dt,d[i-1],d[i],y_avg[i-1],v_avg,H,L_avg,k,ea,m,g,x_dash_avg)
                        #get new x
                        if y_avg[i] < 0:
                            x_avg = 0
                        elif y_avg[i] > L_avg:
                            x_avg = L_avg/2
                        else:
                            x_avg = math.sqrt(2*L_avg*y_avg[i]-y_avg[i]**2)/2
                        #use Runge Kutta method to get new x_dash
                        x_dash_avg = RK4Dyn.RK4_dashser(x_dash_avg,dt,k,x_avg,c_dash)
                        
                    elif plasticity:
                        #find spring displacement
                        d_s_avg = x_avg - x_plas_avg
                        #run Runge Kutta method for plasticity to find y and the velocity
                        y_avg[i],v_avg = RK4Dyn.RK4_plaslink(dt,d[i-1],d[i],y_avg[i-1],v_avg,H,L_avg,k,ea,m,g,x_plas_avg)
                        #find new x
                        if y_avg[i] < 0:
                            x_avg = 0
                        elif y_avg[i] > L_avg:
                            x_avg = L_avg/2
                        else:
                            x_avg = math.sqrt(2*L_avg*y_avg[i]-y_avg[i]**2)/2
                        #find new x_plas if x_plas is changing
                        if d_s_avg > x_crit:
                            x_plas_avg = x_avg - x_crit
                        elif d_s_avg < -x_crit:
                            x_plas_avg = x_avg + x_crit
                    else:
                        #run Runge Kutta method to find y and the velocity
                        y_avg[i],v_avg = RK4Dyn.RK4_link(dt,d[i-1],d[i],y_avg[i-1],v_avg,H,L_avg,k,ea,m,g)

                else:
                    #run Runge Kutta method to find y and the velocity, with k=0 for breakage
                    y_avg[i],v_avg = RK4Dyn.RK4_link(dt,d[i-1],d[i],y_avg[i-1],v_avg,H,L_avg,0,ea,m,g)

                #correct v value if necessary to prevent divergence
                if v_avg > 1000 or math.isnan(v_avg):
                    v_avg = 1000
                
                #correct y value if necessary
                #make sure the displacement doesn't pass the top of the link
                if d[i]-y_avg[i] >= H-L_avg:
                    y_avg[i] = d[i] - (H-L_avg)*.999999
                #make sure the spring doesn't stretch too long
                if d[i]-y_avg[i] <= L_avg-H:
                    y_avg[i] = d[i] - (L_avg-H)*.999999
            
                #calculate force using the calculated y value
                F_avg = ea*math.atanh((d[i]-y_avg[i])/(H-L_avg))
            
            #if damage is on and the link hasn't broken, check to see if it has
            if b_avg == 0 and damage:
                #calculate theta
                #if y steps below zero, making the argument for acos > 1, make sure theta is zero
                if y_avg[i] < 0:
                    theta = 0
                else:
                    theta = math.acos((L_avg-y_avg[i])/L_avg)
                #check if theta is larger than the breaking angle
                if theta >= theta_crit:
                    #set to broken
                    b_avg = 1
            
            #check to see if the link has completely collapsed
            if y_avg[i] >= L_avg:
                #set y correctly
                y_avg[i] = L_avg
                #set indicator to collapsed
                c_avg = 2
                #recalculate force to reflect collapse
                F_avg = ea*math.atanh((d[i] - L_avg)/(H - L_avg))
                #set velocity to zero if running dynamics
                if dyn:
                    v_avg = 0
            
            #check to see if the link has unbuckled
            if not plasticity:
                if y_avg[i] < 0:
                    #set y correctly
                    y_avg[i] = 0
                    #set indicator to unbuckled
                    c_avg = 0
                    #recalculate force to reflect unbuckling
                    F_avg = ea*math.atanh(d[i]/(H - L_avg))
            else:
                if (y_avg[i] > 10*y_avg[i-1] and y_avg[i-1] != 0 and not dyn) or (y_avg[i] < 0 and dyn):
                    #set y correctly
                    y_avg[i] = 0
                    #set indicator to unbuckled
                    c_avg = 0
                    #recalculate force to reflect unbuckling
                    #if the atanh argument is >= 1
                    if d[i] >= (H-L_avg):
                        #make the force as large as it can be
                        F_avg = ea*math.atanh(.9999999999999999)
                    #otherwise calculate the force normally
                    else:
                        F_avg = ea*math.atanh(d[i]/(H - L_avg))
        
        
        #if the link is completely collapsed
        elif c_avg == 2:#-----------------------------------------------------------
            
            #store y
            y_avg[i] = L_avg
            
            #calculate the force in the link
            #if the atanh argument is <= -1
            if (d[i] - L_avg)/(H - L_avg) <= -1:
                #make force as small as possible
                F_avg = ea*math.atanh(-.9999999999999999)
            #otherwise calculate force normally
            else:
                F_avg = ea*math.atanh((d[i] - L_avg)/(H - L_avg))
            
            #check to see if the link is uncollapsing
            #for dynamics, check if the spring force will overcome gravity
            if F_avg < -m*g and dyn:
                #set indicator to buckling
                c_avg = 1
            #for quasistatic, check if the spring force < 0
            elif F_avg < 0 and (not dyn):
                #set indicator to buckling
                c_avg = 1
                    
        
        #calculate total average force
        P_avg[i] = F_avg*n_l
    
    
    
    
    return P, P_avg, y, F_crit_avg, L
def NLSA(ea_t,k_t,H,m,n_l):   
    #normalize
    ea = ea_t/n_l
    k = k_t/n_l
    
    #generate list of random numbers
    if testing:
        #for testing purposes
        R = linspace(.3,.8,n_l)
        #pseudo-random 5-link
        #R = [0.1406236293192208, 0.557452455836349, 0.4018884612118805, 0.8610494090625574, 0.005928894753714831]
    else:
        #generate list of random numbers
        R = [random() for x in range(n_l)]
    
    
    #create length distribution
    def length_distribution(r):
        l = [H*((math.log(1/num)/math.log(2))**(1.0/m)) for num in r]
        L = [H*(1-math.exp(-num)) for num in l]
        return L
    
    #if binning is applied
    if bing:
        #apply binning
        W_b,r_b,n = binning.binning(R,i_max)
        #find length distribution
        L = length_distribution(r_b)
        #find average length
        l_avg = length_distribution(R)
        L_avg = mean(l_avg)
    #if binning is not applied
    else:
        #find length distribution
        L = length_distribution(R)
        #L=[.5]
        #find average length
        L_avg = mean(L)
        n = n_l
    
    
    #setup for force calculations
    
    #make displacement distribution
    if save_ani:
        d = linspace(0,H,200)
    else:
        d = linspace(0,H,1000)
    #initialize y-values
    y = [[0]*n for x in range(len(d)-1)]
    y_avg = [0]*(len(d)-1)
    #initialize total force list
    P = [0]*(len(d)-1)
    P_avg = [0]*(len(d)-1)
    #set indicator for whether links have buckled: 0 = no, 1 = in progress, 2 = yes
    c = [0]*n
    c_avg = 0
    
    #find critical buckling values
    F_crit = [k*Li/4 for Li in L]
    F_crit_avg = k*L_avg/4
    
    #define stuff for the newton function
    F_old = F_crit #initial guesses
    F_old_avg = F_crit_avg #initial guess for average
    #define function
    def g(f,d,L,k,H,ea):
        return L*(1-(4*f)/(k*L)) + (H-L)*math.tanh(f/ea) - d
    #define derivative of function
    def gprime(f,d,L,k,H,ea):
        return -4/k + ((H-L)/ea)*(1-(math.tanh(f/ea))**2)
    
    
    #calculate force at each displacement value (except the last, because that one's infinity)
    for i in range(len(d)-1):
        #initialize force list
        F = [0]*n
        #for each link
        for j in range(n):
            #if the link hasn't buckled:
            #check to see if displacement is past top of link
            if c[j] == 0 and d[i] >= (H-L[j]):
                #if so, set indicator to buckling
                c[j] = 1
            
            #if it hasn't buckled
            if c[j] == 0:
                #calculate force in link
                F[j] = ea*math.atanh(d[i]/(H-L[j]))
                y[i][j] = 0
                #check to see if link has buckled
                if F[j] >= F_crit[j]:
                    c[j] = 1 #set indicator
            #if it's currently buckling
            elif c[j] == 1: 
                #numerically calculate link force
                guess = F_old[j]
                          
                F[j] = MyRootFinding.newton_raphson(g,guess,gprime,args=(d[i],L[j],k,H,ea),tol=.001,Imax=10*len(d),zerotol=.01)
                #assign current value as next guess value
                F_old[j] = F[j]         
                #find and store y value
                y[i][j] = L[j] - 4*F[j]/k
                #check if link has completely collapsed
                if y[i][j] >= L[j]:
                    c[j] = 2 #set indicator
                    F[j] = ea*math.atanh((d[i] - L[j])/(H - L[j]))
            #if it's completely collapsed
            else:
                #calculate link force
                F[j] = ea*math.atanh((d[i] - L[j])/(H - L[j]))
                #store y
                y[i][j] = L[j]
        
        #sum forces to find total force
        #if binning is applied
        if bing:
            P[i] = 0 #initialize force sum
            for j in range(n):
                P[i] += F[j]*W_b[j]*n_l #sum weighted forces
        #if binning is not applied        
        else:    
            P[i] = sum(F)    
        
    return d,P,F_crit_avg
示例#21
0
def bin_all():
    rmid_list = get_total_rmid_list()
    for each in rmid_list:
        binning(each)
def binned_claa(Lmax, mb0, mb1=None):
    L = np.linspace(0, Lmax, Lmax + 1)
    fcl = 1e-4 * 2 * np.pi / (L**2 + L + 1e-30)
    return bins.binning(fcl, mb0, mb1)
示例#23
0
def book(out_name, hs=[]):
    bins = binning()
    h = ROOT.TH1F(out_name, '', len(bins) - 1, bins)
    hs.append(h)
    return h
def binned_cl(fcl, mb0, mb1=None, cn=1):
    scl = np.loadtxt(fcl, unpack=True)[cn]
    return bins.binning(scl, mb0, mb1)
示例#25
0
from JMTucker.Tools.ROOTTools import *
from binning import binning

fn = sys.argv[1]
out_name = sys.argv[2]
print fn

set_style()
ps = plot_saver(plot_dir('overlay/%s' % out_name), size=(600,600), log=False)
f = ROOT.TFile(fn)

h = f.Get('mfvOverlayHistos/h_dz_true')
h.Draw()
ps.save('h_dz_true')

bins, avgs = binning(out_name)

def rebin(h):
    #return h
    return h.Rebin(len(bins)-1, h.GetName() + '_rebin', bins)
    
def get_h(n):
    h = rebin(f.Get('mfvOverlayHistos/%s' % n))
    h.SetLineWidth(2)
    s = 'VV' if 'dvv' in n else '3D'
    h.GetXaxis().SetTitle('d_{%s} (cm)' % s)
    h.GetYaxis().SetTitle('efficiency')
    return h

def get_h_eff(h_num, h_den):
    h_eff = ROOT.TGraphAsymmErrors(h_num, h_den, 'b(1,1)')
def NLSADmg(ea_t, k_t, H, m, n_l, dmax, theta_crit):
    #normalize
    ea = ea_t / n_l
    k = k_t / n_l

    #convert theta to radians
    theta_crit = theta_crit * math.pi / 180

    #generate list of random numbers
    R = [random() for x in range(n_l)]

    #for testing purposes
    #R = linspace(.3,.9,n_l)
    #pseudo-random 5-link
    #R = [0.1406236293192208, 0.557452455836349, 0.4018884612118805, 0.8610494090625574, 0.005928894753714831]

    #create length distribution
    def length_distribution(r):
        l = [H * ((math.log(1 / num) / math.log(2))**(1.0 / m)) for num in r]
        L = [H * (1 - math.exp(-num)) for num in l]
        return L

    #if binning is applied
    if bing:
        #apply binning
        W_b, r_b, n = binning.binning(R, i_max)
        #find length distribution
        L = length_distribution(r_b)
        #find average length
        l_avg = length_distribution(R)
        L_avg = mean(l_avg)
    #if binning is not applied
    else:
        #find length distribution
        L = length_distribution(R)
        #find average length
        L_avg = mean(L)
        n = n_l

    #setup for force calculations

    #initialize displacement list
    d = [0]
    ldng = 1  #set whether loading (1) or unloading (0)
    #initialize y-values
    y = [[0] * n]
    y_avg = [0]
    #initialize total force list
    P = [0]
    P_avg = [0]

    #set indicator for whether links have buckled broken: 0 = no, 1 = buckling, 2 = completely collapsed
    c = [0] * n
    c_avg = 0
    #set indicator for whether links have broken: 0 = no, 1 = yes
    b = [0] * n
    b_avg = 0

    #find critical buckling values
    F_crit = [k * Li / 4 for Li in L]
    F_crit_avg = k * L_avg / 4

    #define stuff for the newton function
    F_old = F_crit  #initial guesses
    F_old_avg = F_crit_avg  #initial guess for average

    #define function
    def g(f, d, L, k, H, ea):
        return L * (1 - (4 * f) / (k * L)) + (H - L) * math.tanh(f / ea) - d

    #define derivative of function
    def gprime(f, d, L, k, H, ea):
        return -4 / k + ((H - L) / ea) * (1 - (math.tanh(f / ea))**2)

    #calculate force at each displacement value (except the last, because that one's infinity)
    i = 1  #set counter
    #loop will continue until d comes back up to its starting position, or until it goes through 100000 iterations
    #(to make sure it'll stop even if it screws up)
    while i <= 100000:
        #set new d value (incrementing by thousandths of H)
        #if not enough links have broken yet:
        if d[i - 1] >= dmax:
            ldng = 0
        if save_ani:
            if ldng == 1:  #if loading
                #increment d forward
                d.append(i * .005 * H)
            else:  #if unloading
                #increment d backward
                d.append(d[i - 1] - .005 * H)
        else:
            if ldng == 1:  #if loading
                #increment d forward
                d.append(i * .001 * H)
            else:  #if unloading
                #increment d backward
                d.append(d[i - 1] - .001 * H)
        #stop if d has displaced further than H
        if d[i] >= H:
            #make d the same length as the force lists
            d.pop()
            break
        #stop if d becomes negative
        if d[i] < 0:
            #make d the same length as the force lists
            d.pop()
            break
        #add next list of y-values
        y.append([])
        #initialize force list
        F = [0] * n
        #for each link
        for j in range(n):
            #if link hasn't broken:
            if b[j] == 0:
                #if the link hasn't buckled:
                #check to see if displacement is past top of link
                if c[j] == 0 and d[i] >= (H - L[j]):
                    #if so, set indicator to buckling
                    c[j] = 1

                #if it hasn't buckled
                if c[j] == 0:
                    #calculate force in link
                    F[j] = ea * math.atanh(d[i] / (H - L[j]))
                    y[i].append(0)
                    #check to see if link has buckled
                    if F[j] >= F_crit[j]:
                        c[j] = 1  #set indicator
                #if it's currently buckling
                elif c[j] == 1:
                    #numerically calculate link force
                    guess = F_old[j]

                    F[j] = MyRootFinding.newton_raphson(g,
                                                        guess,
                                                        gprime,
                                                        args=(d[i], L[j], k, H,
                                                              ea),
                                                        tol=.001,
                                                        Imax=10 * len(d),
                                                        zerotol=.01)
                    #assign current value as next guess value
                    F_old[j] = F[j]
                    #find and store y value
                    y[i].append(L[j] - 4 * F[j] / k)
                    if y[i][j] > L[j]:
                        y[i][j] = L[j]
                    #if still loading
                    #(if not, d is decreasing, and the remaining links aren't going to break and don't need to be checked)
                    if ldng == 1:
                        #check if link has broken
                        #small links will have very large jumps in y, so only calculate acos if theta < 90 degrees
                        if (L[j] - y[i][j]) / L[j] <= 1 and (
                                L[j] - y[i][j]) / L[j] >= -1:
                            theta = math.acos((L[j] - y[i][j]) / L[j])
                        else:  #otherwise theta should be 90 degrees
                            theta = math.pi / 2

                        if theta >= theta_crit:
                            b[j] = 1
                            #check whether top spring has enough room to extend fully
                            if d[i] > L[j]:
                                c[j] = 2
                        #check if link has completely collapsed
                        if y[i][j] >= L[j]:
                            c[j] = 2  #set indicator
                            F[j] = ea * math.atanh((d[i] - L[j]) / (H - L[j]))
                    else:  #if unloading
                        #check if the links have unbent again
                        if y[i][j] < 0:
                            y[i][j] = 0
                            #set force correctly
                            F[j] = ea * math.atanh(d[i] / (H - L[j]))
                            c[j] = 0
                #if it's completely collapsed
                else:
                    #calculate link force
                    F[j] = ea * math.atanh((d[i] - L[j]) / (H - L[j]))
                    #store y
                    y[i].append(L[j])
            else:  #if link has broken
                #if top spring is not fully extended
                if c[j] == 2:
                    #calculate link force
                    F[j] = ea * math.atanh((d[i] - L[j]) / (H - L[j]))
                    #store y
                    y[i].append(L[j])
                    #check if spring has fully extended
                    if d[i] <= L[j]:
                        #set indicator
                        c[j] = 1
                elif c[j] == 1:  #if top spring is fully extended
                    #force is zero
                    F[j] = 0
                    #store y value
                    y[i].append(d[i])
                    #see if spring is being compressed
                    if d[i] > L[j]:
                        #set indicator
                        c[j] = 2
                else:
                    print "spring %d is extending" % j

        #sum forces to find total force
        #if binning is applied
        if bing:
            Psum = 0  #initialize force sum
            for j in range(n):
                Psum += F[j] * W_b[j] * n_l  #sum weighted forces
            P.append(Psum)
        #if binning is not applied
        else:
            P.append(sum(F))

        #increment counter
        i += 1

    return d, P, F_crit_avg