Exemplo n.º 1
0
def plot_current_current(logfile, colors, textxy):
    current_set, current = extract(logfile, identifiers=['Current'])
    T = current_set.keys(
    )[0]  # we care only about one temperature, actually, for calibration Temp is irrelevant anyway
    xymin, xymax = np.min(current_set[T]), np.max(current_set[T])
    textx, texty = textxy[0], textxy[1]

    # linreg
    q0, m0 = ev.linreg(current_set[T],
                       current[T].v(),
                       current[T].e(),
                       overwrite_zeroerrors=True)

    # plot
    plt.errorbar(current_set[T],
                 current[T].v(),
                 yerr=current[T].e(),
                 c=colors[0],
                 linestyle=' ')
    plt.plot(current_set[T], m0.v() * current_set[T] + q0.v(), c=colors[1])

    summary = r'(${0}$) $\times$ c_set + (${1}$) A'.format(
        m0.round(2), q0.round(2))
    plt.text(textx, texty, summary, color='k')

    return xymin, xymax
Exemplo n.º 2
0
def thermal_resistance(T,wavelength,dlambdadPd):
    # based on Heinen2012's equation (2)
    # lambda = dlambda/dT*T + dlambda/dPd*Pd + lambda_0
    #        = dlambdadPd*Pd + wavelength
    # with
    # lambda_0_ = dlambdadT*T + lambda_00
    # (lambda_00 is virtual wavelength at no dissipated power
    #  and heat sink temperature of 0 degC
    #  (resp. at T=0 of whatever the unit of input temperatures is...))
    #
    # R_th = dlambda/dPd / dlambda/dT = dT/dPd
    
    l0, dldT = ev.linreg(T.v(), wavelength.v(),wavelength.e())
    #dldD = ev.stderrval(dlambdadPd)
    dldD = ev.wmean(dlambdadPd) # supposed to be the same value measured several times => weighted mean
    #R_th = dldD/dldT
    
    return dldD, dldT, l0#, R_th
Exemplo n.º 3
0
def main():
    logfile = '20150204_sample21-1-d6/spot333um.csv'
    calib_folder = '20150204_calib_333um_s21-1-d6'


    # calibration
    #pump_lut, refl_lut, emis_lut = lut_from_calibfolder(calib_folder)
    emis_lut = lut_from_calibfolder(calib_folder,identifiers=['Laser'],ignore_error=False) # emission has constant value solely due to BS, no ND in front of detector etc.
    pump_lut, refl_lut = lut_interp_from_calibfolder(calib_folder,identifiers=['Pump','Refl'])
    
    #------------------------------------
    # load measurement
    current_set, current, pump, refl, laser, meantemp = extract(logfile, identifiers=['Current','Pump','Refl','Laser','Temperature'])
    Temperatures = sorted(current_set.keys())

    absorbed, reflected, emitted, pumped, dissipated, relref = {}, {}, {}, {}, {}, {}
    for T in Temperatures:
        reflected[T] = refl_lut(refl[T])
        pumped[T] = pump_lut(pump[T])
        absorbed[T] = pumped[T] - reflected[T]
        emitted[T] = emis_lut(laser[T])
        dissipated[T] = absorbed[T] - emitted[T]
        relref[T] = reflected[T]/pumped[T]*100



    cols = varycolor(3*len(Temperatures))
    cnt = 0

    #plt.subplot(1,2,1)

    baserefl = ev.errvallist()
    for T in Temperatures:
        
        # plot

        pstart, pend = 1, 9 # W pumped
        istart, iend = np.sum([pumped[T].v()<pstart]), np.sum([pumped[T].v()<pend])
        baserefl.append(ev.wmean(relref[T][istart:iend]))

        xplot = current
        xlabel = 'Pump current (A)'

        plt.errorbar(xplot[T].v(),relref[T].v(),
                     xerr=xplot[T].e(),yerr=relref[T].e(),
                     c=cols[cnt],linestyle=' ',
                     label='$({0})^\circ$C'.format(meantemp[T].round(2)))
        plt.plot(xplot[T][istart:iend].v(), (iend-istart)*[baserefl[-1].v()],color='k')

        cnt+=3

    plt.xlabel(xlabel)
    plt.ylabel('Reflectivity (%)')
    #plt.xlim([0, 20])
    reflylim = [25, 70]
    plt.ylim(reflylim)
    plt.legend(loc='best',prop={'size':12},labelspacing=-0.4)
    plt.grid('on')
    plt.show()

    ##

    #plt.subplot(1,2,2)

    templist = [meantemp[T] for T in Temperatures]
    Temp = ev.errvallist(templist)

    q,m = ev.linreg(Temp.v(),baserefl.v(),baserefl.e())

    plt.errorbar(Temp.v(),baserefl.v(),
                 xerr=Temp.e(),yerr=baserefl.e(),
                 color='r',linestyle=' ')
    plt.plot(Temp.v(),q.v()+Temp.v()*m.v(),'k')
    plt.text((Temp[0].v()+Temp[1].v())/2.0,baserefl[0].v()+2,
             r'$({})+({})T_{{hs}}$'.format(q.round(2),m.round(2)))
    plt.ylim(reflylim)
    plt.xlabel('Heat sink temperature ($^\circ$C)')
    plt.ylabel('Reflectivity (%)')
    plt.grid('on')

    ##
    plt.show()
