Ejemplo n.º 1
0
 def test_igammacinv_inverse_large_a(self, dtype, rtol):
   seed_stream = test_util.test_seed_stream()
   a = tf.random.uniform(
       [int(1e4)], 100., 10000., dtype=dtype, seed=seed_stream())
   p = tf.random.uniform([int(1e4)], 0., 1., dtype=dtype, seed=seed_stream())
   igammacinv, a, p = self.evaluate([tfp.math.igammacinv(a, p), a, p])
   self.assertAllClose(scipy_special.gammainccinv(a, p), igammacinv, rtol=rtol)
    def percentile(self, p):
        lambda_ = self.lambda_
        sigma_ = exp(self.ln_sigma_)

        if lambda_ > 0:
            return exp(sigma_ * log(gammainccinv(1 / lambda_ ** 2, p) * lambda_ ** 2) / lambda_) * exp(self.mu_)
        return exp(sigma_ * log(gammaincinv(1 / lambda_ ** 2, p) * lambda_ ** 2) / lambda_) * exp(self.mu_)
def gs_val_meso(gs, t, ca, k1_interp, k2_interp, cp_interp, psi_lcrit_interp,
                psi_x, VPDinterp, psi_63, w_exp, Kmax, psi_sat, gamma, b, d_r,
                z_r, RAI, lai, lam):

    psi_crit = psi_lcrit_interp(psi_x)
    VPD = VPDinterp(t)
    k1 = k1_interp(t)
    k2 = k2_interp(t)
    cp = cp_interp(t)
    x = (psi_x / psi_sat)**-(1 / b)

    psi_r = 1.6 * gs * VPD / gSR_val(x, gamma, b, d_r, z_r, RAI, lai) + psi_x
    # res = root(lambda psi_l: 1.6 * gs * VPD - Kmax * (psi_63 / w_exp) *
    #                    (gammaincc(1 / w_exp, (psi_r / psi_63) ** w_exp) - gammaincc(1 / w_exp, (psi_l / psi_63) ** w_exp)),
    #      psi_r + 0.1, method='hybr')
    # psi_l = res.get('x')
    psi_l_temp = gammainccinv(
        1 / w_exp,
        -1.6 * gs * VPD * w_exp / (gammafunc(1 / w_exp) * Kmax * psi_63) +
        gammaincc(1 / w_exp, (psi_r / psi_63)**w_exp))

    psi_l = psi_63 * psi_l_temp**(1 / w_exp)

    phi = 1 - psi_l / psi_crit

    part1 = dAdgs(t, gs, ca, k1_interp, k2_interp, cp_interp, phi)
    part2 = dAdB(t, gs, ca, k1_interp, k2_interp, cp_interp, phi) *\
            dB_dgs(cp, k2, psi_l, psi_crit, psi_x, psi_r, VPD, psi_63, w_exp, Kmax, psi_sat,
             gamma, b, d_r, z_r, RAI, lai)

    B = (cp + k2) / phi

    return part1 + part2 - 1.6 * lam * VPD * np.sqrt(
        (B + ca - cp)**2 * gs**2 + 2 * (B - ca + cp) * gs * k1 + k1**2)
Ejemplo n.º 4
0
def simulate_aftershock_time(log10_c, omega, log10_tau, size=1):
    # time delay in days
    c = np.power(10, log10_c)
    tau = np.power(10, log10_tau)
    y = np.random.uniform(size=size)

    return gammainccinv(-omega, (1 - y) * gammaincc(-omega, c / tau)) * tau - c
Ejemplo n.º 5
0
 def cdfcinv(self, pvalc): 
     """ return the inverse of cdfc = 1-cdf
     useful for limits with very low probablity
     pvalc : float
         1-pval: zero corresponds to infinite flux
     """
     e,beta,mu = self.altpars()
     if e==0: return np.nan
     gcbar = lambda x : special.gammaincc(mu+1, beta+x)
     #cchat = lambda x : gcbar(x)/gcbar(0)
     cchatinv = lambda pv : special.gammainccinv( mu+1, pv*gcbar(0) )-beta
     return cchatinv(pvalc)/e
Ejemplo n.º 6
0
 def percentile(self, p):
     lambda_ = self.lambda_
     # sigma_ = exp(self.ln_sigma_)  # 削除
     if lambda_ > 0:
         # 変更前↓
         # return exp(sigma_ * log(gammainccinv(1 / lambda_ ** 2, p) * lambda_ ** 2) / lambda_) * exp(self.mu_)
         # 変更後↓
         return exp(lambda_ * log(gammainccinv(1 / lambda_ ** 2, p) * lambda_ ** 2) / lambda_) * exp(self.mu_)
     # 変更前↓
     # return exp(sigma_ * log(gammaincinv(1 / lambda_ ** 2, p) * lambda_ ** 2) / lambda_) * exp(self.mu_)
     # 変更後↓
     return exp(lambda_ * log(gammaincinv(1 / lambda_ ** 2, p) * lambda_ ** 2) / lambda_) * exp(self.mu_)
