Cython with blas. NOTE: requires scipy
328651
def example8():
    """"""

    # See cython_blas.pyx for argument documentation
    mat = np.array([[[2.0, 2.0], [2.0, 2.0]], [[2.0, 2.0], [2.0, 2.0]]],
                   dtype=np.float32)
    result = np.zeros((2, 2), np.float32, order="C")

    run_func(cyth.compute_kernel_matrix,
             "L",
             "T",
             2,
             2,
             1.0,
             mat,
             0,
             2,
             1.0,
             result,
             2
             )
819158
def to_float(b:Collection[Tensor])->Collection[Tensor]:
    ""
    if is_listy(b): return [to_float(o) for o in b]
    return b.float() if b.dtype not in [torch.int64, torch.int32, torch.int16] else b
110500
def cython_enums():
    """"""
    lines = []
    for name in all_names:
        if no_prefix(name):
            lines.append('enum: ZMQ_{0} "{0}"'.format(name))
        else:
            lines.append('enum: ZMQ_{0}'.format(name))
            
    return dict(ZMQ_ENUMS='\n    '.join(lines))
996221
def cublasSspr(handle, uplo, n, alpha, x, incx, AP):
    
    
    status = _libcublas.cublasSspr_v2(handle, 
                                      _CUBLAS_FILL_MODE[uplo], n,                                       
                                      ctypes.byref(ctypes.c_float(alpha)), 
                                      int(x), incx, int(AP))                                      
    cublasCheckStatus(status)
228387
def cythonize(*args, **kwargs):
    '''
    
    '''
    global cythonize
    from Cython.Build import cythonize
    return cythonize(*args, **kwargs)
311443
def make_psf_kernel(psf, npix, cdelt, xpix, ypix, psf_scale_fn=None, normalize=False):
    

    egy = psf.energies
    x = make_pixel_distance(npix, xpix, ypix)
    x *= cdelt

    k = np.zeros((len(egy), npix, npix))
    for i in range(len(egy)):
        k[i] = psf.eval(i, x, scale_fn=psf_scale_fn)

    if normalize:
        k /= (np.sum(k, axis=0)[np.newaxis, ...] * np.radians(cdelt) ** 2)

    return k
410863
def glsfit(psr,renormalize=True):
    """"""
    
    mask = psr.deleted == 0
    res, err = psr.residuals(removemean=False)[mask], psr.toaerrs[mask]
    M = psr.designmatrix(updatebats=False,fixunits=True,fixsigns=True)[mask,:]
        
    C = numpy.diag((err * 1e-6)**2)
    
    if renormalize:
        norm = numpy.sqrt(numpy.sum(M**2,axis=0))
        M /= norm
    else:
        norm = np.ones_like(M[0,:])
    
    mtcm = numpy.dot(M.T,numpy.dot(numpy.linalg.inv(C),M))
    mtcy = numpy.dot(M.T,numpy.dot(numpy.linalg.inv(C),res))
    
    xvar = numpy.linalg.inv(mtcm)
        
    c = scipy.linalg.cho_factor(mtcm)
    xhat = scipy.linalg.cho_solve(c,mtcy)

    sol = psr.vals()
    psr.vals(sol + xhat[1:] / norm[1:])
    psr.errs(numpy.sqrt(numpy.diag(xvar)[1:]) / norm[1:])
    
    return chisq(psr)
1088259
def model1(inps, lims, logger=None):
    
    a_arr, c_ = inps
    ilim, jlim = lims

    i_bs = sympy.symbols('i_lb i_ub', integer=True)
    i = sympy.Idx('i', i_bs)

    j_bs = sympy.symbols('j_lb j_ub', integer=True)
    j = sympy.Idx('j', j_bs)

    a = sympy.IndexedBase('a')

    c = sympy.Symbol('c', real=True)

    x = sympy.IndexedBase('x')
    y = sympy.IndexedBase('y')

    eqs = [
        sympy.Eq(x[i], (a[i]/3-1)**i+c),
        sympy.Eq(y[j], a[j]-j),
    ]

    ex_code = ExampleCode(eqs, (a[i], c), (i, j),
                          logger=logger, save_temp=True)
    x_, y_ = ex_code(inps, bounds=(ilim, jlim))
    x_ref = (a_arr/3-1)**np.arange(ilim[0], ilim[1]) + c_
    y_ref = a_arr[jlim[0]:jlim[1]] - np.arange(jlim[0], jlim[1])
    assert np.allclose(x_, x_ref)
    assert np.allclose(y_, y_ref)
1110294
def parameters(self):
        """"""
        lines = Lines()
        lines.add(0, '@cython.final')
        lines.add(0, 'cdef class Parameters(object):')
        for subpars in self.model.parameters:
            if subpars:
                lines.add(1, 'cdef public %s %s'
                             % (objecttools.classname(subpars), subpars.name))
        for subpars in self.model.parameters:
            if subpars:
                print('        - %s' % subpars.name)
                lines.add(0, '@cython.final')
                lines.add(0, 'cdef class %s(object):'
                             % objecttools.classname(subpars))
                for par in subpars:
                    try:
                        ctype = TYPE2STR[par.TYPE] + NDIM2STR[par.NDIM]
                    except KeyError:
                        ctype = par.TYPE + NDIM2STR[par.NDIM]
                    lines.add(1, 'cdef public %s %s' % (ctype, par.name))
        return lines