Exemplo n.º 4
0
def main():
    # before running this script:
    #   run eval_spectrum.py to provide the .._eval.csv files required for the spectra
    #   run calibration.py (with appropriate calib measurements)
    # and don't forget temperature_heatsink (this is not necessary for this script here, but it provides interesting insights for the measurement at hand)
    logfile = '../24_LL_ev/20150211_sample21-1-d6/spot333um.csv'
    calib_folder = '../24_LL_ev/20150204_calib_333um_s21-1-d6'

    #------------------------------------
    # calibration
    emis_lut = lut_from_calibfolder(
        calib_folder, identifiers=['Laser'], ignore_error=False
    )  # emission has constant value solely due to BS, no ND in front of detector etc.
    pump_lut, refl_lut = lut_interp_from_calibfolder(
        calib_folder, identifiers=['Pump', 'Refl'])

    #------------------------------------
    # load measurement
    current_set, current, pump, refl, laser, spectra, meantemp = extract(
        logfile,
        identifiers=[
            'Current', 'Pump', 'Refl', 'Laser', 'Spectra', 'Temperature'
        ])
    Temperatures = sorted(current_set.keys(
    ))  # set temperatures (round numbers like 15.0 or 22.5 etc)
    T_out = dict(
        (T, meantemp[T].round(1)) for T in Temperatures
    )  # real temperatures for display in plot, including +-uncertainty

    #------------------------------------
    # calculate using calibration
    absorbed, reflected, emitted, pumped, dissipated = {}, {}, {}, {}, {}
    for T in Temperatures:
        reflected[T] = refl_lut(refl[T])
        pumped[T] = pump_lut(pump[T])
        absorbed[T] = pumped[T] - reflected[T]
        emitted[T] = emis_lut(laser[T])
        dissipated[T] = absorbed[T] - emitted[T]

    #
    #------------------------------------
    # invoke instructions for plot and fit
    # plotting the data can be tricky to reproduce, store the plot properties in a text file and read from there!
    # (easy to repeat the plot at a later time)
    # open the instruction file in a text editor, edit the instructions and run this module again; it will use the new instructions
    instrfile = logfile[:-4] + '_instr.csv'
    plotinstructions_write(instrfile, Temperatures, calib_folder)

    #------------------------------------
    # retrieve instructions
    instr = plotinstructions_read(instrfile)

    #
    #------------------------------------
    # translate instructions
    str2lst = lambda s: map(float, s[1:-1].split(','))

    textx = float(
        instr['textx']
    )  # x coordinate for text; same for first two subplots (absorbed-emitted and absorbed-reflectivity)
    fontsize = float(instr['fontsize'])
    title = instr['title']
    xlim = str2lst(
        instr['xlim'])  # range of x-axis; same for first two subplots
    ylim1 = str2lst(
        instr['ylim1'])  # range of y-axis of first (aborbed-emitted) plot
    ylim2 = str2lst(
        instr['ylim2'])  # range of second y-axis (absorbed-reflectivity)
    xlim3 = str2lst(instr['xlim3'])  # third x-axis; (dissipated-wavelength)
    ylim3 = str2lst(instr['ylim3'])  # 3rd y-axis
    plot_temps_for_3 = str2lst(
        instr['plot_temps_for_3']
    )  # which ones to plot? you may have measured a heat sink temperature without lasing output, whose data will confuse the reader, so you don't plot it.
    textx3 = float(instr['textx3'])  # x-coordinate of text in 3rd plot
    texty3 = str2lst(instr['texty3'])  # 3rd y-coordinate
    llow0 = {}
    lhigh0 = {}
    texty1 = {}
    for T in Temperatures:
        llow0[T] = sum(absorbed[T].v() < float(instr['llow0[{0}]'.format(T)])
                       )  # index indicating start of lasing activity
        lhigh0[T] = sum(absorbed[T].v() < float(instr['lhigh0[{0}]'.format(T)])
                        )  # index corresponding to where linear segment stops
        texty1[T] = float(instr['texty1[{0}]'.format(T)])

    #
    #
    #------------------------------------
    #------------------------------------
    # plot
    cols = varycolor(3 * len(Temperatures))

    plt.subplot(3, 1, 1)
    cnt = 0  # color counter

    q0, m0 = {}, {}  # for linreg
    for T in Temperatures:

        # linreg
        q0[T], m0[T] = ev.linreg(absorbed[T].v()[llow0[T]:lhigh0[T]],
                                 emitted[T].v()[llow0[T]:lhigh0[T]],
                                 emitted[T].e()[llow0[T]:lhigh0[T]],
                                 overwrite_zeroerrors=True)

        emax, emaxi = ev.max(emitted[T], True)
        amax = absorbed[T][emaxi]
        print 'Max emission at ({}) degC at ({}) W absorbed power: ({}) W'.format(
            T_out[T], amax, emax)
        # plot
        plt.errorbar(absorbed[T].v(),
                     emitted[T].v(),
                     xerr=absorbed[T].e(),
                     yerr=emitted[T].e(),
                     c=cols[cnt],
                     linestyle=' ')
        plt.plot(absorbed[T].v(),
                 m0[T].v() * absorbed[T].v() + q0[T].v(),
                 c=cols[cnt + 1])

        plt.text(textx,
                 texty1[T],
                 '${0}$$^\circ$C: ${1}$ %'.format(T_out[T],
                                                  m0[T].round(3) * 100),
                 color=cols[cnt],
                 fontsize=fontsize)
        cnt += 3

    plt.title(title)
    plt.xlabel('Absorbed power (W)')
    plt.ylabel('Emited power (W)')
    plt.xlim(xlim)
    plt.ylim(ylim1)
    plt.grid('on')

    #plt.show()

    #------------------------------------
    plt.subplot(3, 1, 2)
    cnt = 0  # reset color counter

    q1, m1 = {}, {}
    for T in Temperatures:
        relref = reflected[T] / pumped[T] * 100

        # plot
        plt.errorbar(absorbed[T].v(),
                     relref.v(),
                     xerr=absorbed[T].e(),
                     yerr=relref.e(),
                     c=cols[cnt],
                     linestyle=' ')
        cnt += 3

    plt.title(title)
    plt.xlabel('Absorbed power (W)')
    plt.ylabel('Reflectivity (%)')
    plt.xlim(xlim)
    plt.ylim(ylim2)
    plt.grid('on')

    #plt.show()

    #------------------------------------
    # plot dissipation and spectra
    plt.subplot(3, 1, 3)
    cnt = 0  # reset

    q3, m3 = {}, {}
    for T in Temperatures:
        if T in plot_temps_for_3:
            # lambda_short
            #plt.errorbar(dissipated[T].v(),spectra[T][0].v(),
            #             xerr=dissipated[T].e(),yerr=spectra[T][0].e(),
            #             c=cols[cnt],linestyle=' ')

            # lambda_long
            # lin reg for range that lases (>threshold, <roll over), hence instr from subplot 1
            q3[T], m3[T] = ev.linreg(dissipated[T].v()[llow0[T]:lhigh0[T]],
                                     spectra[T][1].v()[llow0[T]:lhigh0[T]],
                                     spectra[T][1].e()[llow0[T]:lhigh0[T]],
                                     overwrite_zeroerrors=True)

            # show only a part, not to confuse reader
            #plt.errorbar(dissipated[T].v()[llow0[T]:lhigh0[T]],spectra[T][1].v()[llow0[T]:lhigh0[T]],
            #             xerr=dissipated[T].e()[llow0[T]:lhigh0[T]],yerr=spectra[T][1].e()[llow0[T]:lhigh0[T]],
            #             c=cols[cnt],linestyle=' ')

            # show the whole range
            plt.errorbar(dissipated[T].v(),
                         spectra[T][1].v(),
                         xerr=dissipated[T].e(),
                         yerr=spectra[T][1].e(),
                         c=cols[cnt],
                         linestyle=' ')

        cnt += 3

    plt.title(title)
    plt.xlim(xlim3)
    plt.ylim(ylim3)
    plt.xlim()
    plt.xlabel('Dissipated power (W)')
    plt.ylabel('Wavelength (nm)')
    plt.grid('on')
    cnt = 0  # reset

    wavelength = ev.errvallist([q3[T] for T in plot_temps_for_3
                                ])  # wavelength offsets
    slopes = ev.errvallist([m3[T] for T in plot_temps_for_3])  # slopes
    T_active = ev.errvallist([T_out[T] for T in plot_temps_for_3])

    dldD, dldT, l0 = thermal_resistance(T_active, wavelength, slopes)  #, R_th
    R_th = dldD / dldT
    for T in Temperatures:
        if T in plot_temps_for_3:
            plt.plot(dissipated[T].v(),
                     l0.v() + dldT.v() * T_out[T].v() +
                     dldD.v() * dissipated[T].v(),
                     c=cols[cnt + 1])
        cnt += 3

    plt.text(textx3,
             texty3[0],
             '$\lambda=$' + '$({})$'.format(dldT.round(3)) + '$T_{hs}+$' +
             '$({})$'.format(dldD.round(3)) + '$D+$' +
             '${}$'.format(l0.round(3)),
             color='k')

    R_th = R_th.round(2)
    therm_imp = 'Thermal impedance: $({0})$ K/W'.format(R_th)
    plt.text(textx3, texty3[1], therm_imp, color='k')
    print therm_imp

    for T in Temperatures:
        print meantemp[T]

    plt.show()
