def Hfloq(H0, dip, Eenv, phaseE, nmin, nmax):
    ntot = numn * nstates
    bigH = zeros((ntot, ntot), dtype='complex')
    for i, n in iterproduct(range(nstates), range(nmin, nmax + 1)):
        tmpindx = psinindex(i, n, nmin)
        bigH[tmpindx, tmpindx] = H0[i, i] + n * w0

    #dipole operators corresponding to lowering photon number
    for i, j, n in iterproduct(range(nstates), range(nstates),
                               range(nmin + 1, nmax + 1)):
        tmpindx0 = psinindex(i, n, nmin)
        tmpindx1 = psinindex(j, n - 1, nmin)
        bigH[tmpindx0, tmpindx1] = dip[i, j] * Eenv * exp(1j * phaseE)
        bigH[tmpindx1, tmpindx0] = bigH[tmpindx0, tmpindx1]
    #dipole operators corresponding to raising photon number
    for i, j, n in iterproduct(range(nstates), range(nstates),
                               range(nmin, nmax)):
        tmpindx0 = psinindex(i, n, nmin)
        tmpindx1 = psinindex(j, n + 1, nmin)
        bigH[tmpindx0, tmpindx1] = dip[i, j] * Eenv * exp(-1j * phaseE)
        bigH[tmpindx1, tmpindx0] = bigH[tmpindx0, tmpindx1]
    return bigH

    #dipole operators corresponding to lowering photon number
    for i, j, n in iterproduct(range(nstates), range(nstates),
                               range(nmin + 1, nmax + 1)):
        tmpindx0 = psinindex(i, n, nmin)
        tmpindx1 = psinindex(j, n - 1, nmin)
        bigH[tmpindx0, tmpindx1] = dip[i, j] * Eoft
    return bigH
