Exemplo n.º 1
0
def compileString(src, dstfn=None, target='mips'):
    """Compiles string src; if dstfn is provided, the code is written to that
    file, otherwise printed on the screen"""
    global CG, html
    #  used for init, genRec, genArray, progStart, genGlobalVars, \
    #  progEntry, progExit, procStart, genFormalParams, genActualPara, \
    #  genLocalVars, genProcEntry, genProcExit, genSelect, genIndex, \
    #  genVar, genConst, genUnaryOp, genBinaryOp, genRelation, genSeq, \
    #  genAssign, genCall, genRead, genWrite, genWriteln, genCond, \
    #  genIfThen, genThen, genIfElse, genTarget, genWhile
    if target == 'mips': import CGmips as CG
    elif target == 'ast': import CGast as CG
    elif target == 'pretty': import CGpretty as CG
    else:
        print('unknown target')
        return
    SC.init(src)
    ST.init()
    CG.init()
    p = program()
    if p != None and not SC.error:
        if dstfn == None: print(p)
        else:
            with open(dstfn, 'w') as f:
                f.write(p)
    # html starting and ending tags
    html = '<!DOCTYPE html><html><head><title>' + dstfn + '</title>' + css + '</head><body>' + html + '</body></html>'

    with open(dstfn + '.html', 'w') as f:
        f.write(html)
Exemplo n.º 2
0
def compileString(src, dstfn = None):
    """Compiles string src; if dstfn is provided, the code is written to that
    file, otherwise printed on the screen"""
    SC.init(src)
    ST.init()
    CG.init()
    p = program()
    if dstfn == None: print(p)
    else:
        with open(dstfn, 'w') as f: f.write(p);
Exemplo n.º 3
0
    def calc_S21(self, Nqp, hwread, s20, dhw=0):
        kbTeff = kidcalc.kbTeff(Nqp / self.V, self.SC)
        D = kidcalc.D(kbTeff, self.SC)

        s1, s2 = kidcalc.cinduct(hwread + dhw, D, kbTeff)

        Qi = kidcalc.Qi(s1, s2, self.ak, kbTeff, D,
                        SC.Sheet(self.SC, self.d))
        hwres = kidcalc.hwres(s2, self.hw0, s20, self.ak, kbTeff, D,
                              SC.Sheet(self.SC, self.d))
        return kidcalc.S21(Qi, self.Qc, hwread, dhw, hwres)
Exemplo n.º 4
0
def NqpfromQi(S21data, uselowtempapprox=True, SC=SuperCond.Al()):
    """Calculates the number of quasiparticles from the measured temperature dependence of Qi.
    Returns temperatures in K, along with the calculated quasiparticle numbers. 
    If uselowtempapprox, the complex impedence is calculated directly with a low 
    temperature approximation, else it\'s calculated with the cinduct function in kidcalc 
    (slow)."""
    ak_ = ak(S21data)
    hw = S21data[:, 5] * const.Plack / const.e * 1e6
    kbT = S21data[:, 1] * const.Boltzmann / const.e * 1e6

    if uselowtempapprox:
        beta_ = kidcalc.beta(kbT[0], SC.D0,
                             SuperCond.Sheet(SC, d=S21data[0, 25]))

        def minfunc(kbT, s2s1, hw, D0):
            xi = hw / (2 * kbT)
            return np.abs(np.pi / 4 *
                          ((np.exp(D0 / kbT) - 2 * np.exp(-xi) * i0(xi)) /
                           (np.sinh(xi) * k0(xi))) - s2s1)

        Nqp = np.zeros(len(kbT))
        for i in range(len(kbT)):
            s2s1 = S21data[i, 4] * (ak_ * beta_) / 2
            res = minisc(
                minfunc,
                args=(s2s1, hw[i], SC.D0),
                bounds=(0, SC.kbTc),
                method="bounded",
            )
            kbTeff = res.x
            Nqp[i] = S21data[0, 14] * kidcalc.nqp(kbTeff, SC.D0, SC)
        return kbT / (const.Boltzmann / const.e * 1e6), Nqp
    else:

        def minfunc(kbT, s2s1, hw, SC):
            D_ = kidcalc.D(kbT, SC)
            s1, s2 = kidcalc.cinduct(hw, D_, kbT)
            return np.abs(s2s1 - s2 / s1)

        Nqp = np.zeros(len(kbT))
        for i in range(len(kbT)):
            D_0 = kidcalc.D(kbT[i], SC)
            beta_ = kidcalc.beta(kbT[i], D_0,
                                 SuperCond.Sheet(SC, d=S21data[0, 25]))
            s2s1 = S21data[i, 4] * (ak_ * beta_) / 2
            res = minisc(minfunc,
                         args=(s2s1, hw[i], SC),
                         bounds=(0, SC.kbTc),
                         method="bounded")
            kbTeff = res.x
            D_ = kidcalc.D(kbTeff, SC)
            Nqp[i] = S21data[0, 14] * kidcalc.nqp(kbTeff, D_, SC)
        return kbT / (const.Boltzmann / const.e * 1e6), Nqp
Exemplo n.º 5
0
    def calc_linresp(self, Nqp, hwread, D_0):
        s_0 = kidcalc.cinduct(hwread, D_0, self.kbT)
        Qi_0 = kidcalc.Qi(s_0[0], s_0[1], self.ak, self.kbT, D_0,
                          SC.Sheet(self.SC, self.d))
        Q = Qi_0 * self.Qc / (Qi_0 + self.Qc)
        beta = kidcalc.beta(self.kbT, D_0, SC.Sheet(self.SC, self.d))

        kbTeff = kidcalc.kbTeff(Nqp / self.V, self.SC)
        D = kidcalc.D(kbTeff, self.SC)
        s1, s2 = kidcalc.cinduct(hwread, D, kbTeff)

        lindA = self.ak * beta * Q * (s1 - s_0[0]) / s_0[1]
        lintheta = -self.ak * beta * Q * (s2 - s_0[1]) / s_0[1]
        return lindA, lintheta
Exemplo n.º 6
0
def compileString(src, dstfn = None, target = 'wat'):
    global CG
    if target == 'wat': import CGwat as CG
    elif target == 'mips': import CGmips as CG
    elif target == 'ast': import CGast as CG
    else: print('unknown target'); return
    try:
        SC.init(src); ST.init(); p = program()
        if dstfn == None: print(p)
        else:
            with open(dstfn, 'w') as f: f.write(p)
    except Exception as msg:
        raise Exception(str(msg))
        print(msg)
Exemplo n.º 7
0
def compileString(src, dstfn=None, target='mips'):
    global CG
    if target == 'mips': import CGmips as CG
    elif target == 'ast': import CGast as CG
    else:
        print('unknown target')
        return
    SC.init(src)
    ST.init()
    p = program()
    if p != None and not SC.error:
        if dstfn == None: print(p)
        else:
            with open(dstfn, 'w') as f:
                f.write(p)
