
    `i,                         d Z ddlZddlmZ d ZddZddZd Zdd
Z ej	        dd          Z
 ej	        dd          ZdS )a  
Some of the functions defined here were ported directly from CuSignal under
terms of the MIT license, under the following notice:

Copyright (c) 2019-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
    N)windowsc                    || j         d         }t          |          rA |t          j                            |                              | j                            }nft          |t          j                  r|j         |fk    rt          d          |}n.t          j        ||d                              | j                  }| |z  } |r"| t          j                            |           z  } | S )Nz(window must have the same length as dataF)shapecallablecupyfftfftfreqastypedtype
isinstancendarray
ValueErrorr   
get_windowlinalgnorm)x	normalizewindownws        x/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupyx/signal/_radartools/_radartools.py_pulse_preprocessr      s    GBKF 	Etx''**11!'::;;AA-- 	E|t## !KLLLAA"61e44;;AGDDAE $  ###H    Fc                 |   | j         \  }}t          j        | |          }||}t          |||          }t          j                            | |          }	t          j                            ||          }
t          j                            |	|
                                z  |          }|j        dk    r|j        }|S )a  
    Pulse Compression is used to increase the range resolution and SNR
    by performing matched filtering of the transmitted pulse (template)
    with the received signal (x)

    Parameters
    ----------
    x : ndarray
        Received signal, assume 2D array with [num_pulses, sample_per_pulse]

    template : ndarray
        Transmitted signal, assume 1D array

    normalize : bool
        Normalize transmitted signal

    window : array_like, callable, string, float, or tuple, optional
        Specifies the window applied to the signal in the Fourier
        domain.

    nfft : int, size of FFT for pulse compression. Default is number of
        samples per pulse

    Returns
    -------
    compressedIQ : ndarray
        Pulse compressed output
    Nc)	r   r   result_typer   r	   ifftconjkindreal)r   templater   r   nfft
num_pulsessamples_per_pulser   tfft_xfft_touts               r   pulse_compressionr*   1   s    : %&G!J!Q))E| (Iv66AHLLD!!EHLLD!!E
(--

,d
3
3CzShJr   c                     | j         \  }}||}t          | j        d|          }t          j                            ||          j        S )a  
    Pulse doppler processing yields a range/doppler data matrix that represents
    moving target data that's separated from clutter. An estimation of the
    doppler shift can also be obtained from pulse doppler processing. FFT taken
    across slow-time (pulse) dimension.

    Parameters
    ----------
    x : ndarray
        Received signal, assume 2D array with [num_pulses, sample_per_pulse]

    window : array_like, callable, string, float, or tuple, optional
        Specifies the window applied to the signal in the Fourier
        domain.

    nfft : int, size of FFT for pulse compression. Default is number of
        samples per pulse

    Returns
    -------
    pd_dataMatrix : ndarray
        Pulse-doppler output (range/doppler matrix)
    NF)r   r   Tr   r	   )r   r   r#   r$   r%   xTs         r   pulse_dopplerr.   ]   sG    0 %&G!J!|	13v	.	.B8<<D!!##r   c                     || d|z  z  dz
  z  S )aA  
    Computes the value of alpha corresponding to a given probability
    of false alarm and number of reference cells N.

    Parameters
    ----------
    pfa : float
        Probability of false alarm.

    N : int
        Number of reference cells.

    Returns
    -------
    alpha : float
        Alpha value.
    g          )pfaNs     r   
cfar_alphar4   ~   s    $ q!A%&&r   MbP?c                    | j         }t          |          dk    rt          d          t          j        |t          j                  }t          |          dk    rt          |           d|z  d|z  z   k    rt          d          t          j        | dt          j                  }d|z  }t          ||          }d}	t          |           d|z  z
  d|z  z
  |	d         z   dz
  |	d         z  f}
t          |
|	| ||t          |           |t          j        |          ||f           nt          |          dk    rt          |          dk    st          |          dk    rt          d	          |\  }}|\  }}|d         d|z  z
  d|z  z
  dk    rt          d
          |d         d|z  z
  d|z  z
  dk    rt          d          t          j        | dt          j                  }t          j        |dt          j                  }d|z  d|z  d|z  z   dz   z  }|dd|z  dz   z  |z  z  }t          ||          }d}	|d         d||z   z  z
  |	d         z   dz
  |	d         z  }|d         d||z   z  z
  |	d         z   dz
  |	d         z  }||f}
t          |
|	| |||d         |d         |t          j        |          ||||f           || |z
  dk    fS )a  
    Computes the cell-averaged constant false alarm rate (CA CFAR) detector
    threshold and returns for a given array.
    Parameters
    ----------
    array : ndarray
        Array containing data to be processed.
    guard_cells_x : int
        One-sided guard cell count in the first dimension.
    guard_cells_y : int
        One-sided guard cell count in the second dimension.
    reference_cells_x : int
        one-sided reference cell count in the first dimension.
    reference_cells_y : int
        one-sided reference cell count in the second dimension.
    pfa : float
        Probability of false alarm.
    Returns
    -------
    threshold : ndarray
        CFAR threshold
    return : ndarray
        CFAR detections
       z.Only 1D and 2D arrays are currently supported.)r   r0   z$Array too small for given parametersr   )axisr   )    z2Guard and reference cells must be two dimensional.z5Array first dimension too small for given parameters.z6Array second dimension too small for given parameters.)   r:   )r   len	TypeErrorr   zerosfloat32r   cumsumr4   _ca_cfar_1d_kernel_ca_cfar_2d_kernel)arrayguard_cellsreference_cellsr2   r   maskintermediater3   alphatpbbpgguard_cells_xguard_cells_yreference_cells_xreference_cells_ybpg_xbpg_ys                    r   ca_cfarrP      sw   2 KE
5zzA~~HIII:e4<000D
5zzQu::[1+>>>>CDDD{5qEEE3""E

Q001{?B1v!!f% '3e\4&)%jj!T\%5H5H&1?&D 	E 	E 	E 	E 
Uq{q  C$8$8A$=$= + , , ,'2$}/>,,8a-''!.?*??1DD + , , ,8a-''!.?*??1DD + , , ,{5qEEE{<at|LLL!!Q):%:%&%6&79:&; <	Q!m#a'(+<<<3""qA!2]!BCCc!fL1vqA!2]!BCCc!fL1ven3e\4 8U1Xq$,u2E2E(-9J,&. 	/ 	/ 	/ %$,"##r   a
  
extern "C" __global__ void
_ca_cfar_2d_kernel(float * array, float * intermediate, float * mask,
                   int width, int height, int N, float alpha,
                   int guard_cells_x, int guard_cells_y,
                   int reference_cells_x, int reference_cells_y)
{
    int i_init = threadIdx.x+blockIdx.x*blockDim.x;
    int j_init = threadIdx.y+blockIdx.y*blockDim.y;
    int i, j, x, y, offset;
    int tro, tlo, blo, bro, tri, tli, bli, bri;
    float outer_area, inner_area, T;
    for (i=i_init; i<width-2*(guard_cells_x+reference_cells_x);
         i += blockDim.x*gridDim.x){
        for (j=j_init; j<height-2*(guard_cells_y+reference_cells_y);
             j += blockDim.y*gridDim.y){
            /* 'tri' is Top Right Inner (square), 'blo' is Bottom Left
             * Outer (square), etc. These are the corners at which
             * the intermediate array must be evaluated.
             */
            x = i+guard_cells_x+reference_cells_x;
            y = j+guard_cells_y+reference_cells_y;
            offset = x*height+y;
            tro = (x+guard_cells_x+reference_cells_x)*height+y+
                guard_cells_y+reference_cells_y;
            tlo = (x-guard_cells_x-reference_cells_x-1)*height+y+
                guard_cells_y+reference_cells_y;
            blo = (x-guard_cells_x-reference_cells_x-1)*height+y-
                guard_cells_y-reference_cells_y-1;
            bro = (x+guard_cells_x+reference_cells_x)*height+y-
                guard_cells_y-reference_cells_y-1;
            tri = (x+guard_cells_x)*height+y+guard_cells_y;
            tli = (x-guard_cells_x-1)*height+y+guard_cells_y;
            bli = (x-guard_cells_x-1)*height+y-guard_cells_y-1;
            bri = (x+guard_cells_x)*height+y-guard_cells_y-1;
            /* It would be nice to eliminate the triple
             * branching here, but it only occurs on the boundaries
             * of the array (i==0 or j==0). So it shouldn't hurt
             * overall performance much.
             */
            if (i>0 && j>0){
                outer_area = intermediate[tro]-intermediate[tlo]-
                    intermediate[bro]+intermediate[blo];
            } else if (i == 0 && j > 0){
                outer_area = intermediate[tro]-intermediate[bro];
            } else if (i > 0 && j == 0){
                outer_area = intermediate[tro]-intermediate[tlo];
            } else if (i == 0 && j == 0){
                outer_area = intermediate[tro];
            }
            inner_area = intermediate[tri]-intermediate[tli]-
                intermediate[bri]+intermediate[bli];
            T = outer_area-inner_area;
            T = alpha/N*T;
            mask[offset] = T;
        }
    }
}
rA   a  
extern "C" __global__ void
_ca_cfar_1d_kernel(float * array, float * intermediate, float * mask,
                   int width, int N, float alpha,
                   int guard_cells, int reference_cells)
{
    int i_init = threadIdx.x+blockIdx.x*blockDim.x;
    int i, x;
    int br, bl, sr, sl;
    float big_area, small_area, T;
    for (i=i_init; i<width-2*(guard_cells+reference_cells);
         i += blockDim.x*gridDim.x){
        x = i+guard_cells+reference_cells;
        br = x+guard_cells+reference_cells;
        bl = x-guard_cells-reference_cells-1;
        sr = x+guard_cells;
        sl = x-guard_cells-1;
        if (i>0){
            big_area = intermediate[br]-intermediate[bl];
        } else{
            big_area = intermediate[br];
        }
        small_area = intermediate[sr]-intermediate[sl];
        T = big_area-small_area;
        T = alpha/N*T;
        mask[x] = T;
    }
}
r@   )FNN)NN)r5   )__doc__r   cupyx.scipy.signalr   r   r*   r.   r4   rP   	RawKernelrA   r@   r1   r   r   <module>rT      s    2  & & & & & &  &) ) ) )X$ $ $ $B' ' '*F$ F$ F$ F$R $T^ :%t u: : z $T^ %8 9    r   