from pyinstruments.curvestore.curve_create_widget import CurveCreateWidget
from pyinstruments.pyhardwaredb import instrument
from pyinstruments.curvestore import models
from curve.fitting import Fit

from django.core.exceptions import ObjectDoesNotExist
from PyQt4 import QtCore, QtGui
import pylab
import json
from scipy.optimize import leastsq
from scipy.interpolate import interp1d
from scipy.interpolate import splrep, splev
import numpy as np
from pylab import subplot, plot
import pandas
from curve import fitting
import pyinstruments.curvestore.models as cs
import gc
from users.default import default

#constants
CONSTANTS_LEO_PILLAR = dict(
            TEMs = 1.0,
            fit_only_TEM00 = True,
            peakportionsize = 60e-6,
            peakthreshold = 0.4,
            downsample_margin = 2000,
            downsample_threshold = 0.2,
            maxiter = 100,
            pzt_freq = 20,
            sb_freq = 200e6,
            ISL_guess = 2e11,
            secondharmonicISL_guess = 2e10,
            ISL_guess_phase = 0.0,
            secondharmonicISL_guess_phase = 0.0,
#            length_guess = 50e-6,
            c = 2.99e8,
            curve3name="",
            curve4name="",
            downsamplefactor = 10,
            scopename = 'Prof',
            analyzefile = "users.cryo.Q",
            scheduledanalyzefunction = "save_summary",
            #fit_type = "rebonds_reflexion_sb_asymm",
            #fit_type = "lorentzSB",
            fit_type = "lorentzSB_rebonds_asymm",
            fit_manualguess = dict(),
            )

CONSTANTS = CONSTANTS_LEO_PILLAR
#CONSTANTS = CONSTANTS_SALIM_PILLAR
#CONSTANTS = CONSTANTS_LEO_PILLAR_TEMs


        
class Qscan(object):
    """
    Extract the finesse, and length of a cavity from an FSR scan
    """
    
    def __init__(self, curve_id, constants=None):
        if constants is None:
            self.constants = CONSTANTS
        else:
            self.constants = constants
        self.curve = models.CurveDB.objects.get(id=curve_id)

    def makecurve(self, x, y, name):
        c_x = cs.CurveDB.create(x,y,name=name)
        self.curve.add_child(c_x)
        c_x.params["analyze"] = self.constants["analyzefile"]
        c_x.save()
   
def analyze_Q_vs_frequency(id):
    scan = Qscan(id)
    curve = models.CurveDB.objects.get(id=id)
    childs = curve.childs.filter_param("analyze",value__contains = scan.constants["analyzefile"])
    
    fs = list()
    Qs = list()
    slopes = list()
    overshoots = list()
    gammas = list()
    highs = list()
    lows = list()
    for c,i in zip(childs,range(len(childs))):
        fs.append(c.params["center_freq"])
        fit = c.childs.latest()
        Qs.append(fit.params["Q"])
        slopes.append(fit.params["slope"])
        overshoots.append(fit.params["overshoot"])
        gammas.append(fit.params["gamma"])
        highs.append(fit.params["high"])
        lows.append(fit.params["low"])
#        s.append(fit.params[""])
    scan.makecurve(fs, Qs, "Q vs frequency")
    scan.makecurve(fs, slopes, "slope vs frequency")
    scan.makecurve(fs, overshoots, "overshoot vs frequency")
    scan.makecurve(fs, gammas, "gamma vs frequency")
    scan.makecurve(fs, highs, "high vs frequency")
    scan.makecurve(fs, lows, "low vs frequency")
    
def analyze_clear_all_childs(id):
    scan = Qscan(id)
    curve = models.CurveDB.objects.get(id=id)
    childs = curve.childs.filter_param("analyze",value__contains = scan.constants["analyzefile"])
    i=1
    for c in childs:
        for cc in c.childs.all():
            cc.delete()
            
bc3b9bfc9d80129f5293a2575e20aa5be7d20cb5
<mask token>