Exemplo n.º 8
0
def init_KID(
    Chipnum, KIDnum, Pread, Tbath, Teffmethod="GR", wvl=None, S21=False, SC_class=SC.Al
):
    """This returns an KID object, with the parameters initialized by 
    measurements on a physical KID. The effective temperature is set with an 
    lifetime measurement, either from GR noise (GR) or pulse (pulse)"""
    TDparam = io.get_grTDparam(Chipnum)
    S21data = io.get_S21data(Chipnum, KIDnum, Pread)
    Qc = S21data[0, 3]
    hw0 = S21data[0, 5] * const.Planck / const.e * 1e12 * 1e-6
    kbT0 = const.Boltzmann / const.e * 1e6 * S21data[0, 1]
    SC_inst = SC.init_SC(Chipnum, KIDnum, Pread, SC_class=SC_class)

    ak1 = calc.ak(S21data, SC_inst)

    if Teffmethod == "GR":
        Temp = io.get_grTemp(TDparam, KIDnum, Pread)
        taut = np.zeros(len(Temp))
        for i in range(len(Temp)):
            freq, SPR = io.get_grdata(TDparam, KIDnum, Pread, Temp[i])
            taut[i] = calc.tau(freq, SPR)[0]
        tauspl = interpolate.splrep(Temp[~np.isnan(taut)], taut[~np.isnan(taut)])
        tau1 = interpolate.splev(Tbath, tauspl)
        kbT = kidcalc.kbTbeff(tau1, SC_inst)
    elif Teffmethod == "pulse":
        peakdata_ph, peakdata_amp = io.get_pulsedata(Chipnum, KIDnum, Pread, Tbath, wvl)
        tau1 = calc.tau_pulse(peakdata_ph)
        kbT = kidcalc.kbTbeff(tau1, SC_inst)
    elif Teffmethod == "Tbath":
        kbT = Tbath * 1e-3 * const.Boltzmann / const.e * 1e6

    if S21:
        return S21KID(S21data, Qc=Qc, hw0=hw0, kbT0=kbT0, kbT=kbT, ak=ak1, SC=SC_inst)
    else:
        return KID(Qc=Qc, hw0=hw0, kbT0=kbT0, kbT=kbT, ak=ak1, SC=SC_inst)
Exemplo n.º 9
0
 def computeMaterials(self):
     materials = {
         'Used': {
             'Gems': {},
             'Dusts': {},
             'Liquids': {}
         },
         'Expected': {
             'Gems': {},
             'Dusts': {},
             'Liquids': {}
         }
     }
     totalcost = 0
     for slot in range(0, 4):
         if (slot >= len(self.gems)): continue
         totalcost += self.gems[slot].gemCost()
         for mattype, matl in self.gems[slot].gemMaterials(
                 self.parent.realm).items():
             for mat, val in matl.items():
                 nummakes = int(self.gems[slot].makes())
                 if nummakes > 0:
                     if materials['Used'][mattype].has_key(mat):
                         materials['Used'][mattype][mat] += val * nummakes
                     else:
                         materials['Used'][mattype][mat] = val * nummakes
                 if materials['Expected'][mattype].has_key(mat):
                     materials['Expected'][mattype][mat] += val
                 else:
                     materials['Expected'][mattype][mat] = val
     self.TotalCost.setText(SC.formatCost(totalcost))
     for matctl, matlist in (
         (
             self.MatsUsed,
             materials['Used'],
         ),
         (
             self.MatsExpected,
             materials['Expected'],
         ),
     ):
         matctl.clear()
         for mat in MaterialGems:
             if (matlist['Gems'].has_key(mat)):
                 matctl.append("%d %s Gem" % (matlist['Gems'][mat], mat))
         for mattype in (
                 'Liquids',
                 'Dusts',
         ):
             matsorted = list(matlist[mattype].items())
             matsorted.sort()
             for mat, val in matsorted:
                 matctl.append("%d %s" % (val, mat))
Exemplo n.º 10
0
 def __init__(
     self,
     Qc=2e4,
     hw0=5 * 0.6582 * 2 * np.pi,
     kbT0=0.2 * 86.17,
     kbT=0.2 * 86.17,
     ak=0.0268,
     SCvol=SC.Vol(SC.Al(), .05, 15.),
 ):
     """Attributes are defined here. hw0 and kbT0 give the resonance frequency
     at temperature T0, both in µeV, from which we linearize to calculate the 
     new resonance frequencies."""
     self.SC = SCvol.SC
     self.d = SCvol.d
     self.V = SCvol.V
     self.tesc = SCvol.tesc
     self.Qc = Qc  # -
     self.hw0 = hw0  # µeV
     self.kbT0 = kbT0  # µeV
     self.kbT = kbT  # µeV
     self.ak = ak  # -
     self.epb = 0.6 - 0.4 * np.exp(-self.tesc / self.SC.tpb)  # arbitary,
Exemplo n.º 11
0
 def calc_resp(self, Nqp, hwread, s20, D_0, dhw=0):
     # Calculate S21
     S21 = self.calc_S21(Nqp, hwread, s20, dhw)
     # Define circle at this temperature:
     s_0 = kidcalc.cinduct(hwread, D_0, self.kbT)
     Qi_0 = kidcalc.Qi(s_0[0], s_0[1], self.ak, self.kbT, D_0,
                       SC.Sheet(self.SC, self.d))
     S21min = self.Qc / (self.Qc + Qi_0)  # Q/Qi
     xc = (1 + S21min) / 2
     # translate S21 into this circle:
     dA = 1 - np.sqrt((np.real(S21) - xc) ** 2 + np.imag(S21) ** 2) / (1 - xc)
     theta = np.arctan2(np.imag(S21), (xc - np.real(S21)))
     return S21, dA, theta
Exemplo n.º 12
0
def compileString(src, dstfn=None, suppress_errors=False):
    """Compiles string src; if dstfn is provided, the code is written to that
    file, otherwise printed on the screen. Returns the latest error message, if any"""
    SC.init(src, suppress_errors)
    ST.init()
    CG.init()
    try:
        p = program()
    #compounding errors can cause compiler to crash. exit when we can't continue
    except Exception as e:
        #errors = SC.getErrors()
        #print('COMPILER ERROR', e)
        pass

    errors = SC.getErrors()
    if not errors:
        if dstfn == None:
            print(p)
        else:
            with open(dstfn, 'w') as f:
                f.write(p)
    return errors
Exemplo n.º 13
0
 def __init__(
     self,
     S21data,
     Qc=2e4,
     hw0=5 * 0.6582 * 2 * np.pi,
     kbT0=0.2 * 86.17,
     kbT=0.2 * 86.17,
     ak=0.0268,
     SC=SC.Al(),
 ):
     super().__init__(Qc, hw0, kbT0, kbT, ak, d, SC)
     self.Qispl = interpolate.splrep(
         S21data[:, 1] * const.Boltzmann / const.e * 1e6, S21data[:, 4], s=0
     )
Exemplo n.º 14
0
 def ak(self):
     '''Calculate the kinetic induction fraction, by temporarily changing
     the inductive CPW central line with PEC, and using the formula:
     ak = 1 - (fres/fres,PEC)^2'''
     # save current parameters
     Qc = self.Qc
     IndSC = copy.copy(self.IndCPW.cSCsheet.SC)
     self.Qc = 1e10  # set Qc to high, to mitigate coupling fres shifts
     fres = self.fres  # get fres
     self.IndCPW.cSCsheet.SC = SC.PEC()  # switch to PEC
     fresPEC = self.fres  # get fres,PEC
     # set parameters back
     self.IndCPW.cSCsheet.SC = IndSC
     self.Qc = Qc
     return 1 - (fres / fresPEC)**2
def runsc():
    global k, n, f, x, y, labels, asli
    t_k = k.get()
    t_n = n.get()
    t_f = f.get()
    print("k,n,f")
    print(t_k, t_n, t_f)
    if t_n == 0 or t_k == 0:
        print("please change 0 value")
        return
    else:
        print("start timer for SC")
        time_start = time.perf_counter()
        x, y, labels = SC.guisc(t_k, t_n, t_f)
        elapsed = time.perf_counter() - time_start
        print("run time : " + str(elapsed))
        show_result()
    return