Exemplo n.º 5
0
def calibrate_pump(logfile1,calibfile_pp,calibplot_pp,calibfile_cp,calibplot_cp):


    #------------------------------------
    #current_set,current,pump,reflection,emission,absorption = extract(logfile,identifiers=['Current','Pump','Refl','Laser'])
    current_set1, current, pump, thermal = extract(logfile1, identifiers=['Current','Pump','Laser'])

    #------------------------------------
    # plot instructions

    title = 'Pump'
    Tp, Tt = pump.keys()[0], thermal.keys()[0] # we care only about one temperature, actually, for calibration Temp is irrelevant anyway
    xmin, xmax = ev.min(pump[Tp],False), ev.max(pump[Tp],False)
    ymin, ymax = ev.min(thermal[Tt],False), ev.max(thermal[Tt],False)
    xlim = [xmin.v()-2*xmin.e(),xmax.v()+2*xmax.e()]
    ylim = [ymin.v()-2*ymin.e(),ymax.v()+2*ymax.e()]
    textx, texty = xmax.v()/4, ymax.v()*2/3

    cols = varycolor(3*len(pump)) # 3 per temperature

    plt.clf()
    plt.subplot(1,1,1)

    # linreg
    q0,m0 = ev.linreg(pump[Tp].v(),thermal[Tt].v(),thermal[Tt].e())

    # plot
    plt.errorbar(pump[Tp].v(),thermal[Tt].v(),
                 xerr=pump[Tp].e(),yerr=thermal[Tt].e(),
                 c=cols[0],linestyle=' ')
    plt.plot(pump[Tp].v(),m0.v()*pump[Tp].v()+q0.v(),c=cols[1])

    summary = r'(${0}$) $\times$ pump + (${1}$) W'.format(m0.round(2),q0.round(2))
    plt.text(textx,texty, summary,color='k')


    plt.title(title)
    plt.xlabel('Power seen by S121C (photodiode) (W)')
    plt.ylabel('Power seen by S314C (thermal PM) (W)')
    plt.xlim(xlim)
    plt.ylim(ylim)
    plt.grid('on')

    #
    plt.savefig(calibplot_pp)
    #plt.show()
    #
    #
    
    title = 'Pump (wrt current)'
    Tc = current.keys()[0]
    xmin, xmax = ev.min(current[Tp],False), ev.max(current[Tp],False)
    ymin, ymax = ev.min(thermal[Tt],False), ev.max(thermal[Tt],False)
    xlim = [xmin.v()-2*xmin.e(),xmax.v()+2*xmax.e()]
    ylim = [ymin.v()-2*ymin.e(),ymax.v()+2*ymax.e()]
    textx, texty = xmax.v()/4, ymax.v()*2/3
    start_linreg_at = 6 #A
    #end_linreg_at = ..
    
    sind = sum(current[Tc].v()<start_linreg_at)
    #eind = sum(current[Tc].v()<end_linreg_at)
        
    plt.clf()
    plt.subplot(1,1,1)

    # linreg
    q1,m1 = ev.linreg(current[Tc].v()[sind:],thermal[Tt].v()[sind:],thermal[Tt].e()[sind:])

    # plot
    plt.errorbar(current[Tc].v(),thermal[Tt].v(),
                 xerr=current[Tc].e(),yerr=thermal[Tt].e(),
                 c=cols[0],linestyle=' ')
    plt.plot(current[Tc].v(),m1.v()*current[Tc].v()+q1.v(),c=cols[1])

    summary = r'(${0}$) $\times$ current (${1}$) W'.format(m1.round(2),q1.round(2))
    plt.text(textx,texty, summary,color='k')


    plt.title(title)
    plt.xlabel('Achieved current setting (A)')
    plt.ylabel('Power seen by S314C (thermal PM) (W)')
    plt.xlim(xlim)
    plt.ylim(ylim)
    plt.grid('on')

    #plt.show()
    plt.savefig(calibplot_cp)
    
    #------------------------------------
    # write file with evaluation as LUT
    with open(calibfile_pp,'wb') as pf:
        pf.write(u'columns=PM_pump(W),PM_pump_sterr(W),PM_reference(W),PM_reference_sterr(W);linreg={0}*p+{1}\n'.format(ev.errval(m0,printout='cp!'),ev.errval(q0,printout='cp!')))
        for entry in range(len(pump[Tp])):
            pf.write(u'{0},{1},{2},{3}\n'.format( pump[Tp].v()[entry],pump[Tp].e()[entry],
                                                  thermal[Tt].v()[entry],thermal[Tt].e()[entry] ))
    with open(calibfile_cp,'wb') as cf:
        cf.write(u'columns=current(A),current_sterr(A),PM_reference(W),PM_reference_sterr(W);linreg={0}*c+{1}\n'.format(ev.errval(m1,printout='cp!'),ev.errval(q1,printout='cp!')))
        for entry in range(len(current[Tc])):
            cf.write(u'{0},{1},{2},{3}\n'.format( current[Tc].v()[entry],current[Tc].e()[entry],
                                                  thermal[Tt].v()[entry],thermal[Tt].e()[entry] ))
    
    print u'Pump calibration finished:\n{0}\n{1}\n{2}\n{3}'.format(calibfile_pp,calibplot_pp,calibfile_cp,calibplot_cp)