Ejemplo n.º 7
0
    def test_igamci(self):
        a_list = np.arange(0.01, 10, 0.05)
        q_list = np.arange(0, 10, 0.1)
        test_params = cartesian([a_list, q_list]).astype(np.float64)

        python_results = np.zeros(test_params.shape[0])
        for ind in range(test_params.shape[0]):
            python_results[ind] = gammainccinv(test_params[ind, 0],
                                               test_params[ind, 1])

        opencl_results = igamci().evaluate(
            {
                'a': test_params[:, 0],
                'q': test_params[:, 1]
            }, test_params.shape[0])

        assert_allclose(opencl_results, python_results, atol=1e-7, rtol=1e-7)
Ejemplo n.º 8
0
def get_ivic_snr_thr(npulses, pfa_thr=1e-3):
    """
    Get the threshold for steps 3 and 6 of ivic

    Parameters
    ----------
    npulses : 1D array
        array with the number of pulses in a ray
    pfa_thr : float
        the desired probability of false alarm

    Returns
    -------
    snr_thr : 1D array
        The snr threshold corresponding to each number of pulses according to
        the desired probability of false alarm


    """
    return gammainccinv(npulses, pfa_thr) / npulses
def gs_val_profit(gs, t, ca, k1_interp, k2_interp, cp_interp, trans_max_interp,
                  k_max_interp, k_crit_interp, psi_x, VPDinterp, psi_63, w_exp,
                  Kmax, psi_sat, gamma, b, d_r, z_r, RAI, lai):

    trans_max = trans_max_interp(psi_x)
    k_max = k_max_interp(psi_x)
    k_crit = k_crit_interp(psi_x)
    VPD = VPDinterp(t)
    k1 = k1_interp(t)
    k2 = k2_interp(t)
    cp = cp_interp(t)
    a = 1.6
    x = (psi_x / psi_sat)**-(1 / b)

    psi_r = a * gs * VPD / gSR_val(x, gamma, b, d_r, z_r, RAI, lai) + psi_x

    psi_l_temp = gammainccinv(
        1 / w_exp,
        -1.6 * gs * VPD * w_exp / (gammafunc(1 / w_exp) * Kmax * psi_63) +
        gammaincc(1 / w_exp, (psi_r / psi_63)**w_exp))

    psi_l = psi_63 * psi_l_temp**(1 / w_exp)
    grl_psil = grl_val(psi_l, psi_63, w_exp, Kmax)
    grl_psir = grl_val(psi_r, psi_63, w_exp, Kmax)
    gSR = gSR_val(x, gamma, b, d_r, z_r, RAI, lai)
    dEdpsil = grl_psil * gSR / (grl_psir + gSR)
    gs_max = trans_max / a / VPD
    Amax = A_here(gs_max, ca, k1, k2, cp)

    d2Edpsil2 = dEdpsil * (-(w_exp / psi_63) *
                           (psi_l / psi_63)**(w_exp - 1) + grl_psir *
                           (w_exp / psi_63) *
                           (psi_r / psi_63)**(w_exp - 1) * grl_psil /
                           (grl_psir + gSR)**2)

    part1 = dAdgs(t, gs, ca, k1_interp, k2_interp, cp_interp,
                  1) * dEdpsil / (a * VPD)
    part2 = - Amax * d2Edpsil2 / (k_max - k_crit) *\
            np.sqrt((k2 + ca) ** 2 * gs ** 2 + 2 * (k2 - ca + 2 * cp) * gs * k1 + k1 ** 2)
    return part2 - part1
Ejemplo n.º 10
0
 def _ppf(self, q, a):
     return 1.0 / special.gammainccinv(a, q)
Ejemplo n.º 11
0
 def _upper(self, a):
     return 1.0 / special.gammainccinv(a, 1 - 1e-16)
Ejemplo n.º 12
0
 def quantile(self, p):
     # TODO: Check if you need to subtract 1 from the result
     # TODO: Check if args are in the right order
     return gammainccinv(p, self.lamb)