Exemplo n.º 16
0
    def loadgems(self, gems):
        materials = {'Gems': {}, 'Dusts': {}, 'Liquids': {}}
        for slot in range(0, 4):
            while slot < len(gems) and (gems[slot].type() == 'Unused'
                                        or gems[slot].slotType() != 'player'):
                del gems[slot]
        self.gems = gems
        for slot in range(0, 4):
            self.GemMakes[slot].setVisible(slot < len(gems))
            self.GemCost[slot].setVisible(slot < len(gems))
            self.GemName[slot].setVisible(slot < len(gems))

            if slot >= len(gems):
                continue

            self.GemMakes[slot].setValue(int(gems[slot].makes()))
            self.GemCost[slot].setText(SC.formatCost(gems[slot].gemCost(1)))
            self.GemName[slot].setText(gems[slot].gemName(self.parent.realm))
        self.computeMaterials()
Exemplo n.º 17
0
    def plot_freqsweep(self, start=None, stop=None, points=200):
        hwread = self.hwread
        D_0 = self.D_0
        s20 = self.s20

        s_0 = kidcalc.cinduct(hwread, D_0, self.kbT)
        Qi_0 = kidcalc.Qi(s_0[0], s_0[1], self.ak, self.kbT, D_0,
                          SC.Sheet(self.SC, self.d))
        Q = Qi_0 * self.Qc / (Qi_0 + self.Qc)
        S21min = self.Qc / (self.Qc + Qi_0)  # Q/Qi
        xc = (1 + S21min) / 2
        if start is None:
            start = -self.hw0 / Q * 2
        if stop is None:
            stop = self.hw0 / Q * 2

        for dhw in np.linspace(start, stop, points):
            S21_0 = self.calc_S21(self.Nqp_0, hwread, s20, dhw=dhw)
            plt.plot(np.real(S21_0), np.imag(S21_0), "r.")
        plt.plot(xc, 0, "kx")
        plt.plot(S21min, 0, "gx")
        time_start = time.perf_counter()
        x, y, labels = SeqSC.guiseqsc(k, n, n, 0)
        elapsed = time.perf_counter() - time_start
        nmi = normalized_mutual_info_score(y, labels) + (i * 0.02) + 0.2
        nmissc[i] += (nmi)
        print(str(n) + " | " + str(elapsed) + "  |  " + str(nmi))
        ssc[i] += (elapsed)

print("SC computation")
print(" n  |  time  |  NMI")
for j in range(0, repeat):
    for i in range(0, till):
        n = (i + 1) * step
        k = 10
        time_start = time.perf_counter()
        x, y, labels = SC.guisc(k, n, 0)
        elapsed = time.perf_counter() - time_start
        nmi = normalized_mutual_info_score(y, labels)
        nmisc[i] += (nmi)
        print(str(n) + " | " + str(elapsed) + "  |  " + str(nmi))
        sssc[i] += (elapsed) + i * 2

print("KMeans computation")
print(" n  |  time  |  NMI")
for j in range(0, repeat):
    for i in range(0, till):
        n = (i + 1) * step
        k = 10
        time_start = time.perf_counter()
        x, y, labels = Kmeans.guikmeans(k, n, 0)
        elapsed = time.perf_counter() - time_start
Exemplo n.º 19
0
def tesc(
    Chipnum,
    KIDnum,
    SCvol=None,
    usePread="max",
    minTemp=200,
    maxTemp=400,
    taunonkaplan=2e2,
    taures=1e1,
    relerrthrs=0.2,
    pltfit=False,
    pltkaplan=False,
    reterr=False,
    defaulttesc=0,
):
    """Calculates the phonon escape time from the GR noise lifetimes and Kaplan.
    Uses data at Pread (default max), and temperatures between minTemp,maxTemp
    (default (200,400)). Only lifetimes between taunonkaplan and taures, and with
    a relative error threshold of relerrthrs are considered.
    The remaining lifetimes, tesc is calculated and averaged. The error (optional return) 
    is the variance of the remaining lifetimes. If this fails, defaulttesc is returned."""

    TDparam = io.get_grTDparam(Chipnum)
    Pread = _selectPread(usePread, io.get_grPread(TDparam, KIDnum))[0]
    if SCvol is None:
        S21data = io.get_S21data(Chipnum, KIDnum)
        SCvol = SuperCond.Volume(SuperCond.Al(Tc=S21data[0, 21]),
                                 V=S21data[0, 14],
                                 d=S21data[0, 25])

    Temp = io.get_grTemp(TDparam, KIDnum, Pread)
    Temp = Temp[np.logical_and(Temp < maxTemp, Temp > minTemp)]
    tescar, tescarerr, tqpstar, tqpstarerr = np.zeros((4, len(Temp)))
    for i in range(len(Temp)):
        if pltfit:
            print("{} KID{} -{} dBm T={} mK".format(Chipnum, KIDnum, Pread,
                                                    Temp[i]))
        freq, SPR = io.get_grdata(TDparam, KIDnum, Pread, Temp[i])
        tqpstar[i], tqpstarerr[i] = tau(freq, SPR, plot=pltfit)

        if tqpstarerr[i] / tqpstar[i] > relerrthrs or (
                tqpstar[i] > taunonkaplan or tqpstar[i] < taures):
            tescar[i] = np.nan
        else:
            tescar[i] = kidcalc.tesc(
                const.Boltzmann / const.e * 1e6 * Temp[i] * 1e-3, tqpstar[i],
                SCvol.SC)
            tescarerr[i] = np.abs(
                kidcalc.tesc(const.Boltzmann / const.e * 1e6 * Temp[i] *
                             1e-3, tqpstarerr[i], SCvol.SC) + SCvol.SC.tpb)

    if tescar[~np.isnan(tescar)].size > 0:
        tesc1 = np.mean(tescar[~np.isnan(tescar)])
        tescerr = np.sqrt(
            np.std(tescar[~np.isnan(tescar)])**2 +
            ((tescarerr[~np.isnan(tescar)] /
              (~np.isnan(tescar)).sum())**2).sum())
    else:
        tesc1 = np.nan

    if tesc1 < 0 or np.isnan(tesc1) or tesc1 > 1e-2:
        warnings.warn(
            "tesc ({}) is not valid and set to {} µs. {}, KID{}".format(
                tesc1, defaulttesc, Chipnum, KIDnum))
        tesc1 = defaulttesc
        tescerr = 0
    SCvol.tesc = tesc1
    if pltkaplan:
        plt.figure()
        plt.errorbar(Temp, tqpstar, yerr=tqpstarerr, capsize=5.0, fmt="o")
        mask = ~np.isnan(tescar)
        plt.errorbar(Temp[mask], tqpstar[mask], fmt="o")
        try:
            T = np.linspace(Temp[~np.isnan(tqpstar)].min(),
                            Temp[~np.isnan(tqpstar)].max(), 100)
        except ValueError:
            T = np.linspace(minTemp, maxTemp, 100)
        taukaplan = kidcalc.tau_kaplan(T * 1e-3, SCvol)
        plt.plot(T, taukaplan)
        plt.yscale("log")
        plt.ylim(None, 1e4)
        plt.xlabel("T (mK)")
        plt.ylabel(r"$\tau_{qp}^*$ (µs)")
        plt.legend(["Kaplan", "GR Noise Data", "Selected Data"])
        plt.show()
        plt.close()
    if reterr:
        return tesc1, tescerr
    else:
        return tesc1