224959
def as_pyemu_matrix(self,typ=Matrix):
        
        x = self.values.copy().astype(np.float)
        return typ(x=x,row_names=list(self.index),
                      col_names=list(self.columns))
833702
def _bnd(self, xloc, dist, cache):
        """"""
        return numpy.log(evaluation.evaluate_bound(
            dist, numpy.e**xloc, cache=cache))
973702
def to_np(v):
    ''''''
    if isinstance(v, float): return np.array(v)
    if isinstance(v, (np.ndarray, np.generic)): return v
    if isinstance(v, (list,tuple)): return [to_np(o) for o in v]
    if isinstance(v, Variable): v=v.data
    if torch.cuda.is_available():
        if is_half_tensor(v): v=v.float()
    if isinstance(v, torch.FloatTensor): v=v.float()
    return v.cpu().numpy()
396675
def cublasCsymv(handle, uplo, n, alpha, A, lda, x, incx, beta, y, incy):
    

    status = _libcublas.cublasCsymv_v2(handle, 
                                        _CUBLAS_FILL_MODE[uplo], n, 
                                        ctypes.byref(cuda.cuFloatComplex(alpha.real,
                                                                        alpha.imag)), 
                                        int(A), lda, int(x), incx, 
                                        ctypes.byref(cuda.cuFloatComplex(beta.real,
                                                                        beta.imag)), 
                                        int(y), incy)
    cublasCheckStatus(status)
1242544
def create_from_dict(cls, src_dict, roi_skydir=None, rescale=False):
        
        src_dict = copy.deepcopy(src_dict)
        src_dict.setdefault('SpatialModel', 'PointSource')
        src_dict.setdefault('Spectrum_Filename', None)
        src_dict.setdefault('SpectrumType', 'PowerLaw')
        src_dict['SpatialType'] = get_spatial_type(src_dict['SpatialModel'])

        spectrum_type = src_dict['SpectrumType']
        spatial_type = src_dict['SpatialType']

        spectral_pars = src_dict.pop('spectral_pars', {})
        spatial_pars = src_dict.pop('spatial_pars', {})

        if not spectral_pars:
            spectral_pars = extract_pars_from_dict(spectrum_type, src_dict)
            norm_par_name = get_function_norm_par_name(spectrum_type)
            if norm_par_name is not None:
                spectral_pars[norm_par_name].setdefault('free', True)

        if not spatial_pars:
            spatial_pars = extract_pars_from_dict(spatial_type, src_dict)
            for k in ['RA', 'DEC', 'Prefactor']:
                if k in spatial_pars:
                    del spatial_pars[k]

        spectral_pars = create_pars_from_dict(spectrum_type, spectral_pars,
                                              rescale)
        spatial_pars = create_pars_from_dict(spatial_type, spatial_pars,
                                             False)

        if 'file' in src_dict:
            src_dict['Spectrum_Filename'] = src_dict.pop('file')

        if spectrum_type == 'DMFitFunction' and src_dict['Spectrum_Filename'] is None:
            src_dict['Spectrum_Filename'] = os.path.join('$FERMIPY_DATA_DIR',
                                                         'gammamc_dif.dat')

        src_dict['spectral_pars'] = cast_pars_dict(spectral_pars)
        src_dict['spatial_pars'] = cast_pars_dict(spatial_pars)

        if 'name' in src_dict:
            name = src_dict['name']
            src_dict['Source_Name'] = src_dict.pop('name')
        elif 'Source_Name' in src_dict:
            name = src_dict['Source_Name']
        else:
            raise Exception('Source name undefined.')

        skydir = wcs_utils.get_target_skydir(src_dict, roi_skydir)

        src_dict['RAJ2000'] = skydir.ra.deg
        src_dict['DEJ2000'] = skydir.dec.deg

        radec = np.array([skydir.ra.deg, skydir.dec.deg])

        return cls(name, src_dict, radec=radec)
1357713
def cublasCgeru(handle, m, n, alpha, x, incx, y, incy, A, lda):
    

    status = _libcublas.cublasCgeru_v2(handle,
                                       m, n, ctypes.byref(cuda.cuFloatComplex(alpha.real,
                                                                              alpha.imag)),
                                       int(x), incx, int(y), incy, int(A), lda)
    cublasCheckStatus(status)
1250015
def dump_cython(content, name, ofile):
    '''
    '''
    with open(ofile, 'wb') as fh:
        fh.write('cdef extern from "{}":\n'.format(name))
        for item in content:
            if isinstance(item, FunctionSpec):
                code = format_function(item)
            elif isinstance(item, StructSpec):
                code = format_struct(item)
            elif isinstance(item, EnumSpec):
                code = format_enum(item)
            elif isinstance(item, TypeDef):
                code = format_typedef(item)
            else:
                fh.write('>>>>>>>>\n{}\n<<<<<<<<'.format(item))
                code = []

            fh.write('{}\n\n'.format('\n'.join(['{}{}'.format(tab, c)
                                                for c in code])))
318022
def _cdist_scipy(x, y, exponent=1):
    """"""
    metric = 'euclidean'

    if exponent != 1:
        metric = 'sqeuclidean'

    distances = _spatial.distance.cdist(x, y, metric=metric)

    if exponent != 1:
        distances **= exponent / 2

    return distances