def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in iterproduct(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.tight_layout()
def applyfloquetphase(inpfloqvec, floqphase=0):
    #floquet phase is phase proportional to number of photons
    retfloqvec = copy(inpfloqvec)
    for i, n in iterproduct(range(nstates), range(nmin, nmax + 1)):
        tmpindx = psinindex(i, n, nmin)
        retfloqvec[tmpindx] *= exp(1j * n * floqphase)
    return retfloqvec
示例#4
0
    def get_confidence_intervals(self, fileName=None, show=True, **optim_args):

        if not self.__fitted:
            raise ValueError("The model must be fitted before confidence " +
                             "intervals can be computed")

        x0 = self.__parameters_converted
        nLL, jac, hess = self.get_nLL_funtions()

        if not "fun0" in optim_args:
            self.prst("Determining logLikelihood")
            optim_args["fun0"] = -nLL(x0)
        if not "hess0" in optim_args:
            self.prst("Determining Hessian of logLikelihood")
            optim_args["hess0"] = -hess(x0)

        dim = len(x0)
        result = np.zeros((dim, 2))

        labels = np.array(self.VARIABLE_LABELS)

        indices, directions = zip(*iterproduct(range(dim), (-1, 1)))

        const_args = [
            self.observationData, self.pairRoutes, self.pairDayData,
            self.pairStationData, self.dayStationData, self.dayTimeFactors
        ]

        self.prst("Creating confidence intervals")
        #try: #, max_workers=13
        with ProcessPoolExecutor(const_args=const_args) as pool:
            mapObj = pool.map(RouteChoiceModel._find_profile_CI_static,
                              indices, repeat(x0), directions,
                              repeat(optim_args))

            for index, direction, r in zip(indices, directions, mapObj):
                result[index][(0 if direction == -1 else
                               1)] = self._convert_parameters(r.x)[index]

        self.prst("Printing confidence intervals:")
        self.increase_print_level()

        x0Orig = self._convert_parameters(x0)

        for index, intv in enumerate(result):
            start, end = intv
            strs = []
            for v in start, x0Orig[index], end:
                if (0.01 < np.abs(v) < 1e6) or v == 0:
                    strs.append("{:10.4f}".format(v))
                else:
                    strs.append("{:<10}".format(str(v)))
            self.prst("CI for {:<40}: [{} --- {} --- {}]".format(
                labels[index], *strs))

        self.decrease_print_level()


#print(RouteChoiceModel._convert_parameters([  4.54319707e+03,  -1.76750980e+01,  -2.64583166e+04]))
def groundstatedip(evecarray, t=0, wphase=False, sign=1):
    dipvec = zeros(ntot, dtype='complex')
    for i, n in iterproduct(range(nstates), range(nmin, nmax + 1)):
        tmpindx = psinindex(i, n, nmin)
        dipvec[tmpindx] = Hdip[0, i]
        if (wphase):
            dipvec[tmpindx] *= exp(1j * sign * w0 * n * t)
    return dot(evecarray, dipvec)
示例#6
0
    def _setup_data_points(self):

        # The primary axis is redshift, secondary luminosity.
        _data_points = list(
            map(lambda tup: tuple(reversed(tup)),
                iterproduct(self.redshift_bins, self.luminosity_bins)))

        return list(iterfilter(_data_points, self._valid_data_points))
示例#7
0
def dipsum(ftarray):
    (ndt, nxuv, nir, nz, nm, ndip) = shape(ftarray)
    retarray = zeros((nir, nz, nm), dtype='float')
    inplist = [0, 1]
    indxlist = ftindxlist(inplist)
    for i, j, k in iterproduct(range(nir), range(nz), range(nm)):
        retarray[i, j, k] = sum(
            abs(ftarray[indxlist[0], indxlist[1], i, j, k, :])**2)
    return retarray
示例#8
0
    def tile_radially(self, rcutoff):
        radial = []
        icut = 10
        for n in iterproduct(arange(-icut, icut+1), repeat=len(self.latticevecs)):
            latticevec = dot(self.latticevecs, n)
            for atom, vector in self.basis:
                rvec = vector + latticevec
                r = norm(rvec)
#                print r
                if r < rcutoff:
                    radial.append((atom, rvec))
        return radial
def dipg_floq(dip, nmin, nmax, floqphase=0, nconserved=True):
    #vector corresponding to dipole matrix element with ground state
    retvec = zeros(ntot, dtype='complex')
    if (nconserved):
        nrange = range(1)
    else:
        nrange = range(nmin, nmax + 1)
    for i, n in iterproduct(range(nstates), nrange):
        tmpindx = psinindex(i, n, nmin)
        retvec[tmpindx] = dip[0, i]
    retvec = applyfloquetphase(retvec, floqphase)
    return retvec
示例#10
0
    def __init__(self, size=(175, 175), occupied=None):
        self.size = size
        Ndim = len(size)
        #  Create grid and make the center point occupied
        self.grid = zeros(size, dtype=bool)
        if occupied is None:
            middle = tuple(i / 2 for i in size)
            self.grid[middle] = True
        else:
            self.grid[occupied] = True
        # Move to corners of hypercube
        self.directions = array(tuple(iterproduct((1, -1), repeat=Ndim)))
        # Move in only one direction at a time
#         self.directions = self._directions(Ndim)
        print(self.directions)
        self.Ndim = Ndim
示例#11
0
def plot_confusion_matrix(confusionMatrix,
                          classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues,
                          float_fmt='.1f',
                          figsize=(12, 12),
                          rotation=0):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        confusionMatrix = confusionMatrix.astype('float')
        confusionMatrix /= confusionMatrix.sum(axis=1)[:, np.newaxis]
        confusionMatrix = confusionMatrix * 100
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    plt.imshow(confusionMatrix, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()

    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=rotation)
    plt.yticks(tick_marks, classes)

    fmt = float_fmt if normalize else 'd'
    thresh = confusionMatrix.max() / 2.

    range0 = range(confusionMatrix.shape[0])
    range1 = range(confusionMatrix.shape[1])
    for i, j in iterproduct(range0, range1):
        plt.text(j,
                 i,
                 format(confusionMatrix[i, j], fmt) + '%',
                 horizontalalignment="center",
                 color="white" if confusionMatrix[i, j] > thresh else "black")

    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.tight_layout()
    plt.show()
示例#12
0
def fetchphxfiles(Trng=[2500, 3500],
                  grng=[4.0, 5.5],
                  FeHrng=[0.0, 0.0],
                  aMrng=[0.0, 0.0],
                  repo=phxrepo):
    """
    Download all Phoenix spectra covering the provided ranges. Does not
    re-download files that already exist in the directory.

    Default values are from UV variability sample properties.
    """
    def makerng(x, grid):
        if not hasattr(x, '__iter__'):
            x = [np.max(grid[grid < x]), np.min(grid[grid > x])]
        return x

    rngs = [Trng, grng, FeHrng, aMrng]
    rngs = list(map(makerng, rngs, phxgrids))

    def inclusive(grid, rng):
        use = np.logical_and(grid >= rng[0], grid <= rng[1])
        return grid[use]

    grids = list(map(inclusive, phxgrids, rngs))

    combos = iterproduct(*grids)
    paths = []
    for combo in combos:
        locpath = phxurl(*combo, repo=repo)
        if not os.path.exists(locpath):
            paths.append((locpath, phxurl(*combo, repo='ftp')))

    N = len(paths)
    datasize = N * 6.0 / 1024.0
    print(('Beginning download of {} files, {:.3f} Gb. Ctrl-C to stop.'
           ''.format(N, datasize)))
    print('Progress bar (- = 5%):\n')

    Nbar = ceil(N / 20.0)
    for i, (loc, ftp) in enumerate(paths):
        if i % Nbar == 0:
            print('-', end=' ')
        urlretrieve(ftp, loc)
示例#13
0
def ionintpts(tion,w,wenv,nglpts=5):
    #return set of time points & gauss legendre weights required for integrating
    #over a pulse
    pts,wts=leggauss(nglpts)
    pts=(pts+1)/2#map to range [0:1]
    wts=wts/2

    period=(2*pi)/w
    envperiod=(pi)/wenv
    #print("period\t"+str(period))
    #print("envperiod\t"+str(envperiod))
    ncycles=int(ceil(envperiod/period))
    tarray=zeros(nglpts*ncycles)
    wtarray=zeros(nglpts*ncycles)
    tstart=tion-ncycles/2*period
    for i,n in iterproduct(range(nglpts), range(ncycles)):
       tarray[i+n*nglpts]=tstart+(n+pts[i])*period 
       wtarray[i+n*nglpts]=wts[i]*period
    return tarray,wtarray
示例#14
0
    def dvpartition(data, rng):
        nonlocal n_dims
        nonlocal counts
        nonlocal labels
        nonlocal dims

        # Filter out data that is not in our initial partition
        where = product([(i[0] <= data[:, j]) * (i[1] >= data[:, j])
                         for j, i in enumerate(rng)], 0).astype(bool)
        filtered = data[where, :]

        # Subdivide our partitions by the midpoint in each dimension
        partitions = set([])
        part = [linspace(rng[i][0], rng[i][1], 3) for i in dims]
        newrng = set((tuple((part[i][j[i]], part[i][j[i] + 1]) for i in dims)
                      for j in iterproduct(*(n_dims * [[0, 1]]))), )

        # Calculate counts for new partitions
        freq = histogramdd(filtered, bins=part)[0]

        # Perform binomial test which a given alpha,
        # and if not uniform proceed
        if (binom_test(freq) < alpha / 2.
                and False not in ((filtered.max(0) - filtered.min(0)).T > 0)):

            # For each new partition continue algorithm recursively
            for nr in newrng:
                newpart = dvpartition(data, rng=nr)
                for newp in newpart:
                    partitions.update(tuple((newp, )))

        # Else if uniform and contains data, return current partition
        elif filtered.shape[0] > 0:
            partitions = set(tuple((rng, )))
            labels[where] = len(counts)
            counts += (filtered.shape[0], )
        return partitions
示例#15
0
    def dvpartition(data, rng):
        nonlocal n_dims
        nonlocal counts
        nonlocal labels
        nonlocal dims

        # Filter out data that is not in our initial partition
        where = product([(i[0] <= data[:, j]) * (i[1] >= data[:, j])
                        for j, i in enumerate(rng)], 0).astype(bool)
        filtered = data[where, :]

        # Subdivide our partitions by the midpoint in each dimension
        partitions = set([])
        part = [linspace(rng[i][0], rng[i][1], 3) for i in dims]
        newrng = set((tuple((part[i][j[i]], part[i][j[i] + 1]) for i in dims)
                     for j in iterproduct(*(n_dims * [[0, 1]]))),)

        # Calculate counts for new partitions
        freq = histogramdd(filtered, bins=part)[0]

        # Perform binomial test which a given alpha,
        # and if not uniform proceed
        if (binom_test(freq) < alpha / 2. and
                False not in ((filtered.max(0) - filtered.min(0)).T > 0)):

            # For each new partition continue algorithm recursively
            for nr in newrng:
                newpart = dvpartition(data, rng=nr)
                for newp in newpart:
                    partitions.update(tuple((newp,)))

        # Else if uniform and contains data, return current partition
        elif filtered.shape[0] > 0:
            partitions = set(tuple((rng,)))
            labels[where] = len(counts)
            counts += (filtered.shape[0],)
        return partitions
示例#16
0
def solveCongruence(coeffs,m):
    """
    Input:
        coeffs <iterable>: coefficients of polynomial, starting from lowest degree
        m <int>: a positive number
    Output:
        List of all integers x in [0,m) such that ax^2+bx+c = 0 (mod m).
    """
    # solve equation modulo prime powers
    pfp = primeFactors_processed(m)
    baseSolns = []
    for p,e in pfp:
        bs = solveCongruencePrimePower(coeffs,p,e)
        if not bs:
            return []
        baseSolns.append(bs)
    # Chinese remainder theorem
    solns = []
    primePowers = [p**e for p,e in pfp]
    ppTotient = [(p-1)*p**(e-1) for p,e in pfp]
    for bs in iterproduct(*baseSolns):
        s = sum(m//pp*pow(m//pp,ppt-1,pp)*r for pp,ppt,r in zip(primePowers,ppTotient,bs))%m
        solns.append(s)
    return solns
示例#17
0
def sphericalcontraction(ftarray,
                         ndt=0,
                         xuvnum=0,
                         ntheta=100,
                         nphi=100,
                         polarization='z'):
    thetaarray, phiarray = thetaphigrid(ntheta, nphi)
    nxuv = len(veclist[list(namelist).index("xuvphasearray")])
    nIR = len(veclist[list(namelist).index("IRphasearray")])
    njtheta = len(veclist[list(namelist).index("jthetaphasearray")])
    nphiz = len(veclist[list(namelist).index("jphizphasearray")])
    nt = len(veclist[list(namelist).index("tvec")])

    nxuvvec = nvec(nxuv)
    nIRvec = nvec(nIR)
    njthetavec = nvec(njtheta)
    nphizvec = nvec(nphiz)

    ixuv = nxuvvec.index(xuvnum)

    contractedarray = zeros((ntheta, nphi, nt / 2), dtype='complex')
    #do contraction
    matp = sph_harm(1, 1, thetaarray, phiarray)
    mat0 = sph_harm(0, 1, thetaarray, phiarray)
    matm = sph_harm(-1, 1, thetaarray, phiarray)

    for i, j, k in iterproduct(range(nIR), range(njtheta), range(nphiz)):
        Ntot = nIRvec[i]
        Z = njthetavec[j]
        m = nphizvec[k]
        [Np, N0, Nm] = nphotonsolve(Ntot, Z, m, polarization=polarization)
        if ((Np + N0 + Nm) >= 0):
            anglemat = multiphotonmat(Np, N0, Nm, matp, mat0, matm)
            contractedarray += arrayouter(
                anglemat, ftarray[ndt, ixuv, i, j, k, (nt / 2):])
    return contractedarray
        styles.append([c, ls])

enarray = zeros((nt, ntot), dtype='complex')
evecarray = zeros((nt, ntot, ntot), dtype='complex')
sCEP = 0  #streaking CEP phase
for i in range(nt):
    enarray[i, :], evecarray[i, :, :] = instEig_floq(
        H0, Hdip, F0 * envelope(tarray[i], wenv0), sCEP, nmin, nmax)

#adjust evecs to eliminate factors of -1 due to arbitrary sign convention in eig routine
#evecarray=adjustevecarray(evecarray)
enarray, evecarray = adjustevecs(enarray, evecarray, enorder=False)

fig0 = plt.figure()
fig0.suptitle("energies")
for i, n in iterproduct(range(nstates), range(nmin, nmax + 1)):
    tmpindx = psinindex(i, n, nmin)
    plt.plot(Hrt * enarray[:, tmpindx],
             label="i= " + namelist[i] + ", n= " + str(n),
             color=styles[tmpindx][0],
             linestyle=styles[tmpindx][1],
             linewidth=2)
plt.legend()

#plot eigenvectors as a function of time
fign = plotevecn(tarray, evecarray, iname="1s3d", n=-1)

#accumulated phase
phasearray = phaseaccumulation(enarray, dt)
print("shape phasearray\t" + str(shape(phasearray)))
#ionization amplitudes
def goldenruleamps(diparray, enarray, wosc, tau):
    retarray = zeros(shape(enarray))
    (nt, ns) = shape(enarray)
    for i, j in iterproduct(range(nt), range(ns)):
        retarray[i, j] = diparray[i, j] * goldenrule(wosc, enarray[i, j], tau)
    return retarray
示例#20
0
def contraction_cartesiangrid(ftarray,
                              ndt=0,
                              xuvnum=0,
                              polarization='z',
                              **cartesiankwd):
    xarray, yarray, zarray = makecartesianarrays(**cartesiankwd)
    rarray, thetaarray, phiarray = xyztopolar(xarray, yarray, zarray)

    #lengths of various vectors will be needed in order to loop correctly
    nxuv = len(veclist[list(namelist).index("xuvphasearray")])
    nIR = len(veclist[list(namelist).index("IRphasearray")])
    njtheta = len(veclist[list(namelist).index("jthetaphasearray")])
    nphiz = len(veclist[list(namelist).index("jphizphasearray")])
    nt = len(veclist[list(namelist).index("tvec")])

    #vectors containing the photon numbers
    nxuvvec = nvec(nxuv)
    nIRvec = nvec(nIR)
    njthetavec = nvec(njtheta)
    nphizvec = nvec(nphiz)
    nxuvvec = nvec(nxuv)

    ixuv = nxuvvec.index(xuvnum)

    retvals = zeros(shape(xarray), dtype='complex')
    #for every value of Np, N0, Nm, evaluate the partial wave contribution & add to the sum
    #partial wave contribution = angular part times radial part
    #evaluate spherical harmonics & raise to appropriate powers for angular part
    #interpolate to get radial part

    #precompute powers of the spherical harmonics evaluated on interpolation points
    matp = sph_harm(1, 1, thetaarray, phiarray)
    mat0 = sph_harm(0, 1, thetaarray, phiarray)
    matm = sph_harm(-1, 1, thetaarray, phiarray)
    tmpmat = ones(shape(matp), dtype='complex')
    matppowers = [tmpmat, matp]
    mat0powers = [tmpmat, mat0]
    matmpowers = [tmpmat, matm]
    for i in range(2, nIR + 1):
        matppowers.append(matppowers[-1] * matp)
        mat0powers.append(mat0powers[-1] * mat0)
        matmpowers.append(matmpowers[-1] * matm)

    for i, j, k in iterproduct(range(nIR), range(njtheta), range(nphiz)):
        Ntot = nIRvec[i]
        Z = njthetavec[j]
        m = nphizvec[k]
        [Np, N0, Nm] = nphotonsolve(Ntot, Z, m, polarization=polarization)
        if ((Np + N0 + Nm) >= 0):
            if (Np >= 0):
                tmpmatp = matppowers[Np]
            else:
                tmpmatp = conjugate(matppowers[abs(Np)])
            if (N0 >= 0):
                tmpmat0 = mat0powers[N0]
            else:
                tmpmat0 = conjugate(mat0powers[abs(N0)])
            if (Nm >= 0):
                tmpmatm = matppowers[Nm]
            else:
                tmpmatm = conjugate(matppowers[abs(Nm)])

            anglemat = tmpmatp * tmpmat0 * tmpmatm
            radmat = onedinterp(rarray, freqvec, ftarray[ndt, ixuv, i, j,
                                                         k, :])
            retvals += anglemat * radmat
    return xarray, yarray, zarray, retvals
jthetaphasearray = phasearray(njthetaphase)

njphizphase = 11
jphizphasearray = phasearray(njphizphase)

paramindx = 0
pulsearray = []
loopnamelist = [
    'dtarray', 'xuvphasearray', 'IRphasearray', 'jthetaphasearray',
    'jphizphasearray'
]
looplist = [
    dtarray, xuvphasearray, IRphasearray, jthetaphasearray, jphizphasearray
]
printloopkey(resultdir, loopnamelist, looplist)
for i, j, k, l, m in iterproduct(range(ndt), range(nxuvphase), range(nIRphase),
                                 range(njthetaphase), range(njphizphase)):
    dt = dtarray[i]
    xuvphase = xuvphasearray[j] * pi
    IRphase = IRphasearray[k] * pi
    jthetaphase = jthetaphasearray[l] * pi / 2
    jphizphase = jphizphasearray[m] * pi
    pulselist = [
        pulse(I0=Iir,
              w0=wir,
              wenv=IRwenv,
              CEPtheta=IRphase,
              tstart=0,
              jtheta=jthetaphase,
              jphiz=jphizphase),
        pulse(leftcircular=True,
              I0=Ixuv,
示例#22
0
文件: sgt.py 项目: tejaswini0608/sgt
 def __set_feature_names(self, alphabets):
     return list(iterproduct(alphabets, alphabets))
示例#23
0
xuvphasearray = phasearray(nxuvphase)

ncophase = 7
cophasearray = phasearray(ncophase)

ncounterphase = 7
counterphasearray = phasearray(ncounterphase)

paramindx = 0
pulsearray = []
loopnamelist = [
    'dtarray', 'xuvphasearray', 'cophasearray', 'counterphasearray'
]
looplist = [dtarray, xuvphasearray, cophasearray, counterphasearray]
printloopkey(resultdir, loopnamelist, looplist)
for i, j, k, l in iterproduct(range(ndt), range(nxuvphase), range(ncophase),
                              range(ncounterphase)):
    dt = dtarray[i]
    xuvphase = xuvphasearray[j] * pi
    cophase = cophasearray[k] * pi
    counterphase = counterphasearray[l] * pi
    #print("sumphase\t"+str(sumphasearray[l])+"\t"+str(sumphase))
    #IR pulse is split into two pulses: E(t)= 1/sqrt(2)*E0*(cos(wt+IRphase+sumphase)+cos(wt+IRphase-sumphase))
    pulselist = [
        exponential_pulse(I0=Iir / sqrt(2),
                          w0=wir,
                          wenv=IRwenv,
                          CEPtheta=cophase,
                          tstart=0),
        exponential_pulse(I0=Iir / sqrt(2),
                          w0=-wir,
                          wenv=IRwenv,
示例#24
0
def crossproduct(*args):
    """Returns the cross product of any number of lists (or other iterables)"""
    return list(iterproduct(*args))
示例#25
0
    def _parse_options(self, response, product):
        no_options = 0
        # A checkbox is like a group of options but with only one option into it.
        # The checkboxes can be checked or unchecked.
        checkboxes = response.xpath(
            '//*[@id="options"]//input[@data-val-id and @type="checkbox"]')
        # Group of options with radio buttons into it, we can select only one of each group.
        # But always will be one of each group selected.
        radio_groups = response.xpath('//div[@class="input-group type-radio"]')
        # [[(<id>, <name>, <price_incr>), ...],
        # ...]
        check_options = []
        for checkbox in checkboxes:
            val_id = checkbox.xpath('@data-val-id').extract()[0]
            val_name = checkbox.xpath('@data-caption').extract()[0]
            val_price = extract_price(
                checkbox.xpath('@data-price-adjustment').extract()[0].replace(
                    ' ', ''))
            if not val_price:
                # Only options that change the price
                continue
            check_options.append([
                [val_id, val_name, val_price],
            ])
        radio_options = []
        for radios_cont in radio_groups:
            radios = radios_cont.xpath('.//input[@data-val-id]')
            radios_group = [['', '', '0']]  # Unselected ...
            for radio in radios:
                val_id = radio.xpath('@data-val-id').extract()[0]
                val_name = radio.xpath('@data-caption').extract()[0]
                val_price = extract_price(
                    radio.xpath('@data-price-adjustment').extract()[0].replace(
                        ' ', ''))
                if not val_price:
                    continue
                radios_group.append([val_id, val_name, val_price])
            radio_options.append(radios_group)

        radios_product = []
        if radio_options:
            radios_product_iter = iterproduct(*radio_options)
            # Filter to keep only those which have at least one selected
            # The website is using radio buttons but always there is one of them which not increases the price
            i = 0
            for d in radios_product_iter:
                if any([s[0] != '' for s in d]):
                    i += 1
                    if i > self.limit_options_to:
                        break
                    radios_product.append(d)

        for options in radios_product:
            if no_options > self.limit_options_to:
                return
            new_item = Product(product)
            for option in options:
                if option[0] == '':
                    # Unselected
                    continue
                new_item['identifier'] += '-' + option[0]
                new_item['name'] += ', ' + option[1]
                new_item['price'] = Decimal(new_item['price']) + option[2]

            no_options += 1
            yield new_item

        for i in range(1, len(check_options) + 1):
            check_combs = combinations(check_options, i)
            for checkbox_comb in check_combs:
                if no_options > self.limit_options_to:
                    return
                """
                Example:

                If options are:
                [['one', 'One', '1.5'], ['two', 'Two', '2'], ['three', 'Three', '3']]

                Then the combination will be:
                [(['one', 'One', '1.5'],),
                 (['two', 'Two', '2'],),
                 (['three', 'Three', '3'],)]

                [(['one', 'One', '1.5'], ['two', 'Two', '2']),
                 (['one', 'One', '1.5'], ['three', 'Three', '3']),
                 (['two', 'Two', '2'], ['three', 'Three', '3'])]

                [(['one', 'One', '1.5'], ['two', 'Two', '2'], ['three', 'Three', '3'])]
                """
                new_item = Product(product)
                for checkbox_opts in checkbox_comb:
                    for check_opt in checkbox_opts:
                        new_item['identifier'] += '-' + check_opt[0]
                        new_item['name'] += ', ' + check_opt[1]
                        new_item['price'] = Decimal(
                            new_item['price']) + check_opt[2]
                no_options += 1
                yield new_item

                for options in radios_product:
                    if no_options > self.limit_options_to:
                        return
                    new_new_item = new_item.copy()
                    for option in options:
                        if option[0] == '':
                            # Unselected
                            continue
                        new_new_item['identifier'] += '-' + option[0]
                        new_new_item['name'] += ', ' + option[1]
                        new_new_item['price'] = Decimal(
                            new_new_item['price']) + option[2]
                    no_options += 1
                    yield new_new_item
#number of phase points for XUV and IR pulses
nxuvphase = 5
xuvphasearray = phasearray(nxuvphase)

nIRphase = 5
IRphasearray = phasearray(nIRphase)

nsumphase = 5
sumphasearray = phasearray(nsumphase)

paramindx = 0
pulsearray = []
loopnamelist = ['dtarray', 'xuvphasearray', 'IRphasearray', 'sumphasearray']
looplist = [dtarray, xuvphasearray, IRphasearray, sumphasearray]
printloopkey(resultdir, loopnamelist, looplist)
for i, j, k, l in iterproduct(range(ndt), range(nxuvphase), range(nIRphase),
                              range(nsumphase)):
    dt = dtarray[i]
    xuvphase = xuvphasearray[j] * pi
    IRphase = IRphasearray[k] * pi
    sumphase = sumphasearray[l] * pi
    #print("sumphase\t"+str(sumphasearray[l])+"\t"+str(sumphase))
    #IR pulse is split into two pulses: E(t)= 1/sqrt(2)*E0*(cos(wt+IRphase+sumphase)+cos(wt+IRphase-sumphase))
    pulselist = [
        pulse(I0=Iir / sqrt(2),
              w0=wir,
              wenv=IRwenv,
              CEPtheta=IRphase + sumphase,
              tstart=0),
        pulse(I0=Iir / sqrt(2),
              w0=wir,
              wenv=IRwenv,