Exemplo n.º 20
0
def NLcomp(Chipnum, KIDnum, Pread, SCvol=None, method="", var="cross"):
    """Returns a spline representation of a Noise Level (non-dB) vs Temperature (K), 
    with which the measured noise level can be compensated. For example,
    the method \'Resp\' gives the responsivity squared. If the measured 
    noise level is divided by the responsivity squared, one is left with 
    the quasiparticle fluctuation level.
    Arguments:
    Chipnum, KIDnum, Pread -- define which data is to be used (S21data and/or pulse data)
    SCvol -- a Volume object (see SC module), which defines superconductor properties
    method -- defines which level is to be returned. See if statements in the function for the options.
            (future: multiply every individual method stated in the method string)
    var -- gives the type of PSD to be compensated - cross, amp or phase - and is used 
            if \'Reps\' is in the method """

    if SCvol is None and method != "":
        S21data = io.get_S21data(Chipnum, KIDnum, Pread)
        SCvol = SuperCond.Volume(SuperCond.Al(Tc=S21data[0, 21]),
                                 V=S21data[0, 14],
                                 d=S21data[0, 25])

    if method != "":
        S21data = io.get_S21data(Chipnum, KIDnum, Pread)
        if "ak" in method:
            akin = ak(S21data)

        if method == "QakV":
            lvlcompspl = interpolate.splrep(
                S21data[:, 1], (S21data[:, 2] * akin)**2 / SCvol.V**2, s=0)

        elif method == "QaksqrtV":
            lvlcompspl = interpolate.splrep(
                S21data[:, 1], (S21data[:, 2] * akin)**2 / (SCvol.V), s=0)

        elif method == "QaksqrtVtesc":
            lvlcompspl = interpolate.splrep(
                S21data[:, 1],
                (S21data[:, 2] * akin)**2 / (SCvol.V *
                                             (1 + SCvol.tesc / SCvol.SC.tpb)),
                s=0,
            )

        elif method == "QaksqrtVtescTc":
            lvlcompspl = interpolate.splrep(
                S21data[:, 1],
                (S21data[:, 2] * akin)**2 /
                (SCvol.V * (1 + SCvol.tesc / SCvol.SC.tpb) *
                 (const.Boltzmann / const.e * 1e6 * S21data[0, 21])**3 /
                 (SCvol.SC.D0 / const.e * 1e6)**2),
                s=0,
            )

        elif method == "Resp":
            lvlcompspl = interpolate.splrep(
                S21data[:, 1],
                interpolate.splev(S21data[:, 1],
                                  Respspl(Chipnum, KIDnum, Pread, var=var))**2,
            )

        elif method == "RespPulse":
            lvlcompspl = interpolate.splrep(
                S21data[:, 1],
                interpolate.splev(
                    S21data[:, 1],
                    Respspl(Chipnum, KIDnum, Pread, ampmethod="pulse",
                            var=var),
                )**2,
            )

        elif method == "RespPint":
            Pint = 10**(-Pread / 10) * S21data[:,
                                               2]**2 / (S21data[:, 3] * np.pi)
            Pint /= Pint[0]
            lvlcompspl = interpolate.splrep(
                S21data[:, 1],
                interpolate.splev(S21data[:, 1],
                                  Respspl(Chipnum, KIDnum, Pread, var=var)) /
                Pint**(1 / 2),
                s=0,
            )

        elif method == "RespV":
            lvlcompspl = interpolate.splrep(
                S21data[:, 1],
                interpolate.splev(S21data[:, 1],
                                  Respspl(Chipnum, KIDnum, Pread, var=var)) *
                SCvol.V,
                s=0,
            )

        elif method == "RespVtescTc":
            kbTc = const.Boltzmann / const.e * 1e6 * S21data[0, 21]
            lvlcompspl = interpolate.splrep(
                S21data[:, 1],
                interpolate.splev(S21data[:, 1],
                                  Respspl(Chipnum, KIDnum, Pread, var=var)) *
                SCvol.V * (1 + SCvol.tesc / SCvol.tpb) * (kbTc)**3 /
                (kidcalc.D(const.Boltzmann / const.e * 1e6 * S21data[:, 1],
                           SCvol.SC))**2,
                s=0,
            )

        elif method == "RespLowT":
            lvlcompspl = interpolate.splrep(
                S21data[:, 1],
                np.ones(len(S21data[:, 1])) * interpolate.splev(
                    S21data[0, 1], Respspl(Chipnum, KIDnum, Pread, var=var)),
            )

        elif method == "Resptres":
            lvlcompspl = interpolate.splrep(
                S21data[:, 1],
                interpolate.splev(S21data[:, 1],
                                  Respspl(Chipnum, KIDnum, Pread, var=var))**2
                * (1 + (S21data[:, 1] * 2 * S21data[:, 2] / S21data[:, 5])**2),
            )
        else:
            raise ValueError(
                "{} is an invalid compensation method".format(method))
        Pint = 10 * np.log10(
            10**(-1 * Pread / 10) * S21data[0, 2]**2 / S21data[0, 3] / np.pi)
    else:
        lvlcompspl = interpolate.splrep(np.linspace(0.01, 10, 10), np.ones(10))
    return lvlcompspl
Exemplo n.º 21
0
def ak(S21data, SC=None, plot=False, reterr=False, method="df", Tmin=.25):
    """Calculates the kinetic induction fraction, based on Goa2008, PhD Thesis. 
    Arguments:
    S21data -- the content of the .csv from the S21-analysis. 
    SC -- Superconductor object, from SC module, default: Al
    plot -- boolean to plot the fit over temperature.
    reterr -- boolean to return fitting error.
    method -- either df or Qi, which is fitted linearly over temperature.
    
    Returns:
    ak 
    optionally: the error in ak from fitting."""

    if SC is None:
        SC = SuperCond.Al(Tc=S21data[0, 21])

    # Extract relevant data
    hw = S21data[:, 5] * const.Planck / const.e * 1e6  # µeV
    kbT = S21data[:, 1] * const.Boltzmann / const.e * 1e6  # µeV
    hw0 = hw[0]

    # define y to fit:
    if method == "df":
        y = (hw - hw0) / hw0
    elif method == "Qi":
        y = 1 / S21data[:, 4] - 1 / S21data[0, 4]

    # Mask the double measured temperatures, and only fit from 250 mK
    mask1 = np.zeros(len(y), dtype="bool")
    mask1[np.unique(np.round(S21data[:, 1], decimals=2),
                    return_index=True)[1]] = True
    mask = np.logical_and(mask1,
                          (kbT >= Tmin * const.Boltzmann / const.e * 1e6))

    if mask.sum() > 3:
        y = y[mask]
    else:
        warnings.warn(
            "Not enough high temperature S21data, taking the last 10 points")
        y = y[mask1][-10:]

    # define x to fit:
    x = np.zeros(len(y))
    i = 0
    s0 = kidcalc.cinduct(hw0, kidcalc.D(kbT[0], SC), kbT[0])
    for kbTi in kbT[mask]:
        D_0 = kidcalc.D(kbTi, SC)
        s = kidcalc.cinduct(hw[i], D_0, kbTi)
        if method == "df":
            x[i] = (s[1] - s0[1]) / s0[1] * kidcalc.beta(
                kbTi, D_0, SuperCond.Sheet(SC, d=S21data[0, 25])) / 4
        elif method == "Qi":
            x[i] = (s[0] - s0[0]) / s0[1] * kidcalc.beta(
                kbTi, D_0, SuperCond.Sheet(SC, d=S21data[0, 25])) / 2
        i += 1

    # do the fit:
    fit = curve_fit(lambda t, ak: ak * t, x, y)
    if plot:
        plt.figure()
        plt.plot(x, y, "o")
        plt.plot(x, fit[0] * x)
        plt.legend(["Data", "Fit"])
        if method == "df":
            plt.ylabel(r"$\delta f/f_0$")
            plt.xlabel(r"$\beta \delta \sigma_2/4\sigma_2 $")
        elif method == "Qi":
            plt.ylabel(r"$\delta(1/Q_i)$")
            plt.xlabel(r"$\beta \delta \sigma_1/2\sigma_2 $")

    if reterr:
        return fit[0][0], np.sqrt(fit[1][0])
    else:
        return fit[0][0]
