Ejemplo n.º 1
0
def th_roc_glq(mod_order, snr_db, n_samples, n_thresh, n_terms, fading, *args):
    """
    Computes the theorectical CROC using the Gauss-Laguerre quadrature.

    Parameters
    ----------
    mod_order : int
        Modulation order.
    snr_db : float
        Signal-to-noise ratio in dB.
    n_samples : int
        Number of transmitted symbols.
    n_thresh : int
        Number of thresholds to be evaluated.
    n_terms : int
        Number of terms for the Gauss-Laguerre quadrature.
    fading : str
        Name of the fading.
    args : array-like
        Fading parameters.
    """
    
    if fading not in FADINGS:
        raise NotImplementedError('the formulations for this fading is not'
                                  ' implemented yet.')

    thresholds = np.linspace(.0, 100.0, n_thresh)
    
    # symbol energy
    Es = 1./mod_order
    # noise variance
    var_w = Es*sps.exp10(-snr_db/10.)

    Pf = 1 - sps.gammainc(n_samples/2., thresholds/(2*var_w))
    Pm = 0.0

    printProgress(0, n_terms, prefix='Progress', suffix='Complete', barLength=50)

    if fading == 'exp_weibull':
        beta, alpha, eta = args[0:3]        
        roots, weights = sps.orthogonal.la_roots(n_terms, 0.0)
 
        for k in range(n_terms):
            Pm = Pm + (weights[k] * (1 - math.exp(-roots[k]))**(alpha - 1))*(1 - marcumQ(math.sqrt(n_samples * Es * (eta * roots[k]**(1./beta))**2 / var_w), np.sqrt(thresholds / var_w), n_samples / 2.0))
            printProgress(k, n_terms-1, prefix='Progress', suffix='Complete', barLength=50)

        Pm = alpha*Pm

    elif fading == 'gamma_gamma':
        beta, alpha = args[0:2]
        roots, weights = sps.orthogonal.la_roots(n_terms, 0.5*(alpha + beta))

        for k in range(n_terms):
            Pm = Pm + weights[k] * math.exp(roots[k]) * kv(alpha - beta, 2 * math.sqrt(alpha * beta * roots[k])) * (1 - marcumQ(roots[k] * math.sqrt(n_samples * Es /var_w), np.sqrt(thresholds / var_w), n_samples / 2.0)) 
            printProgress(k, n_terms-1, prefix='Progress', suffix='Complete', barLength=50)

        Pm = Pm * 2 * (alpha * beta)**(0.5 * (alpha + beta)) / (gamma(alpha) * gamma(beta))

    return Pf, Pm
Ejemplo n.º 2
0
def th_roc_num(mod_order, snr_db, n_samples, n_thresh, fading, *args):
    """
    Computes the theorectical CROC using the scipy numerical integration
    library.

    Parameters
    ----------
    mod_order : int
        Modulation order.
    snr_db : float
        Signal-to-noise ratio in dB.
    n_samples : int
        Number of transmitted symbols.
    n_thresh : int
        Number of thresholds to be evaluated.
    n_terms : int
        Number of terms for the Gauss-Laguerre quadrature.
    fading : str
        Name of the fading.
    args : array-like
        Fading parameters.
    """

    if fading not in FADINGS:
        raise NotImplementedError('the formulations for this fading is not'
                                  ' implemented yet.')

    thresholds = np.linspace(.0, 100.0, n_thresh)
    
    # symbol energy
    Es = 1./mod_order
    # noise variance
    var_w = Es*sps.exp10(-snr_db/10.)

    Pf = 1 - sps.gammainc(n_samples/2., thresholds/(2*var_w))
    Pm = np.zeros(n_thresh)

    printProgress(0, n_thresh, prefix='Progress', suffix='Complete', barLength=50)        
    if fading == 'exp_weibull':
        beta, alpha, eta = args[0:3]

        for k in range(n_thresh):
            integrand = lambda u: (alpha*math.exp(-u)*(1 - math.exp(-u))**(alpha-1)) * (1 - marcumQ(math.sqrt(n_samples*Es*(eta*u**(1./beta))**2/var_w), math.sqrt(thresholds[k]/var_w), n_samples/2.0))
            Pm[k] = quad(integrand, 0.0, np.inf, epsrel=1e-9, epsabs=0)[0]
            printProgress(k, n_thresh-1, prefix='Progress', suffix='Complete', barLength=50)

    elif fading == 'gamma_gamma':
        beta, alpha = args[0:2]

        for k in range(n_thresh):
            integrand = lambda r: r**(0.5 * (alpha + beta)) * kv(alpha - beta, 2 * math.sqrt(alpha * beta * r)) * (1 - marcumQ(r * math.sqrt(n_samples * Es / var_w), np.sqrt(thresholds[k] / var_w), n_samples / 2.0))
            Pm[k] = quad(integrand, 0.0, np.inf, epsrel=1e-9, epsabs=0)[0] * 2 * (alpha * beta)**(0.5 * (alpha + beta)) / (gamma(alpha) * gamma(beta))
            printProgress(k, n_thresh-1, prefix='Progress', suffix='Complete', barLength=50)

    return Pf, Pm