Ejemplo n.º 13
0
def get_ivic_flat_reg_var_max(npulses, flat_reg_wlen, n=40., prob_thr=0.01):
    """
    Get the threshold for maximum local variance of noise [dB]

    Parameters
    ----------
    npulses : 1D array
        array with the number of pulses in a ray
    flat_reg_wlen : int
        the length of the flat region window in bins
    n : float
        the mean noise power
    prob_thr : float
        Probably of falsely detecting noise-only flat section as contaminated
        with signal

    Returns
    -------
    var_thr : 1D array
        The thresholds corresponding to each number of pulses

    """
    y = np.arange(0.0001, 1e4, 0.01)

    log_e = np.log10(np.e)
    log_log = np.log10(np.log(10.))

    wconst1 = flat_reg_wlen - 1
    wconst2 = flat_reg_wlen - 2 + 1 / flat_reg_wlen
    wconst3 = flat_reg_wlen * flat_reg_wlen - 3 * flat_reg_wlen + 5 - 3 / flat_reg_wlen
    wconst4 = ((-2 * flat_reg_wlen * flat_reg_wlen * flat_reg_wlen +
                12 * flat_reg_wlen * flat_reg_wlen - 22 * flat_reg_wlen + 12) /
               flat_reg_wlen)
    wconst5 = 4 * (2 - flat_reg_wlen - 1 / flat_reg_wlen)
    wconst6 = ((flat_reg_wlen - 1) * (flat_reg_wlen - 2) *
               (flat_reg_wlen - 3) / flat_reg_wlen)

    var_thr = np.ma.masked_all(len(npulses))
    for i, npuls in enumerate(npulses):
        pdb_part1 = np.power(
            10.,
            np.log10(npuls / n) * npuls + log_log - gammaln(npuls) * log_e)
        pdb = np.empty(4)
        for j in range(pdb.size):
            k = j + 1

            # find first 0 crossing
            f_y = _func_flat_reg(y, k, npuls, n)
            ind = np.where(f_y != 0.)[0]
            cons_list = np.split(ind, np.where(np.diff(ind) != 1)[0] + 1)
            ind = cons_list[0][-1]

            # solve integral
            pdb[j] = pdb_part1 * integrate.quad(
                _func_flat_reg, 0., y[ind], args=(k, npuls, n))[0]

        pdb_1_2 = pdb[0] * pdb[0]

        vardb_1 = wconst1 * (pdb[1] - pdb_1_2)
        vardb_2 = (pdb[3] * wconst2 + pdb[1] * pdb[1] * wconst3 +
                   pdb[1] * pdb_1_2 * wconst4 + pdb[0] * pdb[2] * wconst5 +
                   wconst6 * pdb_1_2 * pdb_1_2)

        vardb_1_2 = vardb_1 * vardb_1

        alpha = vardb_1_2 / (vardb_2 - vardb_1_2)
        theta = (vardb_2 - vardb_1_2) / vardb_1

        var_thr[i] = gammainccinv(alpha, prob_thr) * theta

    return var_thr
Ejemplo n.º 14
0
def _inv_nchi_cdf(N, K, alpha):
    """Inverse CDF for the noncentral chi distribution
    See [1]_ p.3 section 2.3"""
    return gammainccinv(N * K, 1 - alpha) / K
Ejemplo n.º 15
0
 def _ppf(self, q, a):
     fac = special.gammainccinv(a,1-abs(2*q-1))
     return np.where(q>0.5, fac, -fac)
Ejemplo n.º 16
0
 def _upper(self, a):
     return special.gammainccinv(a, 2e-15)
Ejemplo n.º 17
0
 def _munp(self, n, zm, a, b):
     k = (a+1)/b
     z0 = zm/sc.gammainccinv(k, 0.5)**(1/b)
     return z0**n*np.exp(sc.gammaln((a+n+1)/b) - sc.gammaln(k))
Ejemplo n.º 18
0
def test_gammaincc_roundtrip():
    a = np.logspace(-5, 10, 100)
    x = np.logspace(-5, 10, 100)

    y = sc.gammainccinv(a, sc.gammaincc(a, x))
    assert_allclose(x, y, rtol=1e-14)