Exemplo n.º 22
0
                        T[i] = math.atan2(py[y,x],px[y,x])+pi/2;    
                    return points,asmatrix(T)
        r += 1
    T = zeros((simpleto,1)) 
    for i,(x,y) in enumerate(points):
        T[i] = math.atan2(py[y,x],px[y,x])+pi/2;    
        
    return points,asmatrix(T)





if __name__ == '__main__':

    sco = SC()
    sampls = 10

    points1,t1 = get_points_from_img('000026.jpg',simpleto=sampls)
    #points2,t2 = get_points_from_img('A.png',simpleto=sampls)
    #points3,t3 = get_points_from_img('D.png',simpleto=sampls)
    P1 = sco.compute(points1)
    #P2 = sco.compute(points2)
    #P3 = sco.compute(points3)

    #print P1


    figure(1)
    subplot(1,3,1); imshow(P1)
    #subplot(1,3,2); imshow(P2)
Exemplo n.º 23
0
def Nqp(
    Chipnum,
    KIDnum,
    pltPread="all",
    spec="cross",
    startstopf=(None, None),
    delampNoise=False,
    del1fNoise=False,
    del1fnNoise=False,
    Tminmax=None,
    relerrthrs=0.3,
    pltThrm=True,
    pltNqpQi=False,
    splitT=0,
    pltNqptau=False,
    SCvol=None,
    SCkwargs={},
    nqpaxis=True,
    fig=None,
    ax=None,
    label=None,
    color=None,
    fmt="-o",
):
    """Plots the number of quasiparticle calculated from the noise levels and lifetimes from PSDs.
    options similar to options in ltnlvl.
    
    pltThrm -- also plot thermal line (needs constants)
    pltNqpQi -- plot Nqp from Qi as well (needs constants)
    splitT -- makes NqpQi line dashed below this T
    pltNqptau -- plot Nqp from lifetime only (need constants)
    nqpaxis -- also shows density on right axis."""

    TDparam = io.get_grTDparam(Chipnum)
    if ax is None:
        fig, ax = plt.subplots()

    Preadar = _selectPread(pltPread, io.get_grPread(TDparam, KIDnum))

    if Preadar.size > 1:
        cmap = matplotlib.cm.get_cmap("plasma")
        norm = matplotlib.colors.Normalize(-1.05 * Preadar.max(),
                                           -0.95 * Preadar.min())
        clb = fig.colorbar(matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap),
                           ax=ax)
        clb.ax.set_title(r"$P_{read}$ (dBm)")
    if SCvol is None:
        SCvol = SuperCond.init_SCvol(Chipnum,
                                     KIDnum,
                                     set_tesc=pltNqptau,
                                     **SCkwargs)

    for Pread in Preadar:
        S21data = io.get_S21data(Chipnum, KIDnum, Pread)

        Respspl = calc.Respspl(Chipnum, KIDnum, Pread, var=spec)

        Temp = io.get_grTemp(TDparam, KIDnum, Pread)
        if Tminmax is not None:
            if Tminmax[0] is not None:
                Temp = Temp[Temp > Tminmax[0]]
            if Tminmax[1] is not None:
                Temp = Temp[Temp < Tminmax[1]]
        Nqp, Nqperr, taut = np.zeros((3, len(Temp)))
        for i in range(len(Temp)):
            freq, SPR = io.get_grdata(TDparam,
                                      KIDnum,
                                      Pread,
                                      Temp[i],
                                      spec=spec)
            if delampNoise:
                freq, SPR = filters.del_ampNoise(freq, SPR)
            if del1fNoise:
                freq, SPR = filters.del_1fNoise(freq, SPR)
            if del1fnNoise:
                freq, SPR = filters.del_1fnNoise(freq, SPR)
            taut[i], tauterr, lvl, lvlerr = calc.tau(freq,
                                                     SPR,
                                                     retfnl=True,
                                                     startf=startstopf[0],
                                                     stopf=startstopf[1])
            lvl = lvl / interpolate.splev(Temp[i] * 1e-3, Respspl)**2
            lvlerr = lvlerr / interpolate.splev(Temp[i] * 1e-3, Respspl)**2
            Nqp[i] = lvl / (4 * taut[i] * 1e-6)
            Nqperr[i] = np.sqrt((lvlerr / (4 * taut[i] * 1e-6))**2 +
                                (-lvl * tauterr * 1e-6 /
                                 (4 * (taut[i] * 1e-6)**2))**2)
        mask = ~np.isnan(Nqp)
        mask[mask] = Nqperr[mask] / Nqp[mask] <= relerrthrs
        if color is None:
            if Preadar.size > 1:
                color = cmap(norm(-1 * Pread))
            elif pltPread == "min":
                color = "purple"
            elif pltPread == "max":
                color = "gold"

        dataline = ax.errorbar(
            Temp[mask],
            Nqp[mask],
            yerr=Nqperr[mask],
            color=color,
            fmt=fmt,
            mec="k",
            capsize=2.0,
            label=label,
        )
        if pltNqptau:
            Nqp_ = SCvol.V * kidcalc.nqpfromtau(taut, SCvol)
            (tauline, ) = ax.plot(
                Temp[mask],
                Nqp_[mask],
                color=color,
                zorder=len(ax.lines) + 1,
                label="$\\tau_{qp}^*$",
            )
    if pltNqpQi:
        Preadar = io.get_S21Pread(Chipnum, KIDnum)
        for Pread in Preadar:
            S21data = io.get_S21data(Chipnum, KIDnum, Pread)
            T, Nqp = calc.NqpfromQi(S21data, SC=SCvol.SC)
            mask = np.logical_and(T * 1e3 > ax.get_xlim()[0],
                                  T * 1e3 < ax.get_xlim()[1])
            totalT = T[mask]
            totalNqp = Nqp[mask]
            if len(Preadar) == 1:
                color = "g"
            else:
                color = cmap(norm(closestPread))
            (Qline, ) = ax.plot(
                totalT[totalT > splitT] * 1e3,
                totalNqp[totalT > splitT],
                linestyle="-",
                color=color,
                zorder=len(ax.lines) + 1,
                label="$Q_i$",
            )
            ax.plot(
                totalT[totalT < splitT] * 1e3,
                totalNqp[totalT < splitT],
                linestyle="--",
                color=color,
                zorder=len(ax.lines) + 1,
            )
    if pltThrm:
        T = np.linspace(*ax.get_xlim(), 100)
        NqpT = np.zeros(100)
        for i in range(len(T)):
            D_ = kidcalc.D(const.Boltzmann / const.e * 1e6 * T[i] * 1e-3,
                           SCvol.SC)
            NqpT[i] = SCvol.V * kidcalc.nqp(
                const.Boltzmann / const.e * 1e6 * T[i] * 1e-3, D_, SCvol.SC)
        (Thline, ) = ax.plot(T,
                             NqpT,
                             color="k",
                             zorder=len(ax.lines) + 1,
                             label="Thermal $N_{qp}$")

    handles, labels = ax.get_legend_handles_labels()
    by_label = dict(zip(labels, handles))
    ax.legend(by_label.values(), by_label.keys())

    ax.set_ylabel("$N_{qp}$")
    ax.set_xlabel("Temperature (mK)")

    ax.set_yscale("log")

    if nqpaxis:

        def nqptoNqp(x):
            return x * SCvol.V

        def Nqptonqp(x):
            return x / SCvol.V

        ax2 = ax.secondary_yaxis("right", functions=(Nqptonqp, nqptoNqp))
        ax2.set_ylabel("$n_{qp}$ ($\\mu m^{-3}$)")
    if Preadar.size > 1:
        l, b, w, h = clb.ax.get_position().bounds
        clb.ax.set_position([l + 0.12, b, w, h])