Ejemplo n.º 3
0
def th_roc_glq(mod_order, snr_db, n_samples, n_thresh, n_terms, fading, *args):
    """
    Computes the theorectical CROC using the Gauss-Laguerre quadrature.

    Parameters
    ----------
    mod_order : int
        Modulation order.
    snr_db : float
        Signal-to-noise ratio in dB.
    n_samples : int
        Number of transmitted symbols.
    n_thresh : int
        Number of thresholds to be evaluated.
    n_terms : int
        Number of terms for the Gauss-Laguerre quadrature.
    fading : str
        Name of the fading.
    args : array-like
        Fading parameters.
    """

    if fading not in FADINGS:
        raise NotImplementedError('the formulations for this fading is not'
                                  ' implemented yet.')

    thresholds = np.linspace(.0, 100.0, n_thresh)

    # symbol energy
    Es = 1. / mod_order
    # noise variance
    var_w = Es * sps.exp10(-snr_db / 10.)

    Pf = 1 - sps.gammainc(n_samples / 2., thresholds / (2 * var_w))
    Pm = np.zeros(n_thresh)

    # Gauss-Laguerre quadrature
    glq = 0.0

    if fading == 'exp_weibull':
        beta, alpha, eta = args[0:3]
        roots, weights = sps.orthogonal.la_roots(n_terms, 0.0)

        for k in range(n_terms):
            glq = (glq + weights[k] * (1 - math.exp(-roots[k])**(alpha - 1)) *
                   (1 - marcumQ(
                       math.sqrt(2 * n_samples * Es *
                                 (eta * roots[k]**(1. / beta))**2 / var_w),
                       np.sqrt(2 * thresholds / var_w), n_samples)))
        Pm *= alpha

    return Pf, Pm
Ejemplo n.º 4
0
def th_roc_glq(mod_order, snr_db, n_samples, n_thresh, n_terms, fading, *args):
    """
    Computes the theorectical CROC using the Gauss-Laguerre quadrature.

    Parameters
    ----------
    mod_order : int
        Modulation order.
    snr_db : float
        Signal-to-noise ratio in dB.
    n_samples : int
        Number of transmitted symbols.
    n_thresh : int
        Number of thresholds to be evaluated.
    n_terms : int
        Number of terms for the Gauss-Laguerre quadrature.
    fading : str
        Name of the fading.
    args : array-like
        Fading parameters.
    """

    if fading not in FADINGS:
        raise NotImplementedError('the formulations for this fading is not'
                                  ' implemented yet.')

    thresholds = np.linspace(.0, 100.0, n_thresh)
    
    # symbol energy
    Es = 1./mod_order
    # noise variance
    var_w = Es*sps.exp10(-snr_db/10.)

    Pf = 1 - sps.gammainc(n_samples/2., thresholds/(2*var_w))
    Pm = np.zeros(n_thresh)

    # Gauss-Laguerre quadrature
    glq = 0.0

    if fading == 'exp_weibull':
        beta, alpha, eta = args[0:3]
        roots, weights = sps.orthogonal.la_roots(n_terms, 0.0)

        for k in range(n_terms):
            glq = (glq + weights[k]*(1 - math.exp(-roots[k])**(alpha-1))*
                   (1 - marcumQ(math.sqrt(2*n_samples*Es*(eta*roots[k]**(1./beta))**2/var_w),
                                np.sqrt(2*thresholds/var_w),
                                n_samples)))
        Pm *= alpha

    return Pf, Pm
Ejemplo n.º 5
0
def th_roc_num(mod_order, snr_db, n_samples, n_thresh, fading, *args):
    """
    Computes the theorectical CROC using the Gauss-Laguerre quadrature.

    Parameters
    ----------
    mod_order : int
        Modulation order.
    snr_db : float
        Signal-to-noise ratio in dB.
    n_samples : int
        Number of transmitted symbols.
    n_thresh : int
        Number of thresholds to be evaluated.
    n_terms : int
        Number of terms for the Gauss-Laguerre quadrature.
    fading : str
        Name of the fading.
    args : array-like
        Fading parameters.
    """

    if fading not in FADINGS:
        raise NotImplementedError('the formulations for this fading is not'
                                  ' implemented yet.')

    thresholds = np.linspace(.0, 100.0, n_thresh)

    # symbol energy
    Es = 1. / mod_order
    # noise variance
    var_w = Es * sps.exp10(-snr_db / 10.)

    Pf = 1 - sps.gammainc(n_samples / 2., thresholds / (2 * var_w))
    Pm = np.zeros(n_thresh)

    if fading == 'exp_weibull':
        beta, alpha, eta = args[0:3]
        for k in range(n_thresh):
            integrand = lambda u: (alpha * math.exp(-u) * (1 - math.exp(-u)**(
                alpha - 1)) * (1 - marcumQ(
                    math.sqrt(2 * n_samples * Es *
                              (eta * u**(1. / beta))**2 / var_w),
                    math.sqrt(2 * thresholds[k] / var_w), n_samples)))
            Pm[k] = quad(integrand, 0.0, np.inf, epsrel=1e-9, epsabs=0)[0]

    return Pf, Pm