class Qscan(object):
    """
    Extract the finesse, and length of a cavity from an FSR scan
    """

    def __init__(self, curve_id, constants=None):
        if constants is None:
            self.constants = CONSTANTS
        else:
            self.constants = constants
        self.curve = models.CurveDB.objects.get(id=curve_id)

    def makecurve(self, x, y, name):
        c_x = cs.CurveDB.create(x, y, name=name)
        self.curve.add_child(c_x)
        c_x.params['analyze'] = self.constants['analyzefile']
        c_x.save()


<mask token>

<mask token>


class Qscan(object):
    """
    Extract the finesse, and length of a cavity from an FSR scan
    """

    def __init__(self, curve_id, constants=None):
        if constants is None:
            self.constants = CONSTANTS
        else:
            self.constants = constants
        self.curve = models.CurveDB.objects.get(id=curve_id)

    def makecurve(self, x, y, name):
        c_x = cs.CurveDB.create(x, y, name=name)
        self.curve.add_child(c_x)
        c_x.params['analyze'] = self.constants['analyzefile']
        c_x.save()


def analyze_Q_vs_frequency(id):
    scan = Qscan(id)
    curve = models.CurveDB.objects.get(id=id)
    childs = curve.childs.filter_param('analyze', value__contains=scan.
        constants['analyzefile'])
    fs = list()
    Qs = list()
    slopes = list()
    overshoots = list()
    gammas = list()
    highs = list()
    lows = list()
    for c, i in zip(childs, range(len(childs))):
        fs.append(c.params['center_freq'])
        fit = c.childs.latest()
        Qs.append(fit.params['Q'])
        slopes.append(fit.params['slope'])
        overshoots.append(fit.params['overshoot'])
        gammas.append(fit.params['gamma'])
        highs.append(fit.params['high'])
        lows.append(fit.params['low'])
    scan.makecurve(fs, Qs, 'Q vs frequency')
    scan.makecurve(fs, slopes, 'slope vs frequency')
    scan.makecurve(fs, overshoots, 'overshoot vs frequency')
    scan.makecurve(fs, gammas, 'gamma vs frequency')
    scan.makecurve(fs, highs, 'high vs frequency')
    scan.makecurve(fs, lows, 'low vs frequency')


def analyze_clear_all_childs(id):
    scan = Qscan(id)
    curve = models.CurveDB.objects.get(id=id)
    childs = curve.childs.filter_param('analyze', value__contains=scan.
        constants['analyzefile'])
    i = 1
    for c in childs:
        for cc in c.childs.all():
            cc.delete()

<mask token>
CONSTANTS_LEO_PILLAR = dict(TEMs=1.0, fit_only_TEM00=True, peakportionsize=
    6e-05, peakthreshold=0.4, downsample_margin=2000, downsample_threshold=
    0.2, maxiter=100, pzt_freq=20, sb_freq=200000000.0, ISL_guess=
    200000000000.0, secondharmonicISL_guess=20000000000.0, ISL_guess_phase=
    0.0, secondharmonicISL_guess_phase=0.0, c=299000000.0, curve3name='',
    curve4name='', downsamplefactor=10, scopename='Prof', analyzefile=
    'users.cryo.Q', scheduledanalyzefunction='save_summary', fit_type=
    'lorentzSB_rebonds_asymm', fit_manualguess=dict())
CONSTANTS = CONSTANTS_LEO_PILLAR


class Qscan(object):
    """
    Extract the finesse, and length of a cavity from an FSR scan
    """

    def __init__(self, curve_id, constants=None):
        if constants is None:
            self.constants = CONSTANTS
        else:
            self.constants = constants
        self.curve = models.CurveDB.objects.get(id=curve_id)

    def makecurve(self, x, y, name):
        c_x = cs.CurveDB.create(x, y, name=name)
        self.curve.add_child(c_x)
        c_x.params['analyze'] = self.constants['analyzefile']
        c_x.save()