Ejemplo n.º 19
0
def main(top_block_cls=ROC_enDet, options=None):

    from distutils.version import StrictVersion
    if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"):
        style = gr.prefs().get_string('qtgui', 'style', 'raster')
        Qt.QApplication.setGraphicsSystem(style)
    qapp = Qt.QApplication(sys.argv)

    tb = top_block_cls()
    tb.start()
    tb.show()

    # By default the ROC_energy block is called in the calibration mode which estimates the noise floor
    #    tb.set_center_freq(tb.get_center_freq()+4*tb.get_samp_rate())
    #    print(tb.get_center_freq())
    sleep(3)  # take 5 seconds of samples in the calibration mode

    # load the estimated noise value
    estN = scipy.fromfile(open(
        "C:\Users\usuario\Documents\gnuRadio\Misc\SpectrumSensing\P_absSq_exp.dat"
    ),
                          dtype=scipy.float32)
    estN = np.mean(estN[np.abs(estN) >= 1e-15])
    yy = scipy.fromfile(open(
        "C:\Users\usuario\Documents\gnuRadio\Misc\SpectrumSensing\P_var_reim_exp.dat"
    ),
                        dtype=scipy.float32)
    yy = np.mean(yy[np.abs(yy) >= 1e-15])
    zz = scipy.fromfile(open(
        "C:\Users\usuario\Documents\gnuRadio\Misc\SpectrumSensing\P_var_exp.dat"
    ),
                        dtype=scipy.float32)
    zz = np.mean(zz[np.abs(zz) >= 1e-15])

    print('Estimated noise floor in dB: ', estN, yy, zz)

    #    tb.set_center_freq(tb.get_center_freq()-4*tb.get_samp_rate())
    print('the center frequency is:', tb.get_center_freq())

    # Reconfigure flow-graph
    #    tb.lock()
    tb.stop()
    tb.wait()

    tb.disconnect((tb.ROC_energy_block, 0), (tb.blocks_file_sink_3, 0))
    tb.disconnect((tb.ROC_energy_block, 1), (tb.blocks_file_sink_4, 0))
    tb.disconnect((tb.ROC_energy_block, 2), (tb.blocks_file_sink_5, 0))
    tb.disconnect((tb.null_source_0, 0), (tb.blocks_file_sink_0, 0))
    tb.disconnect((tb.null_source_0, 0), (tb.blocks_file_sink_1, 0))
    tb.disconnect((tb.null_source_0, 0), (tb.blocks_file_sink_2, 0))

    # Connect the other sink blocks and restart
    tb.connect((tb.ROC_energy_block, 0), (tb.blocks_file_sink_0, 0))
    tb.connect((tb.ROC_energy_block, 1), (tb.blocks_file_sink_1, 0))
    tb.connect((tb.ROC_energy_block, 2), (tb.blocks_file_sink_2, 0))
    tb.connect((tb.null_source_0, 0), (tb.blocks_file_sink_3, 0))
    tb.connect((tb.null_source_0, 0), (tb.blocks_file_sink_4, 0))
    tb.connect((tb.null_source_0, 0), (tb.blocks_file_sink_5, 0))
    #    tb.unlock()

    try:
        tb.start()
    except ValueError:
        print('Something went wrong')

    tb.set_fun('meas')  # change to the 'measurement' mode
    # sleep(0.1)

    i = 0
    for targPf in np.logspace(
            -6, 0, 21
    ):  # data with the first value of threshold is invalidated due to the noise floor
        new_thr = (10**(estN / 10)) * scpsp.gammainccinv(tb.get_N(), targPf)
        tb.set_thr(new_thr)  # change threshold
        sleep(0.1)  # run the flowgraph (with current values) for 3 seconds
        print(i, new_thr)
        i = i + 1

    tb.stop()
    tb.wait()

    def quitting():
        tb.stop()
        tb.wait()

    qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting)
    qapp.exec_()