Ejemplo n.º 6
0
def th_roc_num(mod_order, snr_db, n_samples, n_thresh, fading, *args):
    """
    Computes the theorectical CROC using the Gauss-Laguerre quadrature.

    Parameters
    ----------
    mod_order : int
        Modulation order.
    snr_db : float
        Signal-to-noise ratio in dB.
    n_samples : int
        Number of transmitted symbols.
    n_thresh : int
        Number of thresholds to be evaluated.
    n_terms : int
        Number of terms for the Gauss-Laguerre quadrature.
    fading : str
        Name of the fading.
    args : array-like
        Fading parameters.
    """

    if fading not in FADINGS:
        raise NotImplementedError('the formulations for this fading is not'
                                  ' implemented yet.')

    thresholds = np.linspace(.0, 100.0, n_thresh)
    
    # symbol energy
    Es = 1./mod_order
    # noise variance
    var_w = Es*sps.exp10(-snr_db/10.)

    Pf = 1 - sps.gammainc(n_samples/2., thresholds/(2*var_w))
    Pm = np.zeros(n_thresh)

    if fading == 'exp_weibull':
        beta, alpha, eta = args[0:3]
        for k in range(n_thresh):
            integrand = lambda u: (alpha*math.exp(-u)*(1 - math.exp(-u)**(alpha-1))*
                                   (1 - marcumQ(math.sqrt(2*n_samples*Es*(eta*u**(1./beta))**2/var_w),
                                                math.sqrt(2*thresholds[k]/var_w),
                                                n_samples)))
            Pm[k] = quad(integrand, 0.0, np.inf, epsrel=1e-9, epsabs=0)[0]

    return Pf, Pm
Ejemplo n.º 7
0
def gen(x, name):
    """Generate fixture data and write to file.

    # Arguments

    * `x`: domain
    * `name::str`: output filename

    # Examples

    ``` python
    python> x = linspace(-1000.0, 1000.0, 2001)
    python> gen(x, './data.json')
    ```
    """
    y = exp10(x)
    data = {"x": x.tolist(), "expected": y.tolist()}

    # Based on the script directory, create an output filepath:
    filepath = os.path.join(DIR, name)

    # Write the data to the output filepath as JSON:
    with open(filepath, "w") as outfile:
        json.dump(data, outfile)
Ejemplo n.º 8
0
from scipy import special

# for computing 10^x
a = special.exp10(2)
print(a)

# for computing 2^x
a = special.exp2(3)
print(a)

# sin function
s = special.sindg(90)
print(s)

# cos function
c = special.cosdg(90)
print(c)
Ejemplo n.º 9
0
        punti_sperimentali[elem]['moduli']
        for elem in range(len(punti_sperimentali))
    ]))

eq_master_sperimentale = UnivariateSpline(tempi_totali,
                                          moduli_totali,
                                          k=1,
                                          s=0)
x_totali = numpy.linspace(tempi_totali[0], tempi_totali[-1], CALC_STEPS)
y_interpolati_sper = eq_master_sperimentale(x_totali)

required_time = numpy.log10(REQUIRED_TIME) - numpy.log10(
    arrhenius(ENTALPIA, 25 + 273,
              97 + 273))  # 10 anni corretti da shift factor
indice_modulo = bisect(x_totali, required_time)
modulo_shiftato = special.exp10(y_interpolati_sper[indice_modulo])
spessore = special.cbrt(
    (3 * L**4 * P * modulo_shiftato) / (4 * f * (1 + nu)))  # metri

# Inizia il codice per i grafici

f1 = plt.figure()
plt.title("Master curve")
plt.xlabel(r"$log(t) \,\, [s]$")
plt.ylabel(r"$log(J) \,\, [Pa^{-1}]$")
plt.plot(x_totali, y_interpolati_sper)
plt.hold('on')

f2 = plt.figure()

#
Ejemplo n.º 10
0
from scipy import *
print(help(cluster))
import scipy
scipy.info(cluster)
scipy.source(cluster)
#special functions in scipy
#exponential functions
from scipy import special
a = special.exp10(3)
print(a)
b = special.exp2(2)
print(b)
#trigonametry
c = special.sindg(90)
print(c)
d = special.cosdg(90)
print(d)
#Integraion function
#general integration
from scipy import integrate
e = scipy.integrate.quad(lambda x: special.exp10(x), 0, 1)
print(e)
#Double itegration
f = lambda x, y: x * y**2
g = lambda x: 1
h = lambda x: -1
integrate.dblquad(f, 0, 2, g, h)
#fourier Transformations
from scipy.fftpack import fft, ifft
import numpy as np
x = np.array([1, 2, 3, 4])
Ejemplo n.º 11
0
from scipy import cluster
from scipy import fftpack
from scipy import special

# use help() function to see sub packages
# help()
# to make reference to scipy use sp
# to see information of the subpackage fftpack
# sp.info(fftpack)
# sp.source(cluster)

# use the special function to access math functions
func = special.kelvin(15)
print(func)

func1 = special.exp10(5)
print(func1)

func2 = special.xlogy(2, 10)
print(func2)

func3 = special.sindg(105)
print(func3)

# Use integrate function to integrate variables
var1 = lambda a: a**3
function1 = integrate.quad(var1, 0, 6)
print(function1)
# Double integration of two variable x and y
var2 = lambda y, x: x * y**4
function2 = integrate.dblquad(var2, 0, 6, lambda x: 0, lambda x: 1)
Ejemplo n.º 12
0
#!/usr/bin/env python3
"""Scipy examples."""
import numpy as np
from scipy import linalg
# pylint: disable=no-name-in-module
from scipy.special import comb, exp10, perm