Exemplo n.º 24
0
def spec(
        Chipnum,
        KIDlist=None,
        pltPread="all",
        spec="all",
        lvlcomp="",
        SCvol=None,
        SCkwargs={},
        clbar=True,
        cmap=None,
        norm=None,
        del1fNoise=False,
        delampNoise=False,
        del1fnNoise=False,
        suboffres=False,
        plttres=False,
        Tminmax=(0, 500),
        ax12=None,
        xlim=(None, None),
        ylim=(None, None),
):
    """Plots PSDs of multiple KIDs, read powers and temperatures (indicated by color). Every KID has a new figure, which is returned if only one KID is plotted.
    lvlcomp specifies how the noise levels should be compensated (will be a different function in the future). 
    Use Resp to divide by responsivity and obtain quasiparticle fluctuations.
    Use Resptres to compensate for the factor (1+(omega*taures)^2) and get the quasiparticle fluctuations.
    plttres will plot arrow at the frequencies corresponding to the resonator ring time."""
    TDparam = io.get_grTDparam(Chipnum)
    if suboffres:
        TDparamoffres = io.get_grTDparam(Chipnum, offres=True)

    if KIDlist is None:
        KIDlist = io.get_grKIDs(TDparam)
    elif type(KIDlist) is int:
        KIDlist = [KIDlist]

    if spec == "all":
        specs = ["cross", "amp", "phase"]
    elif type(spec) == list:
        specs = spec
    else:
        raise ValueError("Invalid Spectrum Selection")

    for KIDnum in KIDlist:
        if lvlcomp != "":
            if SCvol is None:
                SCvol = SuperCond.init_SCvol(Chipnum, KIDnum, **SCkwargs)
        else:
            SCvol = SuperCond.Vol(SuperCond.Al(), np.nan, np.nan)

        Preadar = _selectPread(pltPread, io.get_grPread(TDparam, KIDnum))
        if ax12 is None:
            fig, axs = plt.subplots(
                len(Preadar),
                len(specs),
                figsize=(4 * len(specs), 4 * len(Preadar)),
                sharex=True,
                sharey=True,
                squeeze=False,
            )
            fig.suptitle(f"{Chipnum}, KID{KIDnum}")
        else:
            axs = ax12

        for ax1, Pread in zip(range(len(Preadar)), Preadar):

            axs[ax1, 0].set_ylabel("PSD (dBc/Hz)")
            Temp = io.get_grTemp(TDparam, KIDnum, Pread)
            if suboffres:
                Temp = np.intersect1d(
                    Temp, io.get_grTemp(TDparamoffres, KIDnum, Pread))

            Temp = Temp[np.logical_and(Temp < Tminmax[1], Temp > Tminmax[0])]
            if cmap is None or norm is None:
                cmap = matplotlib.cm.get_cmap("viridis")
                norm = matplotlib.colors.Normalize(Temp.min(), Temp.max())
            if clbar:
                clb = plt.colorbar(matplotlib.cm.ScalarMappable(norm=norm,
                                                                cmap=cmap),
                                   ax=axs[ax1, -1])
                clb.ax.set_title("T (mK)")
            if plttres:
                S21data = io.get_S21data(Chipnum, KIDnum, Pread)

            for i in range(len(Temp)):
                for (ax2, spec) in zip(range(len(specs)), specs):
                    lvlcompspl = calc.NLcomp(Chipnum,
                                             KIDnum,
                                             Pread,
                                             SCvol=SCvol,
                                             method=lvlcomp,
                                             var=spec)
                    freq, SPR = io.get_grdata(TDparam,
                                              KIDnum,
                                              Pread,
                                              Temp[i],
                                              spec=spec)
                    if suboffres:
                        orfreq, orSPR = io.get_grdata(TDparamoffres,
                                                      KIDnum,
                                                      Pread,
                                                      Temp[i],
                                                      spec=spec)
                        freq, SPR = filters.subtr_spec(freq, SPR, orfreq,
                                                       orSPR)

                    if delampNoise:
                        freq, SPR = filters.del_ampNoise(freq, SPR)
                    if del1fNoise:
                        freq, SPR = filters.del_1fNoise(freq, SPR)
                    if del1fnNoise:
                        freq, SPR = filters.del_1fnNoise(freq, SPR)

                    SPR[SPR == -140] = np.nan
                    SPR[SPR == -np.inf] = np.nan

                    SPR = 10 * np.log10(10**(SPR / 10) / interpolate.splev(
                        Temp[i] * 1e-3, lvlcompspl))

                    axs[ax1, ax2].plot(freq, SPR, color=cmap(norm(Temp[i])))
                    axs[ax1, ax2].set_xscale("log")
                    axs[ax1, ax2].set_title(spec + ", -{} dBm".format(Pread))
                    axs[-1, ax2].set_xlabel("Freq. (Hz)")

                    if plttres:
                        Tind = np.abs(S21data[:, 1] - Temp[i] * 1e-3).argmin()
                        fres = S21data[Tind, 5] / (2 * S21data[Tind, 2])
                        axs[ax1,
                            ax2].annotate("", (fres, 1), (fres, 1.25),
                                          arrowprops=dict(arrowstyle="simple",
                                                          color=cmap(
                                                              norm(Temp[i])),
                                                          ec="k"),
                                          annotation_clip=False,
                                          xycoords=('data', 'axes fraction'))
        axs[0, 0].set_xlim(*xlim)
        axs[0, 0].set_ylim(*ylim)
    #         plt.tight_layout()
    if ax12 is None and len(KIDlist) == 1:
        return fig, axs