Exemplo n.º 6
0
def calibrate_reflection(logfile2, logfile3, calibfile_r, calibplot_r):

    #------------------------------------
    #current,pump,reflection,emission,absorption = extract(logfile,identifiers=['Current','Pump','Refl','Laser'])
    current_set2, current2, thermal = extract(logfile2,
                                              identifiers=['Current', 'Laser'])
    current_set3, current3, reflection = extract(
        logfile3, identifiers=['Current', 'Refl'])

    #------------------------------------
    # plot instructions

    title = 'Reflection'
    Tr, Tt = reflection.keys()[0], thermal.keys(
    )[0]  # we care only about one temperature, actually, for calibration Temp is irrelevant anyway
    xmin, xmax = ev.min(reflection[Tr], False), ev.max(reflection[Tr], False)
    ymin, ymax = ev.min(thermal[Tt], False), ev.max(thermal[Tt], False)
    xlim = [xmin.v() - 2 * xmin.e(), xmax.v() + 2 * xmax.e()]
    ylim = [ymin.v() - 2 * ymin.e(), ymax.v() + 2 * ymax.e()]
    textx, texty = xmax.v() / 4, ymax.v() * 2 / 3

    cols = varycolor(3 * len(reflection))  # 3 per temperature

    plt.clf()
    plt.subplot(1, 1, 1)

    # linreg
    q0, m0 = ev.linreg(reflection[Tr].v(), thermal[Tt].v(), thermal[Tt].e())

    # plot
    plt.errorbar(reflection[Tr].v(),
                 thermal[Tt].v(),
                 xerr=reflection[Tr].e(),
                 yerr=thermal[Tt].e(),
                 c=cols[0],
                 linestyle=' ')
    plt.plot(reflection[Tr].v(),
             m0.v() * reflection[Tr].v() + q0.v(),
             c=cols[1])

    summary = r'(${0}$) $\times$ refl + (${1}$) W'.format(
        m0.round(2), q0.round(2))
    plt.text(textx, texty, summary, color='k')

    plt.title(title)
    plt.xlabel('Power seen by S121C (photodiode) (W)')
    plt.ylabel('Power seen by S314C (thermal PM) (W)')
    plt.xlim(xlim)
    plt.ylim(ylim)
    plt.grid('on')

    #plt.show()
    plt.savefig(calibplot_r)

    #------------------------------------
    # write file with evaluation as LUT
    with open(calibfile_r, 'wb') as rf:
        rf.write(
            u'columns=PM_refl(W),PM_refl_sterr(W),PM_reference(W),PM_reference_sterr(W);linreg={0}*r+{1}\n'
            .format(ev.errval(m0, printout='cp!'), ev.errval(q0,
                                                             printout='cp!')))
        for entry in range(len(reflection[Tr])):
            rf.write(u'{0},{1},{2},{3}\n'.format(reflection[Tr].v()[entry],
                                                 reflection[Tr].e()[entry],
                                                 thermal[Tt].v()[entry],
                                                 thermal[Tt].e()[entry]))

    print u'Reflection calibration finished:\n{0}\n{1}'.format(
        calibfile_r, calibplot_r)