# find combinations of 5, 2 values using comb(N, k)
COM = comb(5, 2, exact=False, repetition=True)
print(COM)

# find permutation of 5, 2 using perm (N, k) function
PER = perm(5, 2, exact=True)
print(PER)

EXP = exp10([1, 10])
print(EXP)

# define square matrix
TWO_D_ARRAY = np.array([[4, 5], [3, 2]])
# pass values to det() function
print(linalg.det(TWO_D_ARRAY))
print(linalg.inv(TWO_D_ARRAY))

ARR = np.array([[5, 4], [6, 3]])
# pass value into function
EG_VAL, EG_VECT = linalg.eig(ARR)
# get eigenvalues
print(EG_VAL)
# get eigenvectors
print(EG_VECT)
Ejemplo n.º 13
0
vertices=hstack((vertices,vstack((horizontal,-100*ones(26)))))
vertices=hstack((vertices,vstack((200*ones(16),vertical))))
vertices=hstack((vertices,vstack((-200*ones(16),vertical))))

inside_vertices=where( multiply(abs(vertices[0])<=200,
    abs(vertices[1])<=100))
vertices=vertices[:,inside_vertices[0]]

triangulation=Delaunay(vertices.T)

index2point=lambda index:triangulation.points[index]
all_centers=index2point(triangulation.vertices).mean(axis=1)
not_in_wing=lambda pt: (pt[0]/128)**2+(pt[1]/16)**2>=1
trngl_set=triangulation.vertices[where(map(not_in_wing, all_centers))]

kappa=lambda pt: exp10(6)*(pt[0]>99.99)
gN=lambda pt:float(pt[0]<=99.99)

points=triangulation.points.shape[0]
stiff_matrix=dok_matrix((points,points))
Robin_matrix=dok_matrix((points,points))
Robin_vector=zeros((points,1))

for triangle in triangulation.vertices:
    helper_matrix=dok_matrix((points,points))
    pt1,pt2,pt3=index2point(triangle)
    area=abs(0.5*cross(pt2-pt1,pt3-pt1))
    coeffs=0.5*vstack((pt2-pt3,pt2-pt1,pt1-pt2))/area
    helper_matrix[triangle,triangle]=array(mat(coeffs)*mat(coeffs).T)
    stiff_matrix=stiff_matrix+helper_matrix
Ejemplo n.º 14
0
SAVE_MODEL_AT = [10]
LOCAL_FOLDER = 'train_11_07/complete_training_test'
PHASE = 'full_training'

STEM = ''
USE_SOFTMAX = True
AVERAGING_METHOD = 'micro'
LR_INT = [1e-6, 1e-3]
NUM_DRAWS = 3
BATCH_SIZES = [64]
DEVICE = torch.device('cuda')
DEEP_RANDOMIZATION = True
NLL = True

# Setup
learning_rates = exp10(-np.random.uniform(-np.log10(LR_INT[0]), -np.log10(LR_INT[1]), size=NUM_DRAWS))

# label_dim = 3
# annotator_dim = 38
# dataset = EmotionDataset(device=DEVICE)
# dataset_name = 'emotion'
# task = 'valence'

# label_dim = 2
# annotator_dim = 2
# dataset = TripAdvisorDataset(device=DEVICE)
# dataset_name = 'tripadvisor'
# task = 'gender'

# label_dim = 2
# annotator_dim = 2
Ejemplo n.º 15
0
from scipy import integrate, special

i = integrate.quad(lambda x: special.exp10(x), 0, 1)
print(i)
Ejemplo n.º 16
0
import numpy as np
from scipy.special import cbrt, exp10, comb, perm


if __name__ == "__main__":
    #Find cubic root of 27 & 64 using cbrt() function
    cb = cbrt([27, 64])
    #print value of cb
    print(cb)

    #define exp10 function and pass value in its
    exp = exp10([1,10])
    print(exp)

    #find permutation of 5, 2 using perm (N, k) function
    per = perm(5, 2, exact = True)
    print(per)

    #find combinations of 5, 2 values using comb(N, k)
    com = comb(5, 2, exact = False, repetition=True)
    print(com)

Ejemplo n.º 17
0
def get_learning_rates(start, end, num_draws):
    return exp10(
        -np.random.uniform(-np.log10(start), -np.log10(end), size=num_draws))
Ejemplo n.º 18
0
import scipy as sp
from scipy import integrate
from scipy import cluster
from scipy import fftpack
from scipy import special