def analyze_Q_vs_frequency(id):
    scan = Qscan(id)
    curve = models.CurveDB.objects.get(id=id)
    childs = curve.childs.filter_param('analyze', value__contains=scan.
        constants['analyzefile'])
    fs = list()
    Qs = list()
    slopes = list()
    overshoots = list()
    gammas = list()
    highs = list()
    lows = list()
    for c, i in zip(childs, range(len(childs))):
        fs.append(c.params['center_freq'])
        fit = c.childs.latest()
        Qs.append(fit.params['Q'])
        slopes.append(fit.params['slope'])
        overshoots.append(fit.params['overshoot'])
        gammas.append(fit.params['gamma'])
        highs.append(fit.params['high'])
        lows.append(fit.params['low'])
    scan.makecurve(fs, Qs, 'Q vs frequency')
    scan.makecurve(fs, slopes, 'slope vs frequency')
    scan.makecurve(fs, overshoots, 'overshoot vs frequency')
    scan.makecurve(fs, gammas, 'gamma vs frequency')
    scan.makecurve(fs, highs, 'high vs frequency')
    scan.makecurve(fs, lows, 'low vs frequency')


def analyze_clear_all_childs(id):
    scan = Qscan(id)
    curve = models.CurveDB.objects.get(id=id)
    childs = curve.childs.filter_param('analyze', value__contains=scan.
        constants['analyzefile'])
    i = 1
    for c in childs:
        for cc in c.childs.all():
            cc.delete()

from pyinstruments.curvestore.curve_create_widget import CurveCreateWidget
from pyinstruments.pyhardwaredb import instrument
from pyinstruments.curvestore import models
from curve.fitting import Fit
from django.core.exceptions import ObjectDoesNotExist
from PyQt4 import QtCore, QtGui
import pylab
import json
from scipy.optimize import leastsq
from scipy.interpolate import interp1d
from scipy.interpolate import splrep, splev
import numpy as np
from pylab import subplot, plot
import pandas
from curve import fitting
import pyinstruments.curvestore.models as cs
import gc
from users.default import default
CONSTANTS_LEO_PILLAR = dict(TEMs=1.0, fit_only_TEM00=True, peakportionsize=
    6e-05, peakthreshold=0.4, downsample_margin=2000, downsample_threshold=
    0.2, maxiter=100, pzt_freq=20, sb_freq=200000000.0, ISL_guess=
    200000000000.0, secondharmonicISL_guess=20000000000.0, ISL_guess_phase=
    0.0, secondharmonicISL_guess_phase=0.0, c=299000000.0, curve3name='',
    curve4name='', downsamplefactor=10, scopename='Prof', analyzefile=
    'users.cryo.Q', scheduledanalyzefunction='save_summary', fit_type=
    'lorentzSB_rebonds_asymm', fit_manualguess=dict())
CONSTANTS = CONSTANTS_LEO_PILLAR


class Qscan(object):
    """
    Extract the finesse, and length of a cavity from an FSR scan
    """

    def __init__(self, curve_id, constants=None):
        if constants is None:
            self.constants = CONSTANTS
        else:
            self.constants = constants
        self.curve = models.CurveDB.objects.get(id=curve_id)

    def makecurve(self, x, y, name):
        c_x = cs.CurveDB.create(x, y, name=name)
        self.curve.add_child(c_x)
        c_x.params['analyze'] = self.constants['analyzefile']
        c_x.save()


def analyze_Q_vs_frequency(id):
    scan = Qscan(id)
    curve = models.CurveDB.objects.get(id=id)
    childs = curve.childs.filter_param('analyze', value__contains=scan.
        constants['analyzefile'])
    fs = list()
    Qs = list()
    slopes = list()
    overshoots = list()
    gammas = list()
    highs = list()
    lows = list()
    for c, i in zip(childs, range(len(childs))):
        fs.append(c.params['center_freq'])
        fit = c.childs.latest()
        Qs.append(fit.params['Q'])
        slopes.append(fit.params['slope'])
        overshoots.append(fit.params['overshoot'])
        gammas.append(fit.params['gamma'])
        highs.append(fit.params['high'])
        lows.append(fit.params['low'])
    scan.makecurve(fs, Qs, 'Q vs frequency')
    scan.makecurve(fs, slopes, 'slope vs frequency')
    scan.makecurve(fs, overshoots, 'overshoot vs frequency')
    scan.makecurve(fs, gammas, 'gamma vs frequency')
    scan.makecurve(fs, highs, 'high vs frequency')
    scan.makecurve(fs, lows, 'low vs frequency')