Exemplo n.º 7
0
def calibrate_pump(logfile1,logfile2,calibfile_pp,calibplot_pp,calibfile_cp,calibplot_cp):

    # logfile0 w/ directly attached P-I measurement
    #  here we assume the P-I relation to be constant
    
    # logfile1 w/ P-I measurement after BS
    #  (logfile0 and 1 give BS-fraction assumed to be constant)
    # logfile2 w/ "emission" measurement for whole I-range
    #  from 2 find P-I relation, transform I into P with results from 1
    #  this gives a P-P relation for pump.
    #
    # drop 0-measurement and work with P-I relation from logfile1

    #------------------------------------
    #current_set,current,pump,reflection,emission,absorption = extract(logfile,identifiers=['Current','Pump','Refl','Laser'])
    current_set1, current1, thermal1 = extract(logfile1, identifiers=['Current','Laser'])
    current_set2, current2, pump2 = extract(logfile2, identifiers=['Current','Pump'])

    T1, T2 = current1.keys()[0], current2.keys()[0] # because the protocol writes HS temperature that we're not interested in during calibration (lazy.)
    

    #------------------------------------
    cols = varycolor(3*len(current1)) # 3 per temperature
    
    
    # P-I (1)
    xmin, xmax = ev.min(current1[T1],False), ev.max(current1[T1],False)
    ymin, ymax = ev.min(thermal1[T1],False), ev.max(thermal1[T1],False)
    xlim = [xmin.v()-2*xmin.e(),xmax.v()+2*xmax.e()]
    ylim = [ymin.v()-2*ymin.e(),ymax.v()+2*ymax.e()]
    textx, texty = xmax.v()/4, ymax.v()*2/3
    
    start_linreg_at = 6 #A
    
    sind1 = sum(current1[T1].v()<start_linreg_at)
    
    q1,m1 = ev.linreg(current1[T1].v()[sind1:],thermal1[T1].v()[sind1:],thermal1[T1].e()[sind1:])
    
    if False:
        plt.clf()
        plt.subplot(1,1,1)
        
        plt.errorbar(current1[T1].v(),thermal1[T1].v(),
                     xerr=current1[T1].e(),yerr=thermal1[T1].e(),
                     c=cols[0],linestyle=' ')
        plt.plot(current1[T1].v(),m1.v()*current1[T1].v()+q1.v(),c=cols[1])
        summary = r'(${0}$) $\times$ pump + (${1}$) W'.format(m1.round(2),q1.round(2))
        plt.text(textx,texty, summary,color='k')
        plt.title('P-I pos1 -- supposed to be linear relation!')
        plt.xlabel('Pump current (A)')
        plt.ylabel('Power seen by S314C (thermal PM) (W)')
        plt.xlim(xlim)
        plt.ylim(ylim)
        plt.grid('on')
        plt.show()
    
    
    # P-I (2)
    xmin, xmax = ev.min(current2[T2],False), ev.max(current2[T2],False)
    ymin, ymax = ev.min(pump2[T2],False), ev.max(pump2[T2],False)
    xlim = [xmin.v()-2*xmin.e(),xmax.v()+2*xmax.e()]
    ylim = [ymin.v()-2*ymin.e(),ymax.v()+2*ymax.e()]
    textx, texty = xmax.v()/4, ymax.v()*2/3
    
    start_linreg_at = 6 #A
    
    sind2 = sum(current2[T2].v()<start_linreg_at)
    
    q2,m2 = ev.linreg(current2[T2].v()[sind2:],pump2[T2].v()[sind2:],pump2[T2].e()[sind2:])
    
    if False:
        plt.clf()
        plt.subplot(1,1,1)
    
        plt.errorbar(current2[T2].v(),pump2[T2].v(),
                     xerr=current2[T2].e(),yerr=pump2[T2].e(),
                     c=cols[0],linestyle=' ')
        plt.plot(current2[T2].v(),m2.v()*current2[T2].v()+q2.v(),c=cols[1])
        summary = r'(${0}$) $\times$ pump + (${1}$) W'.format(m2.round(2),q2.round(2))
        plt.text(textx,texty, summary,color='k')
        plt.title('P-I pump')
        plt.xlabel('Pump current (A)')
        plt.ylabel('Power seen by S121C (photodiode) (W)')
        plt.xlim(xlim)
        plt.ylim(ylim)
        plt.grid('on')
        plt.show()
        
    
    # ----------------------------------
    # with m1,q1 scale current from 2
    
    plt.clf()
    plt.subplot(1,1,1)
    

    pump_ = ev.errvallist([ev.max(ev.errvallist([0,p]),False) for p in current2[T2]*m1+q1]) # ignore values below pump threshold
    nzeros = np.sum(pump_.v()==0)

    
    xmin, xmax = ev.min(pump2[T2],False), ev.max(pump2[T2],False)
    ymin, ymax = ev.min(pump_,False), ev.max(pump_,False)
    xlim = [xmin.v()-2*xmin.e(),xmax.v()+2*xmax.e()]
    ylim = [ymin.v()-2*ymin.e(),ymax.v()+2*ymax.e()]
    textx, texty = xmax.v()/4, ymax.v()*2/3
    
    
    q3,m3 = ev.linreg(pump2[T2].v()[nzeros:],pump_.v()[nzeros:],pump_.e()[nzeros:])
    
    plt.errorbar(pump2[T2].v(),pump_.v(),
                 xerr=pump2[T2].e(),yerr=pump_.e(),
                 c=cols[0],linestyle=' ')
    plt.plot(pump2[T2].v(),m3.v()*pump2[T2].v()+q3.v(),c=cols[1])
    
    summary = r'(${0}$) $\times$ pump + (${1}$) W'.format(m3.round(2),q3.round(2))
    plt.text(textx,texty, summary,color='k')
    
    plt.title('Pump')
    plt.xlabel('Power seen by S121C (photodiode) (W)')
    plt.ylabel('Power at sample (W)')
    plt.xlim(xlim)
    plt.ylim(ylim)
    plt.grid('on')
    
    #plt.show()
    plt.savefig(calibplot_pp)
    
    #
    #
    # P-I (scaled)
    
    plt.clf()
    plt.subplot(1,1,1)
    
    xmin, xmax = ev.min(current2[T2],False), ev.max(current2[T2],False)
    ymin, ymax = ev.min(pump_,False), ev.max(pump_,False)
    xlim = [xmin.v()-2*xmin.e(),xmax.v()+2*xmax.e()]
    ylim = [ymin.v()-2*ymin.e(),ymax.v()+2*ymax.e()]
    textx, texty = xmax.v()/4, ymax.v()*2/3
    start_linreg_at = 20 #A
    #end_linreg_at = ..
    
    sind = sum(current2[T2].v()<start_linreg_at)
    #eind = sum(current[Tc].v()<end_linreg_at)
        

    # linreg
    q4,m4 = ev.linreg(current2[T2].v()[sind:],pump_.v()[sind:],pump_.e()[sind:])

    # plot
    plt.errorbar(current2[T2].v(),pump_.v(),
                 xerr=current2[T2].e(),yerr=pump_.e(),
                 c=cols[0],linestyle=' ')
    plt.plot(current2[T2].v(),m4.v()*current2[T2].v()+q4.v(),c=cols[1])

    summary = r'(${0}$) $\times$ current (${1}$) W'.format(m4.round(2),q4.round(2))
    plt.text(textx,texty, summary,color='k')


    plt.title('Pump (wrt current)')
    plt.xlabel('Achieved current setting (A)')
    plt.ylabel('Power at sample (W)')
    plt.xlim(xlim)
    plt.ylim(ylim)
    plt.grid('on')

    #plt.show()
    plt.savefig(calibplot_cp)
    
    #exit()
    
    #------------------------------------
    # write file with evaluation as LUT
    with open(calibfile_pp,'wb') as pf:
        pf.write(u'columns=PM_pump(W),PM_pump_sterr(W),PM_reference(W),PM_reference_sterr(W);linreg={0}*p+{1}\n'.format(ev.errval(m3,printout='cp!'),ev.errval(q3,printout='cp!')))
        for entry in range(len(pump_)):
            pf.write(u'{0},{1},{2},{3}\n'.format( pump2[T2].v()[entry],pump2[T2].e()[entry],
                                                  pump_.v()[entry],pump_.e()[entry] ))
    with open(calibfile_cp,'wb') as cf:
        cf.write(u'columns=current(A),current_sterr(A),PM_reference(W),PM_reference_sterr(W);linreg={0}*c+{1}\n'.format(ev.errval(m4,printout='cp!'),ev.errval(q4,printout='cp!')))
        for entry in range(len(current2[T2])):
            cf.write(u'{0},{1},{2},{3}\n'.format( current2[T2].v()[entry],current2[T2].e()[entry],
                                                  pump_.v()[entry],pump_.e()[entry] ))
    
    print u'Pump calibration finished:\n{0}\n{1}\n{2}\n{3}'.format(calibfile_pp,calibplot_pp,calibfile_cp,calibplot_cp)