help()
#sp.source()
#sp.info()
sci = special.kelvin(16)
sci1 = special.xlogy(15)
sci2 = special.exp10(40)
print(sci)
print(sci1)
print(sci2)
Ejemplo n.º 19
0
def th_roc_num(mod_order, snr_db, n_samples, n_thresh, fading, *args):
    """
    Computes the theorectical CROC using the scipy numerical integration
    library.

    Parameters
    ----------
    mod_order : int
        Modulation order.
    snr_db : float
        Signal-to-noise ratio in dB.
    n_samples : int
        Number of transmitted symbols.
    n_thresh : int
        Number of thresholds to be evaluated.
    n_terms : int
        Number of terms for the Gauss-Laguerre quadrature.
    fading : str
        Name of the fading.
    args : array-like
        Fading parameters.
    """

    if fading not in FADINGS:
        raise NotImplementedError('the formulations for this fading is not'
                                  ' implemented yet.')

    thresholds = np.linspace(.0, 100.0, n_thresh)

    # symbol energy
    Es = 1. / mod_order
    # noise variance
    var_w = Es * sps.exp10(-snr_db / 10.)

    Pf = 1 - sps.gammainc(n_samples / 2., thresholds / (2 * var_w))
    Pm = np.zeros(n_thresh)

    printProgress(0,
                  n_thresh,
                  prefix='Progress',
                  suffix='Complete',
                  barLength=50)
    if fading == 'exp_weibull':
        beta, alpha, eta = args[0:3]

        for k in range(n_thresh):
            integrand = lambda u: (alpha * math.exp(-u) * (1 - math.exp(-u))**(
                alpha - 1)) * (1 - marcumQ(
                    math.sqrt(n_samples * Es *
                              (eta * u**(1. / beta))**2 / var_w),
                    math.sqrt(thresholds[k] / var_w), n_samples / 2.0))
            Pm[k] = quad(integrand, 0.0, np.inf, epsrel=1e-9, epsabs=0)[0]
            printProgress(k,
                          n_thresh - 1,
                          prefix='Progress',
                          suffix='Complete',
                          barLength=50)

    elif fading == 'gamma_gamma':
        beta, alpha = args[0:2]

        for k in range(n_thresh):
            integrand = lambda r: r**(0.5 * (alpha + beta)) * kv(
                alpha - beta, 2 * math.sqrt(alpha * beta * r)) * (1 - marcumQ(
                    r * math.sqrt(n_samples * Es / var_w),
                    np.sqrt(thresholds[k] / var_w), n_samples / 2.0))
            Pm[k] = quad(integrand, 0.0, np.inf, epsrel=1e-9,
                         epsabs=0)[0] * 2 * (alpha * beta)**(
                             0.5 *
                             (alpha + beta)) / (gamma(alpha) * gamma(beta))
            printProgress(k,
                          n_thresh - 1,
                          prefix='Progress',
                          suffix='Complete',
                          barLength=50)

    return Pf, Pm
Ejemplo n.º 20
0
def th_roc_glq(mod_order, snr_db, n_samples, n_thresh, n_terms, fading, *args):
    """
    Computes the theorectical CROC using the Gauss-Laguerre quadrature.

    Parameters
    ----------
    mod_order : int
        Modulation order.
    snr_db : float
        Signal-to-noise ratio in dB.
    n_samples : int
        Number of transmitted symbols.
    n_thresh : int
        Number of thresholds to be evaluated.
    n_terms : int
        Number of terms for the Gauss-Laguerre quadrature.
    fading : str
        Name of the fading.
    args : array-like
        Fading parameters.
    """

    if fading not in FADINGS:
        raise NotImplementedError('the formulations for this fading is not'
                                  ' implemented yet.')

    thresholds = np.linspace(.0, 100.0, n_thresh)

    # symbol energy
    Es = 1. / mod_order
    # noise variance
    var_w = Es * sps.exp10(-snr_db / 10.)

    Pf = 1 - sps.gammainc(n_samples / 2., thresholds / (2 * var_w))
    Pm = 0.0

    printProgress(0,
                  n_terms,
                  prefix='Progress',
                  suffix='Complete',
                  barLength=50)

    if fading == 'exp_weibull':
        beta, alpha, eta = args[0:3]
        roots, weights = sps.orthogonal.la_roots(n_terms, 0.0)

        for k in range(n_terms):
            Pm = Pm + (weights[k] *
                       (1 - math.exp(-roots[k]))**(alpha - 1)) * (1 - marcumQ(
                           math.sqrt(n_samples * Es *
                                     (eta * roots[k]**(1. / beta))**2 / var_w),
                           np.sqrt(thresholds / var_w), n_samples / 2.0))
            printProgress(k,
                          n_terms - 1,
                          prefix='Progress',
                          suffix='Complete',
                          barLength=50)

        Pm = alpha * Pm

    elif fading == 'gamma_gamma':
        beta, alpha = args[0:2]
        roots, weights = sps.orthogonal.la_roots(n_terms, 0.5 * (alpha + beta))

        for k in range(n_terms):
            Pm = Pm + weights[k] * math.exp(roots[k]) * kv(
                alpha - beta, 2 * math.sqrt(alpha * beta * roots[k])) * (
                    1 - marcumQ(roots[k] * math.sqrt(n_samples * Es / var_w),
                                np.sqrt(thresholds / var_w), n_samples / 2.0))
            printProgress(k,
                          n_terms - 1,
                          prefix='Progress',
                          suffix='Complete',
                          barLength=50)

        Pm = Pm * 2 * (alpha * beta)**(0.5 * (alpha + beta)) / (gamma(alpha) *
                                                                gamma(beta))

    return Pf, Pm
Ejemplo n.º 21
0
import scipy
from scipy import cluster
from scipy import special
from scipy import integrate

a = special.exp10(2)
print(a)

b = special.exp2(2)
print(b)

c = special.sindg(90)
print(c)

print(special.cosdg(0))

print(scipy.integrate.quad(lambda x: special.exp10(x), 0, 1))
Ejemplo n.º 22
0
# -*- coding: utf-8 -*-
"""
Created on Fri May  1 20:35:19 2020

@author: Shivanshu
"""

from scipy import special
from scipy import integrate
import numpy as np
from scipy import linalg