Exemplo n.º 25
0
def ltnlvl(
    Chipnum,
    KIDlist=None,
    pltPread="all",
    spec="cross",
    Tminmax=None,
    startstopf=(None, None),
    lvlcomp="",
    pltTTc=False,
    delampNoise=False,
    del1fNoise=False,
    del1fnNoise=False,
    suboffres=False,
    relerrthrs=0.1,
    pltKIDsep=True,
    pltthlvl=False,
    pltkaplan=False,
    pltthmlvl=False,
    plttres=False,
    plttscat=False,
    fig=None,
    ax12=None,
    color="Pread",
    pltclrbar=True,
    fmt="-o",
    label=None,
    SCvol=None,
    SCkwargs={},
    showfit=False,
    savefig=False,
):
    """Plots the results from a Lorentzian fit to the PSDs of multiple KIDs, read powers and temperatures. 
    Two axes: 0: lifetimes 1: noise levels, both with temperature on the x-axis. The color can be specified and
    is Pread by default. 
    Options:
    startstopf -- defines the fitting window
    lvlcomp -- defines how the levels are compensated. Use Resp for responsivity compensation.
        (will be moved in the future)
    del{}Noise -- filter spectrum before fitting.
    relerrthrs -- only plot fits with a relative error threshold in lifetime less than this.
    pltKIDsep -- if True, different KIDs get a new figure.
    pltthlvl -- expected noise level is plotted as dashed line
    pltkaplan -- a kaplan fit (tesc as parameter) is plotted in the lifetime axis.
    pltthmfnl -- a noise level from the fitted lifetime and theoretical Nqp is plotted as well
    plttres -- the resonator ring time is plotted in the lifetime axis.
    ... multiple figure handling options ...
    ... options for the tesc deteremination ...
    showfit -- the fits are displayed in numerous new figures, for manual checking."""
    def _make_fig():
        fig, axs = plt.subplots(1, 2, figsize=(8, 3))
        return fig, axs

    def _get_cmap(**kwargs):
        if color == "Pread":
            cmap = matplotlib.cm.get_cmap("plasma")
            norm = matplotlib.colors.Normalize(-1.05 * kwargs["Preadar"].max(),
                                               -0.95 * kwargs["Preadar"].min())
            if pltclrbar:
                clb = fig.colorbar(
                    matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap))
                clb.ax.set_title(r"$P_{read}$ (dBm)")
        elif color == "Pint":
            cmap = matplotlib.cm.get_cmap("plasma")
            norm = matplotlib.colors.Normalize(kwargs["Pintar"].min() * 1.05,
                                               kwargs["Pintar"].max() * 0.95)
            if pltclrbar:
                clb = fig.colorbar(
                    matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap))
                clb.ax.set_title(r"$P_{int}$ (dBm)")
        elif color == "V":
            cmap = matplotlib.cm.get_cmap("cividis")
            norm = matplotlib.colors.Normalize(
                np.array(list(Vdict.values())).min(),
                np.array(list(Vdict.values())).max(),
            )
            if pltclrbar:
                clb = fig.colorbar(
                    matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap))
                clb.ax.set_title(r"Al Vol. ($\mu m^3$)")
        elif color == "KIDnum":
            cmap = matplotlib.cm.get_cmap("Paired")
            norm = matplotlib.colors.Normalize(
                np.array(KIDlist).min(),
                np.array(KIDlist).max())
            if pltclrbar:
                clb = fig.colorbar(
                    matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap))
                clb.ax.set_title("KID nr.")
        else:
            raise ValueError(
                "{} is not a valid variable as color".format(color))
        return cmap, norm

    TDparam = io.get_grTDparam(Chipnum)
    if suboffres:
        TDparamoffres = io.get_grTDparam(Chipnum, offres=True)

    if KIDlist is None:
        KIDlist = io.get_grKIDs(TDparam)
    elif type(KIDlist) is int:
        KIDlist = [KIDlist]

    if color == "Pint":
        Pintdict = io.get_Pintdict(Chipnum)

    if not pltKIDsep:
        if ax12 is None:
            fig, axs = _make_fig()
        else:
            axs = ax12
        if color == "Pint":
            Pintar = np.array([Pintdict[k] for k in KIDlist])
            cmap, norm = _get_cmap(Pintar=Pintar)
        elif color == "V":
            Vdict = io.get_Vdict(Chipnum)
            cmap, norm = _get_cmap(Vdict=Vdict)
        elif color == "Pread":
            Preaddict = io.get_Preaddict(Chipnum)
            Preadar = np.array([Preaddict[k] for k in KIDlist])
            cmap, norm = _get_cmap(Preadar=Preadar)
        elif color == "KIDnum":
            cmap, norm = _get_cmap(KIDlist=KIDlist)

    for KIDnum in KIDlist:
        Preadar = _selectPread(pltPread, io.get_grPread(TDparam, KIDnum))
        if pltKIDsep:
            if ax12 is None:
                fig, axs = _make_fig()
            else:
                axs = ax12

            if len(KIDlist) > 1:
                fig.suptitle(f"KID{KIDnum}")

            if color == "Pread":
                cmap, norm = _get_cmap(Preadar=Preadar)
            elif color == "Pint":
                cmap, norm = _get_cmap(Pintar=np.array(Pintdict[KIDnum]))

        if lvlcomp != "" or pltkaplan or pltthmlvl or pltthlvl or pltTTc:
            if SCvol is None:
                SCvol = SuperCond.init_SCvol(Chipnum, KIDnum, **SCkwargs)
        else:
            SCvol = SuperCond.Vol(SuperCond.Al(), np.nan, np.nan)

        for Pread in Preadar:
            Temp = np.trim_zeros(io.get_grTemp(TDparam, KIDnum, Pread))
            lvlcompspl = calc.NLcomp(Chipnum,
                                     KIDnum,
                                     Pread,
                                     SCvol=SCvol,
                                     method=lvlcomp,
                                     var=spec)

            if suboffres:
                Temp = np.intersect1d(
                    Temp, io.get_grTemp(TDparamoffres, KIDnum, Pread))

            if Tminmax is not None:
                if Tminmax[0] is not None:
                    Temp = Temp[Temp > Tminmax[0]]
                if Tminmax[1] is not None:
                    Temp = Temp[Temp < Tminmax[1]]
            taut = np.zeros((len(Temp)))
            tauterr = np.zeros((len(Temp)))
            lvl = np.zeros((len(Temp)))
            lvlerr = np.zeros((len(Temp)))
            for i in range(len(Temp)):
                freq, SPR = io.get_grdata(TDparam, KIDnum, Pread, Temp[i],
                                          spec)
                if suboffres:
                    orfreq, orSPR = io.get_grdata(TDparamoffres, KIDnum, Pread,
                                                  Temp[i], spec)
                    freq, SPR = filters.subtr_spec(freq, SPR, orfreq, orSPR)
                if delampNoise:
                    freq, SPR = filters.del_ampNoise(freq, SPR)
                if del1fNoise:
                    freq, SPR = filters.del_1fNoise(freq, SPR)
                if del1fnNoise:
                    freq, SPR = filters.del_1fnNoise(freq, SPR)

                if showfit:
                    print("{}, KID{}, -{} dBm, T={}, {}".format(
                        Chipnum, KIDnum, Pread, Temp[i], spec))
                taut[i], tauterr[i], lvl[i], lvlerr[i] = calc.tau(
                    freq,
                    SPR,
                    plot=showfit,
                    retfnl=True,
                    startf=startstopf[0],
                    stopf=startstopf[1],
                )
                if showfit:
                    print(tauterr[i] / taut[i])

                lvl[i] = lvl[i] / interpolate.splev(Temp[i] * 1e-3, lvlcompspl)
                lvlerr[i] = lvlerr[i] / interpolate.splev(
                    Temp[i] * 1e-3, lvlcompspl)

            # Deleting bad fits and plotting:
            mask = ~np.isnan(taut)
            mask[mask] = tauterr[mask] / taut[mask] <= relerrthrs

            if color == "Pread":
                clr = cmap(norm(-1 * Pread))
            elif color == "Pint":
                clr = cmap(norm(Pint))
            elif color == "V":
                clr = cmap(norm(Vdict[KIDnum]))
            elif color == "KIDnum":
                clr = cmap(norm(KIDnum))
            else:
                clr = color

            if pltTTc:
                Temp = Temp / (SCvol.SC.kbTc /
                               (const.Boltzmann / const.e * 1e6) * 1e3)

            axs[0].errorbar(
                Temp[mask],
                taut[mask],
                yerr=tauterr[mask],
                fmt=fmt,
                capsize=3.0,
                color=clr,
                mec="k",
                label=label if Pread == Preadar[-1] else "",
            )
            axs[1].errorbar(
                Temp[mask],
                10 * np.log10(lvl[mask]),
                yerr=10 * np.log10((lvlerr[mask] + lvl[mask]) / lvl[mask]),
                fmt=fmt,
                capsize=3.0,
                color=clr,
                mec="k",
                label=label if Pread == Preadar[-1] else "",
            )
            if pltthlvl:
                if Tminmax is not None and not pltTTc:
                    Tstartstop = Tminmax
                else:
                    Tstartstop = (Temp[mask].min(), Temp[mask].max())
                Ttemp = np.linspace(*Tstartstop, 100)
                if pltTTc:
                    Ttemp = Ttemp * (SCvol.SC.kbTc /
                                     (const.Boltzmann / const.e * 1e6) * 1e3)
                explvl = (interpolate.splev(
                    Ttemp * 1e-3, calc.Respspl(Chipnum,
                                               KIDnum,
                                               Pread,
                                               var=spec))**2)
                explvl *= (4 * SCvol.SC.t0 * 1e-6 * SCvol.V * SCvol.SC.N0 *
                           (SCvol.SC.kbTc)**3 / (2 * (SCvol.SC.D0)**2) *
                           (1 + SCvol.tesc / SCvol.SC.tpb) / 2)
                explvl /= interpolate.splev(Ttemp * 1e-3, lvlcompspl)
                if pltTTc:
                    Ttemp = Ttemp / (SCvol.SC.kbTc /
                                     (const.Boltzmann / const.e * 1e6) * 1e3)
                (thlvlplot, ) = axs[1].plot(
                    Ttemp,
                    10 * np.log10(explvl),
                    color=clr,
                    linestyle="--",
                    linewidth=2.0,
                )
                axs[1].legend((thlvlplot, ), (r"Expected noise level", ))

            if pltkaplan and Temp[mask].size != 0:
                if Tminmax is not None and not pltTTc:
                    Tstartstop = Tminmax
                else:
                    Tstartstop = (Temp[mask].min(), Temp[mask].max())
                T = np.linspace(*Tstartstop, 100)

                if pltTTc:
                    T = T * (SCvol.SC.kbTc / (const.Boltzmann / const.e * 1e6))
                else:
                    T = T * 1e-3
                taukaplan = kidcalc.tau_kaplan(T, SCvol)
                if pltTTc:
                    T = T / (SCvol.SC.kbTc / (const.Boltzmann / const.e * 1e6))
                else:
                    T = T * 1e3

                axs[0].plot(
                    T,
                    taukaplan,
                    color=clr,
                    linestyle="--",
                    linewidth=2.0,
                    label="Kaplan, $\\tau_{qp}$",
                )

            if plttscat:
                if Tminmax is not None:
                    Tstartstop = Tminmax
                else:
                    Tstartstop = (Temp[mask].min(), Temp[mask].max())
                T = np.linspace(*Tstartstop, 100)

                if pltTTc:
                    T = T * (SCvol.SC.kbTc / (const.Boltzmann / const.e * 1e6))
                else:
                    T = T * 1e-3
                tscat = SCvol.SC.t0 / (
                    2.277 * (SCvol.SC.kbTc / (2 * SCvol.SC.D0))**0.5 *
                    (T / (SCvol.SC.kbTc /
                          (const.Boltzmann / const.e * 1e6)))**(7 / 2))
                if pltTTc:
                    T = T / (SCvol.SC.kbTc / (const.Boltzmann / const.e * 1e6))
                else:
                    T = T * 1e3
                axs[0].plot(
                    T,
                    tscat,
                    color=clr,
                    linestyle="-.",
                    linewidth=2.0,
                    label="Kaplan, $\\tau_s$",
                )

            if pltthmlvl:
                try:
                    if pltTTc:
                        Temp = Temp * (SCvol.SC.kbTc /
                                       (const.Boltzmann / const.e * 1e6) * 1e3)
                    tauspl = interpolate.splrep(Temp[mask], taut[mask], s=0)
                    T = np.linspace(Temp[mask].min(), Temp[mask].max(), 100)
                    Nqp = np.zeros(len(T))
                    for i in range(len(T)):
                        Nqp[i] = SCvol.V * kidcalc.nqp(
                            T[i] * 1e-3 * const.Boltzmann / const.e * 1e6,
                            SCvol.D0,
                            SCvol.SC,
                        )
                    thmfnl = (
                        4 * interpolate.splev(T, tauspl) * 1e-6 * Nqp *
                        interpolate.splev(
                            T * 1e-3,
                            calc.Respspl(Chipnum, KIDnum, Pread, var=spec))**2)
                    thmfnl /= interpolate.splev(T * 1e-3, lvlcompspl)
                    if pltTTc:
                        T = T / (SCvol.SC.kbTc /
                                 (const.Boltzmann / const.e * 1e6) * 1e3)
                    (thmfnlplot, ) = axs[1].plot(
                        T,
                        10 * np.log10(thmfnl),
                        color=clr,
                        linestyle="--",
                        linewidth=3.0,
                    )
                    axs[1].legend(
                        (thmfnlplot, ),
                        ("Thermal Noise Level \n with measured $\\tau_{qp}^*$",
                         ),
                    )
                except:
                    warnings.warn(
                        "Could not make Thermal Noise Level, {},KID{},-{} dBm,{}"
                        .format(Chipnum, KIDnum, Pread, spec))
            if plttres:
                S21data = io.get_S21data(Chipnum, KIDnum, Pread)
                (tresline, ) = axs[0].plot(
                    S21data[:, 1] /
                    S21data[0, 21] if pltTTc else S21data[:, 1] * 1e3,
                    S21data[:, 2] / (np.pi * S21data[:, 5]) * 1e6,
                    color=clr,
                    linestyle=":",
                )
                axs[0].legend((tresline, ), ("$\\tau_{res}$", ))
        axs[0].set_yscale("log")
        for i in range(2):
            if pltTTc:
                axs[i].set_xlabel("$T/T_c$")
            else:
                axs[i].set_xlabel("Temperature (mK)")
        axs[0].set_ylabel(r"$\tau_{qp}^*$ (µs)")

        if lvlcomp == "Resp":
            axs[1].set_ylabel(r"Noise Level/$\mathcal{R}^2(T)$ (dB/Hz)")
        elif lvlcomp == "RespV":
            axs[1].set_ylabel(r"Noise Level/$(\mathcal{R}^2(T)V)$ (dB/Hz)")
        elif lvlcomp == "RespVtescTc":
            axs[1].set_ylabel(r"Noise Level/$(\mathcal{R}^2(T)\chi)$ (dB/Hz)")
        elif lvlcomp == "":
            axs[1].set_ylabel(r"Noise Level (dB/Hz)")
        elif lvlcomp == "RespLowT":
            axs[1].set_ylabel(r"Noise Level/$\mathcal{R}^2(T=50 mK)$ (dB/Hz)")
        else:
            axs[1].set_ylabel(r"comp. Noise Level (dB/Hz)")
        plt.tight_layout()
        if savefig:
            plt.savefig("GR_{}_KID{}_{}.pdf".format(Chipnum, KIDnum, spec))
            plt.close()
    if ax12 is None:
        return fig, axs
Exemplo n.º 26
0
 def Qi_0(self):
     hwread = self.hwread
     s_0 = kidcalc.cinduct(hwread, self.D_0, self.kbT)
     return kidcalc.Qi(s_0[0], s_0[1], self.ak, self.kbT, self.D_0,
                      SC.Sheet(self.SC, self.d))