Ejemplo n.º 20
0
    def __init__(self):
        gr.top_block.__init__(self, "ROC curves energy detector")
        Qt.QWidget.__init__(self)
        self.setWindowTitle("ROC curves energy detector")
        qtgui.util.check_set_qss()
        try:
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
        except:
            pass
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        self.settings = Qt.QSettings("GNU Radio", "ROC_enDet")
        self.restoreGeometry(self.settings.value("geometry").toByteArray())

        ####################################################################################################
        # Variables
        ####################################################################################################
        self.S = S = -75.0  # signal power in dBW
        self.w = w = -77.0  # noise power in dBW
        self.theta = theta = 0.0  # variable to simulate the presence or absence of signal
        self.sigma_s = sigma_s = 10**(S / 20.0) / np.sqrt(
            2
        )  # signal deviation (amplitude) of real and imaginary part in normalized Volts (referred to a 1 Ohm resistance)
        self.sigma_n = sigma_n = 10**(
            w / 20.0
        )  # the sqrt(2) is an artifact of the channel that adds 3dB to the SNR (maybe the Linux version doesn't have this problem)
        self.samp_rate = samp_rate = 320000
        self.N = N = 32  # number of samples
        # page size greatly limits this value, min page size seems to be the default 4096, then the buffer is formed in chunks of size [pagesize/N,N]
        self.targPf = targPf = 1e-7  # initial value, modified later within a loop to create the ROC curve
        self.thr = thr = sigma_n**2 * scpsp.gammainccinv(
            N,
            targPf)  # threshold value for a target probability of false alarm

        ####################################################################################################
        # Blocks
        ####################################################################################################
        self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
            1024,  #size
            samp_rate,  #samp_rate
            "",  #name
            1  #number of inputs
        )
        self.qtgui_time_sink_x_0.set_update_time(0.10)
        self.qtgui_time_sink_x_0.set_y_axis(-1, 1)

        self.qtgui_time_sink_x_0.set_y_label('Amplitude', "")

        self.qtgui_time_sink_x_0.enable_tags(-1, True)
        self.qtgui_time_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_FREE,
                                                  qtgui.TRIG_SLOPE_POS, 0.0, 0,
                                                  0, "")
        self.qtgui_time_sink_x_0.enable_autoscale(False)
        self.qtgui_time_sink_x_0.enable_grid(False)
        self.qtgui_time_sink_x_0.enable_axis_labels(True)
        self.qtgui_time_sink_x_0.enable_control_panel(False)

        if not True:
            self.qtgui_time_sink_x_0.disable_legend()

        labels = ['', '', '', '', '', '', '', '', '', '']
        widths = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        colors = [
            "blue", "red", "green", "black", "cyan", "magenta", "yellow",
            "dark red", "dark green", "blue"
        ]
        styles = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        markers = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

        for i in xrange(1):
            if len(labels[i]) == 0:
                self.qtgui_time_sink_x_0.set_line_label(
                    i, "Data {0}".format(i))
            else:
                self.qtgui_time_sink_x_0.set_line_label(i, labels[i])
            self.qtgui_time_sink_x_0.set_line_width(i, widths[i])
            self.qtgui_time_sink_x_0.set_line_color(i, colors[i])
            self.qtgui_time_sink_x_0.set_line_style(i, styles[i])
            self.qtgui_time_sink_x_0.set_line_marker(i, markers[i])
            self.qtgui_time_sink_x_0.set_line_alpha(i, alphas[i])

        self._qtgui_time_sink_x_0_win = sip.wrapinstance(
            self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
        self.top_layout.addWidget(self._qtgui_time_sink_x_0_win)

        self.channels_channel_model_0 = channels.channel_model(
            noise_voltage=sigma_n,
            frequency_offset=0.0,
            epsilon=1.0,
            taps=(1.0 + 1.0j, ),
            noise_seed=0,
            block_tags=False)
        self.blocks_throttle_0 = blocks.throttle(gr.sizeof_gr_complex * 1,
                                                 samp_rate, True)
        self.blocks_stream_to_vector_0 = blocks.stream_to_vector(
            gr.sizeof_gr_complex * 1, N)
        self.blocks_file_sink_0 = blocks.file_sink(
            gr.sizeof_float * 1,
            'C:\\Users\\usuario\\Documents\\gnuRadio\\Misc\\SpectrumSensing\\N_det.dat',
            False)
        self.blocks_file_sink_0.set_unbuffered(True)
        self.blocks_file_sink_1 = blocks.file_sink(
            gr.sizeof_float * 1,
            'C:\\Users\\usuario\\Documents\\gnuRadio\\Misc\\SpectrumSensing\\N_inD.dat',
            False)
        self.blocks_file_sink_1.set_unbuffered(True)
        self.blocks_file_sink_2 = blocks.file_sink(
            gr.sizeof_float * 1,
            'C:\\Users\\usuario\\Documents\\gnuRadio\\Misc\\SpectrumSensing\\Thr.dat',
            False)
        self.blocks_file_sink_2.set_unbuffered(True)
        self.blocks_file_sink_3 = blocks.file_sink(
            gr.sizeof_float * 1,
            'C:\\Users\\usuario\\Documents\\gnuRadio\\Misc\\SpectrumSensing\\P_var.dat',
            False)
        self.blocks_file_sink_3.set_unbuffered(True)
        self.blocks_file_sink_4 = blocks.file_sink(
            gr.sizeof_float * 1,
            'C:\\Users\\usuario\\Documents\\gnuRadio\\Misc\\SpectrumSensing\\P_var_reim.dat',
            False)
        self.blocks_file_sink_4.set_unbuffered(True)
        self.blocks_file_sink_5 = blocks.file_sink(
            gr.sizeof_float * 1,
            'C:\\Users\\usuario\\Documents\\gnuRadio\\Misc\\SpectrumSensing\\P_absSq.dat',
            False)
        self.blocks_file_sink_5.set_unbuffered(True)

        self.analog_noise_source_x_0 = analog.noise_source_c(
            analog.GR_GAUSSIAN, theta * sigma_s, 0)
        #        self.analog_sig_source_x_0 = analog.sig_source_c(samp_rate,analog.GR_COS_WAVE,1e3,theta*sigma_s, 0) # test for sinusoidal signals
        self.ROC_energy_block = ROC_energy_block.blk(N=N, thr=thr, fun='cal')

        ####################################################################################################
        # Connections
        ####################################################################################################
        self.connect((self.ROC_energy_block, 0), (self.blocks_file_sink_3, 0))
        self.connect((self.ROC_energy_block, 1), (self.blocks_file_sink_4, 0))
        self.connect((self.ROC_energy_block, 2), (self.blocks_file_sink_5, 0))

        self.connect((self.ROC_energy_block, 0), (self.qtgui_time_sink_x_0, 0))
        self.connect((self.analog_noise_source_x_0, 0),
                     (self.blocks_throttle_0, 0))
        #        self.connect((self.analog_sig_source_x_0, 0), (self.blocks_throttle_0, 0))   # change to signal source
        self.connect((self.blocks_stream_to_vector_0, 0),
                     (self.ROC_energy_block, 0))
        self.connect((self.blocks_throttle_0, 0),
                     (self.channels_channel_model_0, 0))
        self.connect((self.channels_channel_model_0, 0),
                     (self.blocks_stream_to_vector_0, 0))
Ejemplo n.º 21
0
def main(top_block_cls=ROC_enDet, options=None):

    from distutils.version import StrictVersion
    if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"):
        style = gr.prefs().get_string('qtgui', 'style', 'raster')
        Qt.QApplication.setGraphicsSystem(style)
    qapp = Qt.QApplication(sys.argv)

    tb = top_block_cls()
    tb.start()
    tb.show()

    # By default the ROC_energy block is called in the calibration mode which estimates the noise floor
    sleep(5)  # take 5 seconds of samples in the calibration mode

    # load the estimated noise value
    estN = scipy.fromfile(open(
        "C:\Users\usuario\Documents\gnuRadio\Misc\SpectrumSensing\P_absSq.dat"
    ),
                          dtype=scipy.float32)
    estN = np.mean(estN[np.abs(estN) >= 1e-15])
    yy = scipy.fromfile(open(
        "C:\Users\usuario\Documents\gnuRadio\Misc\SpectrumSensing\P_var_reim.dat"
    ),
                        dtype=scipy.float32)
    yy = np.mean(yy[np.abs(yy) >= 1e-15])
    zz = scipy.fromfile(open(
        "C:\Users\usuario\Documents\gnuRadio\Misc\SpectrumSensing\P_var.dat"),
                        dtype=scipy.float32)
    zz = np.mean(zz[np.abs(zz) >= 1e-15])

    print('Estimated noise floor in dB: ', estN, yy, zz)

    # Reconfigure flow-graph
    # tb.lock()
    tb.stop()
    tb.wait()
    tb.disconnect((tb.ROC_energy_block, 0), (tb.blocks_file_sink_3, 0))
    tb.disconnect((tb.ROC_energy_block, 1), (tb.blocks_file_sink_4, 0))
    tb.disconnect((tb.ROC_energy_block, 2), (tb.blocks_file_sink_5, 0))
    # Connect the other sink blocks and restart
    tb.connect((tb.ROC_energy_block, 0), (tb.blocks_file_sink_0, 0))
    tb.connect((tb.ROC_energy_block, 1), (tb.blocks_file_sink_1, 0))
    tb.connect((tb.ROC_energy_block, 2), (tb.blocks_file_sink_2, 0))
    #tb.unlock()
    tb.start()

    tb.set_theta(1.0)  # enable signal 'transmission'
    tb.set_fun('meas')  # change to the 'measurement' mode
    # sleep(0.1)

    for targPf in np.logspace(
            -6, 0, 21
    ):  # data with the first value of threshold is invalidated due to the noise floor
        #new_thr = (10**(estN/10))*scpsp.gammainccinv(tb.get_N(), targPf)
        new_thr = tb.get_sigma_n()**2 * scpsp.gammainccinv(
            tb.get_N(), targPf)  #use this for simulation accuracy
        tb.set_thr(new_thr)  # change threshold
        sleep(1)  # run the flowgraph (with current values) for 3 seconds

    tb.stop()
    tb.wait()

    def quitting():
        tb.stop()
        tb.wait()

    qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting)
    qapp.exec_()