def analyze_clear_all_childs(id):
    scan = Qscan(id)
    curve = models.CurveDB.objects.get(id=id)
    childs = curve.childs.filter_param('analyze', value__contains=scan.
        constants['analyzefile'])
    i = 1
    for c in childs:
        for cc in c.childs.all():
            cc.delete()

from pyinstruments.curvestore.curve_create_widget import CurveCreateWidget
from pyinstruments.pyhardwaredb import instrument
from pyinstruments.curvestore import models
from curve.fitting import Fit

from django.core.exceptions import ObjectDoesNotExist
from PyQt4 import QtCore, QtGui
import pylab
import json
from scipy.optimize import leastsq
from scipy.interpolate import interp1d
from scipy.interpolate import splrep, splev
import numpy as np
from pylab import subplot, plot
import pandas
from curve import fitting
import pyinstruments.curvestore.models as cs
import gc
from users.default import default

#constants
CONSTANTS_LEO_PILLAR = dict(
            TEMs = 1.0,
            fit_only_TEM00 = True,
            peakportionsize = 60e-6,
            peakthreshold = 0.4,
            downsample_margin = 2000,
            downsample_threshold = 0.2,
            maxiter = 100,
            pzt_freq = 20,
            sb_freq = 200e6,
            ISL_guess = 2e11,
            secondharmonicISL_guess = 2e10,
            ISL_guess_phase = 0.0,
            secondharmonicISL_guess_phase = 0.0,
#            length_guess = 50e-6,
            c = 2.99e8,
            curve3name="",
            curve4name="",
            downsamplefactor = 10,
            scopename = 'Prof',
            analyzefile = "users.cryo.Q",
            scheduledanalyzefunction = "save_summary",
            #fit_type = "rebonds_reflexion_sb_asymm",
            #fit_type = "lorentzSB",
            fit_type = "lorentzSB_rebonds_asymm",
            fit_manualguess = dict(),
            )

CONSTANTS = CONSTANTS_LEO_PILLAR
#CONSTANTS = CONSTANTS_SALIM_PILLAR
#CONSTANTS = CONSTANTS_LEO_PILLAR_TEMs


        
class Qscan(object):
    """
    Extract the finesse, and length of a cavity from an FSR scan
    """
    
    def __init__(self, curve_id, constants=None):
        if constants is None:
            self.constants = CONSTANTS
        else:
            self.constants = constants
        self.curve = models.CurveDB.objects.get(id=curve_id)

    def makecurve(self, x, y, name):
        c_x = cs.CurveDB.create(x,y,name=name)
        self.curve.add_child(c_x)
        c_x.params["analyze"] = self.constants["analyzefile"]
        c_x.save()
   
def analyze_Q_vs_frequency(id):
    scan = Qscan(id)
    curve = models.CurveDB.objects.get(id=id)
    childs = curve.childs.filter_param("analyze",value__contains = scan.constants["analyzefile"])
    
    fs = list()
    Qs = list()
    slopes = list()
    overshoots = list()
    gammas = list()
    highs = list()
    lows = list()
    for c,i in zip(childs,range(len(childs))):
        fs.append(c.params["center_freq"])
        fit = c.childs.latest()
        Qs.append(fit.params["Q"])
        slopes.append(fit.params["slope"])
        overshoots.append(fit.params["overshoot"])
        gammas.append(fit.params["gamma"])
        highs.append(fit.params["high"])
        lows.append(fit.params["low"])
#        s.append(fit.params[""])
    scan.makecurve(fs, Qs, "Q vs frequency")
    scan.makecurve(fs, slopes, "slope vs frequency")
    scan.makecurve(fs, overshoots, "overshoot vs frequency")
    scan.makecurve(fs, gammas, "gamma vs frequency")
    scan.makecurve(fs, highs, "high vs frequency")
    scan.makecurve(fs, lows, "low vs frequency")
    
def analyze_clear_all_childs(id):
    scan = Qscan(id)
    curve = models.CurveDB.objects.get(id=id)
    childs = curve.childs.filter_param("analyze",value__contains = scan.constants["analyzefile"])
    i=1
    for c in childs:
        for cc in c.childs.all():
            cc.delete()
            