n = special.exp10(2)  #exponantial

x = special.sindg(90)  # value of sin angle
print(n, x)

i = integrate.quad(lambda x: special.exp10(2), 0, 1)  #integration
print(i)

a = np.array([[1, 2], [3, 4]])
b = linalg.inv(a)
print(b)  # inverse of matrix (linear algebra)
from scipy import cluster
import scipy
#help(cluster)

#scipy.info(cluster)

#help()

#special functions

from scipy import special

a = special.exp10(4)

print(a)

#getting the sin value
c = special.sindg(45)

print(c)

#intergrations

from scipy import integrate

i = scipy.integrate.quad(lambda x: x * 2 + 4, 2, 6)
print(i)

#fourirer tranformations

from scipy.fftpack import fft, ifft
Ejemplo n.º 24
0
def adjust_learning_rate(optimizer, epoch, lr):
    """Sets the learning rate to the initial LR decayed by 10 every 20 epochs"""
    lr = lr / exp10(epoch / 20)
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr
Ejemplo n.º 25
0
alpha_list = [0.5, 1.0, 1.5, 2.0]
index_left = int(
    (np.where(log_f == log_f[np.abs(log_f - fitting_range[0]).argmin()])[0]))
index_right = int((np.where(
    log_f == log_f[np.abs(log_f - fitting_range[1]).argmin()])[0]) + 1)
log_f_fitting = log_f[index_left:index_right]
f_fitting = f[index_left:index_right]

for i in range(len(alpha_list)):
    S_alpha = psd_one_over_f(
        f, find_kappa(alpha_list[i]), gamma_arr,
        find_sigma_ou(1, find_kappa(alpha_list[i]), gamma_arr))
    S_alpha_fitting = S_alpha[index_left:index_right]
    popt, pcov = curve_fit(func2,
                           log_f_fitting,
                           np.log10(S_alpha_fitting),
                           maxfev=5000)
    plt.plot(log_f,
             S_alpha,
             label='alpha = ' + str(alpha_list[i]) + ' (alpha = ' +
             str(round(popt[1], 5)) + ' from fitting)')
    plt.plot(log_f_fitting, exp10(func2(log_f_fitting, *popt)))

plt.yscale("log")
plt.xlabel("log f")
plt.ylabel("Normalized S(f)")
plt.title('OU_composed 1/f^(alpha) noise')
plt.legend()
plt.show()
'''''' '''''' '''''' ''
Ejemplo n.º 26
0
from scipy import integrate
from scipy import linalg
# help(integrate)

# sp.info(fftpack)
# sp.source(cluster)


fun1 = special.kelvin(15)
print(fun1)


fun2 = special.xlogy(2, 10)
print(fun2)

fun3 = special.exp10(50)
print(fun3)

fun4 = special.sindg(60)
print(fun4)

fun5 = special.cosdg(60)
print(fun5)

print('---------------------')


def var1(x): return x**3