Ejemplo n.º 22
0
    def radius(self, T, prec, deriv=[]):
        r"""
        Calculate the radius `R` to compute the value of the theta function
        to within `2^{-P + 1}` bits of precision where `P` is the 
        real / complex precision given by the input matrix. Used primarily
        by ``RiemannTheta.integer_points()``.

        `R` is the radius of [CRTF] Theorems 2, 4, and 6.

        Input
        -----
        
        - ``T`` -- the Cholesky decomposition of the imaginary part of the 
          Riemann matrix `\Omega`

        - ``prec`` -- the desired precision of the computation
        
        - ``deriv`` -- (list) (default=``[]``) the derivative, if given. 
          Radius increases as order of derivative increases.            
        """
        Pi = np.pi
        I  = 1.0j
        g  = np.float64(T.shape[0])

        # compute the length of the shortest lattice vector
        #U  = qflll(T)
	A = lattice_reduce(T)
        r  = min(la.norm(A[:,i]) for i in range(int(g)))
        normTinv = la.norm(la.inv(T))

        # solve for the radius using:
        #   * Theorem 3 of [CRTF] (no derivative)
        #   * Theorem 5 of [CRTF] (first order derivative)
        #   * Theorem 7 of [CRTF] (second order derivative)
        if len(deriv) == 0:
            eps  = prec
            lhs  = eps * (2.0/g) * (r/2.0)**g * gamma(g/2.0)
            ins  = gammainccinv(g/2.0,lhs)
            R    = np.sqrt(ins) + r/2.0
            rad  = max( R, (np.sqrt(2*g)+r)/2.0)
        elif len(deriv) == 1:
            # solve for left-hand side
            L         = self.deriv_accuracy_radius
            normderiv = la.norm(np.array(deriv[0]))
            eps  = prec
            lhs  = (eps * (r/2.0)**g) / (np.sqrt(Pi)*g*normderiv*normTinv)

            # define right-hand-side function involving the incomplete gamma
            # function
            def rhs(ins):
                """
                Right-hand side function for computing the bounding ellipsoid
                radius given a desired maximum error bound for the first
                derivative of the Riemann theta function.
                """
                return gamma((g+1)/2)*gammaincc((g+1)/2, ins) +               \
                    np.sqrt(Pi)*normTinv*L * gamma(g/2)*gammaincc(g/2, ins) - \
                    float(lhs)

            #  define lower bound (guess) and attempt to solve for the radius
            lbnd = np.sqrt(g+2 + np.sqrt(g**2+8)) + r
            try:
                ins = fsolve(rhs, float(lbnd))[0]
            except RuntimeWarning:
                # fsolve had trouble finding the solution. We try 
                # a larger initial guess since the radius increases
                # as desired precision increases
                try:
                    ins = fsolve(rhs, float(2*lbnd))[0]
                except RuntimeWarning:
                    raise ValueError, "Could not find an accurate bound for the radius. Consider using higher precision."

            # solve for radius
            R   = np.sqrt(ins) + r/2.0
            rad = max(R,lbnd)

        elif len(deriv) == 2:
            # solve for left-hand side
            L             = self.deriv_accuracy_radius
            prodnormderiv = np.prod([la.norm(d) for d in deriv])

            eps  = prec
            lhs  = (eps*(r/2.0)**g) / (2*Pi*g*prodnormderiv*normTinv**2)

            # define right-hand-side function involving the incomplete gamma
            # function
            def rhs(ins):
                """
                Right-hand side function for computing the bounding ellipsoid
                radius given a desired maximum error bound for the second
                derivative of the Riemann theta function.
                """
                return gamma((g+2)/2)*gammaincc((g+2)/2, ins) + \
                    2*np.sqrt(Pi)*normTinv*L *                  \
                    gamma((g+1)/2)*gammaincc((g+1)/2,ins) +     \
                    Pi*normTinv**2*L**2 *                       \
                    gamma(g/2)*gammaincc(g/2,ins) - float(lhs)

            #  define lower bound (guess) and attempt to solve for the radius
            lbnd = np.sqrt(g+4 + np.sqrt(g**2+16)) + r
            try:
                ins = fsolve(rhs, float(lbnd))[0]
            except RuntimeWarning:
                # fsolve had trouble finding the solution. We try 
                # a larger initial guess since the radius increases
                # as desired precision increases
                try:
                    ins = fsolve(rhs, float(2*lbnd))[0]
                except RuntimeWarning:
                    raise ValueError, "Could not find an accurate bound for the radius. Consider using higher precision."

            # solve for radius
            R   = np.sqrt(ins) + r/2.0
            rad = max(R,lbnd)

        else:
            # can't computer higher derivatives, yet
            raise NotImplementedError("Ellipsoid radius for first and second derivatives not yet implemented.")

        return rad
def rchi2_given_prob(p, m, nu):
    a = (nu / 2.0) * np.float64(m) / (3.0 + np.float64(m))
    return gammainccinv(a, p) / a
Ejemplo n.º 24
0
 def _lower(self, a):
     return -special.gammainccinv(a, 2e-15)
Ejemplo n.º 25
0
 def _logpdf(self, z, zm, a, b):
     k = (a+1)/b
     z0 = zm/sc.gammainccinv(k, 0.5)**(1/b)
     lognorm = np.log(b) - np.log(z0) - sc.gammaln(k)
     return lognorm + sc.xlogy(a, z/z0) - (z/z0)**b
Ejemplo n.º 26
0
 def _ppf(self, q, a):
     fac = special.gammainccinv(a,1-abs(2*q-1))
     return numpy.where(q>0.5, fac, -fac)
Ejemplo n.º 27
0
 def _cdf(self, z, zm, a, b):
     k = (a+1)/b
     t = sc.gammainccinv(k, 0.5)
     return sc.gammainc(k, t*(z/zm)**b)
Ejemplo n.º 28
0
 def _calc_sigma_from_cl(self):
     self._sigma = np.sqrt(2 * gammainccinv(self.ndim/2., 1. - self.cl))
Ejemplo n.º 29
0
 def _ppf(self, q, zm, a, b):
     k = (a+1)/b
     t = sc.gammainccinv(k, 0.5)
     return zm*(sc.gammaincinv(k, q)/t)**(1/b)
Ejemplo n.º 30
0
    def test_roundtrip(self):
        a = np.logspace(-5, 10, 100)
        x = np.logspace(-5, 10, 100)

        y = sc.gammainccinv(a, sc.gammaincc(a, x))
        assert_allclose(x, y, rtol=1e-14)
Ejemplo n.º 31
0
def _inv_nchi_cdf(N, K, alpha):
    """Inverse CDF for the noncentral chi distribution
    See [1]_ p.3 section 2.3"""
    return gammainccinv(N * K, 1 - alpha) / K
Ejemplo n.º 32
0
 def _rvs(self, zm, a, b):
     sz, rs = self._size, self._random_state
     k = (a+1)/b
     t = zm**b/sc.gammainccinv(k, 0.5)
     g = stats.gamma.rvs(k, scale=t, size=sz, random_state=rs)
     return g**(1/b)