fun6 = integrate.quad(var1, 0, 6)
Ejemplo n.º 27
0
    def simulate(self,sourceType,sourceSpectrum,airmass=1.,nread=1.,expTime=None,downsampling=5):
        """
        simulate

        Simulates an observation of the specified source type and spectrum and at the specified
        air mass. The source type must be supported by the instrument model (as specified by
        Instrument.getSourceTypes). The source spectrum should either be a SpectralFluxDensity
        object, or else should contain equal-length arrays of wavelength in Angstroms
        and flux in units of 1e-17 erg/(cm^2*s*Ang) as sourceSpectrum[0:1].

        Uses the specified exposure time (secs) or the instrument's nominal exposure time if expTime
        is None. The read noise is scaled by sqrt(nread).

        Use the setWavelengthGrid() method to specify the grid of wavelengths used for
        this simulation, otherwise the default is to use the atmosphere's sky spectrum
        wavelength grid. After applying resolution smoothing, the results are downsampled in
        wavelength using the specified factor.

        Returns a numpy array of results with one row per downsampled wavelength bin containing
        the following named columns in a numpy.recarray:

         - wave: wavelength in Angstroms
         - srcflux: source flux in 1e-17 erg/s/cm^2/Ang
         - obsflux: estimate of observed co-added flux in 1e-17 erg/s/cm^2/Ang
         - ivar: inverse variance of obsflux in 1/(1e-17 erg/s/cm^2/Ang)**2
         - snrtot: total signal-to-noise ratio of coadded spectrum
         - nobj[j]: mean number of observed photons from the source in camera j
         - nsky[j]: mean number of observed photons from the sky in camera j
         - rdnoise[j]: RMS read noise in electrons in camera j
         - dknoise[j]: RMS dark current shot noise in electrons in camera j
         - snr[j]: signal-to-noise ratio in camera j
         - camivar[j]: inverse variance of source flux in (1e-17 erg/s/cm^2/Ang)^-2 in camera j
         - camflux[j]: source flux in 1e-17 erg/s/cm^2/Ang in camera j 
                     (different for each camera because of change of resolution)
                
         

        Note that the number of cameras (indexed by j) in the returned results is not hard coded
        but determined by the instrument we were initialized with. Cameras are indexed in order
        of increasing wavelength.

        After calling this method the following high-resolution (pre-downsampling) arrays are also
        available as data members:

         - wavelengthGrid ~ wave
         - sourceFlux ~ srcflux
         - observedFlux ~ obsflux

        In addition, each camera provides the following arrays tabulated on the same high-resolution
        wavelength grid:

         - throughput
         - sourcePhotonsSmooth ~ nobj
         - skyPhotonRateSmooth ~ nsky/expTime
         - readnoisePerBin ~ rdnoise
         - darkCurrentPerBin ~ sqrt(dknoise/expTime)

        These are accessible using the same camera index j, e.g. qsim.cameras[j].throughput.
        """
        # Check that this is a supported source type.
        if sourceType not in self.instrument.fiberloss:
            raise RuntimeError('Quick.simulate: source type %s is not one of %s.' %
                (sourceType,','.join(self.instrument.getSourceTypes())))

        # Use the instrument's nominal exposure time by default.
        if expTime is None:
            expTime = self.instrument.model['exptime']

        # Use a wavelength grid covering all cameras with 0.1 Ang spacing by default.
        if self.wavelengthGrid is None:
            waveMin = self.instrument.cameraWavelengthRanges[0][0]
            waveMax = self.instrument.cameraWavelengthRanges[-1][-1]
            self.setWavelengthGrid(waveMin,waveMax,0.1)

        # Convert the source to a SpectralFluxDensity if necessary, setting the flux to zero
        # outside the input source spectrum's range.
        if not isinstance(sourceSpectrum,specsim.spectrum.SpectralFluxDensity):
            sourceSpectrum = specsim.spectrum.SpectralFluxDensity(
                sourceSpectrum[0],sourceSpectrum[1],extrapolatedValue=0.)

        # Resample the source spectrum to our simulation grid, if necessary.
        self.sourceFlux = sourceSpectrum.values
        if not np.array_equal(self.wavelengthGrid,sourceSpectrum.wavelength):
            self.sourceFlux = sourceSpectrum.getResampledValues(self.wavelengthGrid)

        # Loop over cameras.
        sourcePhotonsSmooth = { }
        self.observedFlux = np.zeros_like(self.wavelengthGrid)
        throughputTotal = np.zeros_like(self.wavelengthGrid)
        for camera in self.cameras:

            # Calculate the calibration from source flux to mean number of detected photons
            # before resolution smearing in this camera's CCD.
            camera.sourceCalib = (expTime*camera.photonRatePerBin*
                self.fiberAcceptanceFraction[sourceType]*exp10(-self.extinction*airmass/2.5))

            # Apply resolution smoothing to the detected source photons.
            camera.sourcePhotonsSmooth = camera.sparseKernel.dot(
                self.sourceFlux*camera.sourceCalib)

            # Truncate any resolution leakage beyond this camera's wavelength limits.
            camera.sourcePhotonsSmooth[~camera.coverage] = 0.

            # Calculate the variance in the number of detected electrons
            # for this camera.
            camera.nElecVariance = (
                camera.sourcePhotonsSmooth + camera.skyPhotonRateSmooth*expTime +
                (camera.readnoisePerBin*nread)**2 + camera.darkCurrentPerBin*expTime)

            # Estimate this camera's contribution to the coadded observed source flux.
            self.observedFlux += camera.throughput*camera.sparseKernel.dot(self.sourceFlux)
            throughputTotal += camera.throughput

        # Approximate the observed source flux spectrum as the throughput-weighted sum of
        # the flux smoothed by each camera's resolution.
        thruMask = throughputTotal > 0
        self.observedFlux[thruMask] /= throughputTotal[thruMask]

        # Prepare the downsampled grid.
        nbins = self.wavelengthGrid.size
        try:
            ndown = nbins//downsampling
            assert ndown > 0
            # Truncate at the end of the spectrum in case the downsampling does not evenly divide
            # the high-resolution wavelength spectrum.
            last = ndown*downsampling
            downShape = (ndown,downsampling)
        except (TypeError,AssertionError):
            raise RuntimeError('simulate.Quick: invalid option downsampling = %r.' % downsampling)

        # Initialize the results record array. The str() wrappers below are required since we
        # are importing unicode_literals from __future__ but numpy does not accept unicode
        # record names.
        nbands = len(self.cameras)
        results = np.recarray((ndown,),dtype=[
            (str('wave'),float),
            (str('srcflux'),float),
            (str('obsflux'),float),
            (str('ivar'),float),
            #(str('ivarnew'),float),
            (str('snrtot'),float),
            (str('nobj'),float,(nbands,)),
            (str('nsky'),float,(nbands,)),
            (str('rdnoise'),float,(nbands,)),
            (str('dknoise'),float,(nbands,)),
            (str('snr'),float,(nbands,)),
            (str('camflux'),float,(nbands,)),
            (str('camivar'),float,(nbands,)),            
            ])

        # Fill the results arrays from our high-resolution arrays. Wavelengths are tabulated at
        # bin centers, so the first downsampled wavelength is offset by 0.5*(downsampling-1)*dwave
        # from the first high-resolution wavelength.
        dwave = (self.wavelengthGrid[-1]-self.wavelengthGrid[0])/(self.wavelengthGrid.size-1)
        results.wave = self.wavelengthGrid[:last:downsampling] + 0.5*(downsampling-1)*dwave
        results.srcflux = np.mean(self.sourceFlux[:last].reshape(downShape),axis=1)
        results.obsflux = np.mean(self.observedFlux[:last].reshape(downShape),axis=1)
        for j,camera in enumerate(self.cameras):
            # Add the source and sky photons contributing to each downsampled wavelength bin.
            (results.nobj)[:,j] = np.sum(camera.sourcePhotonsSmooth[:last].reshape(downShape),axis=1)
            # Scale the sky photon rate by the exposure time.
            (results.nsky)[:,j] = np.sum(camera.skyPhotonRateSmooth[:last].reshape(downShape),axis=1)*expTime
            # Calculate readnoise squared, scaled by the optional nread parameter (nominally 1).
            rdnoiseSq = np.sum(camera.readnoisePerBin[:last].reshape(downShape)**2,axis=1)*nread
            # Calculate the dark current shot noise variance.
            dknoiseSq = np.sum(camera.darkCurrentPerBin[:last].reshape(downShape),axis=1)*expTime
            # Save the noise contributions to the results.
            (results.rdnoise)[:,j] = np.sqrt(rdnoiseSq)
            (results.dknoise)[:,j] = np.sqrt(dknoiseSq)
            # Calculate the total variance in number of detected electrons of this downsampled bin.
            variance = (results.nobj)[:,j] + (results.nsky)[:,j] + rdnoiseSq + dknoiseSq
            # Calculate the corresponding signal-to-noise ratios. Bins with no signal will have SNR=0.
            signalMask = (results.nobj)[:,j] > 0
            (results.snr)[:,j] = np.zeros((ndown,))
            (results.snr)[signalMask,j] = (results.nobj)[signalMask,j]/np.sqrt(variance[signalMask])
            # Compute calib in downsampled wave grid, it's a sum because
            # nphot is a sum over orginal wave bins.
            # The effective calibration of convolved spectra is different from the true one
            # because resolution and transmission don't commute
            smooth_camera_calib=camera.sparseKernel.dot(camera.sourceCalib)
            calib_downsampled = np.sum(smooth_camera_calib[:last].reshape(downShape),axis=1)
            # Add inverse variance for camera
            vcMask=(variance>0)&(calib_downsampled>0)
            (results.camivar)[vcMask,j] = calib_downsampled[vcMask]**2/variance[vcMask]
            # Add flux in camera (not the same for all cameras because of change of resolution)
            (results.camflux)[vcMask,j] = (results.nobj)[vcMask,j]/calib_downsampled[vcMask]
            
        # Calculate the total SNR, combining the individual camera SNRs in quadrature.
        results.snrtot = np.sqrt(np.sum(results.snr**2,axis=1))
        # Calculate the corresponding inverse variance per bin. Bins with no observed flux will have IVAR=0.
        fluxMask = results.obsflux > 0
        results.ivar = np.zeros((ndown,))
        results.ivar[fluxMask] = (results[fluxMask].snrtot/results[fluxMask].obsflux)**2

        '''
        # Loop over downsampled bins to calculate flux inverse variances.
        results.ivarnew = np.zeros((ndown,))
        for alpha in range(ndown):
            # Initialize the weight vector for flux interpolation parameter alpha.
            wgt = np.zeros((nbins,))
            wgt[alpha*downsampling:(alpha+1)*downsampling] = 1.
            # Loop over cameras.
            for camera in self.cameras:
                # Calculate this camera's photons-per-unit-flux response to this parameter.
                Kprime = camera.sparseKernel.dot(camera.sourceCalib*wgt)
                # Calculate this camera's contribution to the corresponding diagonal
                # flux inverse variances.
                nIVar = np.zeros((nbins,))
                nIVar[camera.coverage] = 1./camera.nElecVariance[camera.coverage]
                fIVar = Kprime**2*(nIVar + 0.5*nIVar**2)
                results.ivarnew[alpha] += np.sum(fIVar[:last])
        np.savetxt('ivar.dat',np.vstack([results.ivar,results.ivarnew]).T)
        '''

        # Remember the parameters used for this simulation.
        self.airmass = airmass
        self.sourceType = sourceType
        self.expTime = expTime

        # Return the downsampled vectors
        return results
Ejemplo n.º 28
0
# Parampreet Singh - 22/06/20
# brief exploration SciPy package

import matplotlib.pyplot as plt
from scipy import interpolate as intpol
from scipy import linalg
from scipy.fftpack import fft, ifft
from scipy import integrate
from scipy import special
import numpy as np

a = special.exp10(3)  # 10 ** 3
print(a)

a = special.sindg(90)  # sin value in degress
print(a)

# integration
# integrate.quad(expression, lower limit, upper limit)
a = integrate.quad(lambda x: x**2, 0, 1)
# quad is a single varibale
# dblquad is two variables
print(a)

# integrate.quad(expression, lower limit, upper limit, lower(2nd), upper(2nd))
a = integrate.dblquad(lambda x, y: x**2 + y**2, 0, 1, 0, 1)
print(a)

# Fourier transformation
x = np.array([1, 2, 3, 4])
y = ifft(x)  # inverse
Ejemplo n.º 29
0
import scipy as sp
from scipy import special

func1 = special.kelvin(15)
print(func1)

#2 * ^elog(10)
func2 = special.xlogy(2, 10)
print(func2)

#exo10(x) = 10**(x)
func3 = special.exp10(0)
print(func3)

#sin(30)
func4 = special.sindg(90)
print(func4)