Ejemplo n.º 33
0
    def radius(self, T, prec, deriv=[]):
        r"""
        Calculate the radius `R` to compute the value of the theta function
        to within `2^{-P + 1}` bits of precision where `P` is the 
        real / complex precision given by the input matrix. Used primarily
        by ``RiemannTheta.integer_points()``.

        `R` is the radius of [CRTF] Theorems 2, 4, and 6.

        Input
        -----
        
        - ``T`` -- the Cholesky decomposition of the imaginary part of the 
          Riemann matrix `\Omega`

        - ``prec`` -- the desired precision of the computation
        
        - ``deriv`` -- (list) (default=``[]``) the derivative, if given. 
          Radius increases as order of derivative increases.            
        """
        Pi = np.pi
        I  = 1.0j
        g  = np.float64(T.shape[0])

        # compute the length of the shortest lattice vector
        #U  = qflll(T)
	A = lattice_reduce(T)
        r  = min(la.norm(A[:,i]) for i in range(int(g)))
        normTinv = la.norm(la.inv(T))

        # solve for the radius using:
        #   * Theorem 3 of [CRTF] (no derivative)
        #   * Theorem 5 of [CRTF] (first order derivative)
        #   * Theorem 7 of [CRTF] (second order derivative
        if len(deriv) == 0:
            eps  = prec
            lhs  = eps * (2.0/g) * (r/2.0)**g * gamma(g/2.0)
            ins  = gammainccinv(g/2.0,lhs)
            R    = np.sqrt(ins) + r/2.0
            rad  = max( R, (np.sqrt(2*g)+r)/2.0)
        elif len(deriv) == 1:
            # solve for left-hand side
            L         = self.deriv_accuracy_radius
            normderiv = la.norm(np.array(deriv[0]))
            eps  = prec
            lhs  = (eps * (r/2.0)**g) / (np.sqrt(Pi)*g*normderiv*normTinv)

            # define right-hand-side function involving the incomplete gamma
            # function
            def rhs(ins):
                """
                Right-hand side function for computing the bounding ellipsoid
                radius given a desired maximum error bound for the first
                derivative of the Riemann theta function.
                """
                return gamma((g+1)/2)*gammaincc((g+1)/2, ins) +               \
                    np.sqrt(Pi)*normTinv*L * gamma(g/2)*gammaincc(g/2, ins) - \
                    float(lhs)

            #  define lower bound (guess) and attempt to solve for the radius
            lbnd = np.sqrt(g+2 + np.sqrt(g**2+8)) + r
            try:
                ins = fsolve(rhs, float(lbnd))[0]
            except RuntimeWarning:
                # fsolve had trouble finding the solution. We try 
                # a larger initial guess since the radius increases
                # as desired precision increases
                try:
                    ins = fsolve(rhs, float(2*lbnd))[0]
                except RuntimeWarning:
                    raise ValueError, "Could not find an accurate bound for the radius. Consider using higher precision."

            # solve for radius
            R   = np.sqrt(ins) + r/2.0
            rad = max(R,lbnd)

        elif len(deriv) == 2:
            # solve for left-hand side
            L             = self.deriv_accuracy_radius
            prodnormderiv = np.prod([la.norm(d) for d in deriv])

            eps  = prec
            lhs  = (eps*(r/2.0)**g) / (2*Pi*g*prodnormderiv*normTinv**2)

            # define right-hand-side function involving the incomplete gamma
            # function
            def rhs(ins):
                """
                Right-hand side function for computing the bounding ellipsoid
                radius given a desired maximum error bound for the second
                derivative of the Riemann theta function.
                """
                return gamma((g+2)/2)*gammaincc((g+2)/2, ins) + \
                    2*np.sqrt(Pi)*normTinv*L *                  \
                    gamma((g+1)/2)*gammaincc((g+1)/2,ins) +     \
                    Pi*normTinv**2*L**2 *                       \
                    gamma(g/2)*gammaincc(g/2,ins) - float(lhs)

            #  define lower bound (guess) and attempt to solve for the radius
            lbnd = np.sqrt(g+4 + np.sqrt(g**2+16)) + r
            try:
                ins = fsolve(rhs, float(lbnd))[0]
            except RuntimeWarning:
                # fsolve had trouble finding the solution. We try 
                # a larger initial guess since the radius increases
                # as desired precision increases
                try:
                    ins = fsolve(rhs, float(2*lbnd))[0]
                except RuntimeWarning:
                    raise ValueError, "Could not find an accurate bound for the radius. Consider using higher precision."

            # solve for radius
            R   = np.sqrt(ins) + r/2.0
            rad = max(R,lbnd)

        else:
            # can't computer higher derivatives, yet
            raise NotImplementedError("Ellipsoid radius for first and second derivatives not yet implemented.")

        return rad