diff --git a/sklearn/_build_utils/__init__.py b/sklearn/_build_utils/__init__.py index 755171ee770c4..33af1a5128ad7 100644 --- a/sklearn/_build_utils/__init__.py +++ b/sklearn/_build_utils/__init__.py @@ -40,7 +40,6 @@ def cythonize_extensions(extension): """Check that a recent Cython is available and cythonize extensions""" _check_cython_version() from Cython.Build import cythonize - import Cython # Fast fail before cythonization if compiler fails compiling basic test # code even without OpenMP @@ -80,21 +79,6 @@ def cythonize_extensions(extension): "cdivision": True, } - # TODO: once Cython 3 is released and we require Cython>=3 we should get - # rid of the `legacy_implicit_noexcept` directive. - # This should mostly consist in: - # - # - ensuring nogil is at the end of function signature, - # e.g. replace "nogil except -1" by "except -1 nogil". - # - # - "noexcept"-qualifying Cython and externalized C interfaces - # which aren't raising nor propagating exceptions. - # See: https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html#error-return-values # noqa - # - # See: https://github.com/cython/cython/issues/5088 for more details - if parse(Cython.__version__) > parse("3.0.0a11"): - compiler_directives["legacy_implicit_noexcept"] = True - return cythonize( extension, nthreads=n_jobs, diff --git a/sklearn/_loss/_loss.pxd b/sklearn/_loss/_loss.pxd index a50b3ff0d327c..3aad078c0f3a1 100644 --- a/sklearn/_loss/_loss.pxd +++ b/sklearn/_loss/_loss.pxd @@ -20,57 +20,57 @@ ctypedef struct double_pair: # C base class for loss functions cdef class CyLossFunction: - cdef double cy_loss(self, double y_true, double raw_prediction) nogil - cdef double cy_gradient(self, double y_true, double raw_prediction) nogil - cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil + cdef double cy_loss(self, double y_true, double raw_prediction) noexcept nogil + cdef double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil + cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) noexcept nogil cdef class CyHalfSquaredError(CyLossFunction): - cdef double cy_loss(self, double y_true, double raw_prediction) nogil - cdef double cy_gradient(self, double y_true, double raw_prediction) nogil - cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil + cdef double cy_loss(self, double y_true, double raw_prediction) noexcept nogil + cdef double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil + cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) noexcept nogil cdef class CyAbsoluteError(CyLossFunction): - cdef double cy_loss(self, double y_true, double raw_prediction) nogil - cdef double cy_gradient(self, double y_true, double raw_prediction) nogil - cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil + cdef double cy_loss(self, double y_true, double raw_prediction) noexcept nogil + cdef double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil + cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) noexcept nogil cdef class CyPinballLoss(CyLossFunction): cdef readonly double quantile # readonly makes it accessible from Python - cdef double cy_loss(self, double y_true, double raw_prediction) nogil - cdef double cy_gradient(self, double y_true, double raw_prediction) nogil - cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil + cdef double cy_loss(self, double y_true, double raw_prediction) noexcept nogil + cdef double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil + cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) noexcept nogil cdef class CyHalfPoissonLoss(CyLossFunction): - cdef double cy_loss(self, double y_true, double raw_prediction) nogil - cdef double cy_gradient(self, double y_true, double raw_prediction) nogil - cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil + cdef double cy_loss(self, double y_true, double raw_prediction) noexcept nogil + cdef double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil + cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) noexcept nogil cdef class CyHalfGammaLoss(CyLossFunction): - cdef double cy_loss(self, double y_true, double raw_prediction) nogil - cdef double cy_gradient(self, double y_true, double raw_prediction) nogil - cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil + cdef double cy_loss(self, double y_true, double raw_prediction) noexcept nogil + cdef double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil + cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) noexcept nogil cdef class CyHalfTweedieLoss(CyLossFunction): cdef readonly double power # readonly makes it accessible from Python - cdef double cy_loss(self, double y_true, double raw_prediction) nogil - cdef double cy_gradient(self, double y_true, double raw_prediction) nogil - cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil + cdef double cy_loss(self, double y_true, double raw_prediction) noexcept nogil + cdef double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil + cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) noexcept nogil cdef class CyHalfTweedieLossIdentity(CyLossFunction): cdef readonly double power # readonly makes it accessible from Python - cdef double cy_loss(self, double y_true, double raw_prediction) nogil - cdef double cy_gradient(self, double y_true, double raw_prediction) nogil - cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil + cdef double cy_loss(self, double y_true, double raw_prediction) noexcept nogil + cdef double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil + cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) noexcept nogil cdef class CyHalfBinomialLoss(CyLossFunction): - cdef double cy_loss(self, double y_true, double raw_prediction) nogil - cdef double cy_gradient(self, double y_true, double raw_prediction) nogil - cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil + cdef double cy_loss(self, double y_true, double raw_prediction) noexcept nogil + cdef double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil + cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) noexcept nogil diff --git a/sklearn/_loss/_loss.pyx.tp b/sklearn/_loss/_loss.pyx.tp index 4e2e9262f4703..efb40d678e3f6 100644 --- a/sklearn/_loss/_loss.pyx.tp +++ b/sklearn/_loss/_loss.pyx.tp @@ -228,7 +228,7 @@ from libc.stdlib cimport malloc, free # time. Compared to the reference, we add the additional case distinction x <= -2 in # order to use log instead of log1p for improved performance. As with the other # cutoffs, this is accurate within machine precision of double. -cdef inline double log1pexp(double x) nogil: +cdef inline double log1pexp(double x) noexcept nogil: if x <= -37: return exp(x) elif x <= -2: @@ -245,7 +245,7 @@ cdef inline void sum_exp_minus_max( const int i, const Y_DTYPE_C[:, :] raw_prediction, # IN Y_DTYPE_C *p # OUT -) nogil: +) noexcept nogil: # Thread local buffers are used to stores results of this function via p. # The results are stored as follows: # p[k] = exp(raw_prediction_i_k - max_value) for k = 0 to n_classes-1 @@ -285,21 +285,21 @@ cdef inline void sum_exp_minus_max( cdef inline double closs_half_squared_error( double y_true, double raw_prediction -) nogil: +) noexcept nogil: return 0.5 * (raw_prediction - y_true) * (raw_prediction - y_true) cdef inline double cgradient_half_squared_error( double y_true, double raw_prediction -) nogil: +) noexcept nogil: return raw_prediction - y_true cdef inline double_pair cgrad_hess_half_squared_error( double y_true, double raw_prediction -) nogil: +) noexcept nogil: cdef double_pair gh gh.val1 = raw_prediction - y_true # gradient gh.val2 = 1. # hessian @@ -310,21 +310,21 @@ cdef inline double_pair cgrad_hess_half_squared_error( cdef inline double closs_absolute_error( double y_true, double raw_prediction -) nogil: +) noexcept nogil: return fabs(raw_prediction - y_true) cdef inline double cgradient_absolute_error( double y_true, double raw_prediction -) nogil: +) noexcept nogil: return 1. if raw_prediction > y_true else -1. cdef inline double_pair cgrad_hess_absolute_error( double y_true, double raw_prediction -) nogil: +) noexcept nogil: cdef double_pair gh # Note that exact hessian = 0 almost everywhere. Optimization routines like # in HGBT, however, need a hessian > 0. Therefore, we assign 1. @@ -338,7 +338,7 @@ cdef inline double closs_pinball_loss( double y_true, double raw_prediction, double quantile -) nogil: +) noexcept nogil: return (quantile * (y_true - raw_prediction) if y_true >= raw_prediction else (1. - quantile) * (raw_prediction - y_true)) @@ -347,7 +347,7 @@ cdef inline double cgradient_pinball_loss( double y_true, double raw_prediction, double quantile -) nogil: +) noexcept nogil: return -quantile if y_true >=raw_prediction else 1. - quantile @@ -355,7 +355,7 @@ cdef inline double_pair cgrad_hess_pinball_loss( double y_true, double raw_prediction, double quantile -) nogil: +) noexcept nogil: cdef double_pair gh # Note that exact hessian = 0 almost everywhere. Optimization routines like # in HGBT, however, need a hessian > 0. Therefore, we assign 1. @@ -368,14 +368,14 @@ cdef inline double_pair cgrad_hess_pinball_loss( cdef inline double closs_half_poisson( double y_true, double raw_prediction -) nogil: +) noexcept nogil: return exp(raw_prediction) - y_true * raw_prediction cdef inline double cgradient_half_poisson( double y_true, double raw_prediction -) nogil: +) noexcept nogil: # y_pred - y_true return exp(raw_prediction) - y_true @@ -383,7 +383,7 @@ cdef inline double cgradient_half_poisson( cdef inline double_pair closs_grad_half_poisson( double y_true, double raw_prediction -) nogil: +) noexcept nogil: cdef double_pair lg lg.val2 = exp(raw_prediction) # used as temporary lg.val1 = lg.val2 - y_true * raw_prediction # loss @@ -394,7 +394,7 @@ cdef inline double_pair closs_grad_half_poisson( cdef inline double_pair cgrad_hess_half_poisson( double y_true, double raw_prediction -) nogil: +) noexcept nogil: cdef double_pair gh gh.val2 = exp(raw_prediction) # hessian gh.val1 = gh.val2 - y_true # gradient @@ -405,21 +405,21 @@ cdef inline double_pair cgrad_hess_half_poisson( cdef inline double closs_half_gamma( double y_true, double raw_prediction -) nogil: +) noexcept nogil: return raw_prediction + y_true * exp(-raw_prediction) cdef inline double cgradient_half_gamma( double y_true, double raw_prediction -) nogil: +) noexcept nogil: return 1. - y_true * exp(-raw_prediction) cdef inline double_pair closs_grad_half_gamma( double y_true, double raw_prediction -) nogil: +) noexcept nogil: cdef double_pair lg lg.val2 = exp(-raw_prediction) # used as temporary lg.val1 = raw_prediction + y_true * lg.val2 # loss @@ -430,7 +430,7 @@ cdef inline double_pair closs_grad_half_gamma( cdef inline double_pair cgrad_hess_half_gamma( double y_true, double raw_prediction -) nogil: +) noexcept nogil: cdef double_pair gh gh.val2 = exp(-raw_prediction) # used as temporary gh.val1 = 1. - y_true * gh.val2 # gradient @@ -444,7 +444,7 @@ cdef inline double closs_half_tweedie( double y_true, double raw_prediction, double power -) nogil: +) noexcept nogil: if power == 0.: return closs_half_squared_error(y_true, exp(raw_prediction)) elif power == 1.: @@ -460,7 +460,7 @@ cdef inline double cgradient_half_tweedie( double y_true, double raw_prediction, double power -) nogil: +) noexcept nogil: cdef double exp1 if power == 0.: exp1 = exp(raw_prediction) @@ -478,7 +478,7 @@ cdef inline double_pair closs_grad_half_tweedie( double y_true, double raw_prediction, double power -) nogil: +) noexcept nogil: cdef double_pair lg cdef double exp1, exp2 if power == 0.: @@ -501,7 +501,7 @@ cdef inline double_pair cgrad_hess_half_tweedie( double y_true, double raw_prediction, double power -) nogil: +) noexcept nogil: cdef double_pair gh cdef double exp1, exp2 if power == 0.: @@ -526,7 +526,7 @@ cdef inline double closs_half_tweedie_identity( double y_true, double raw_prediction, double power -) nogil: +) noexcept nogil: cdef double tmp if power == 0.: return closs_half_squared_error(y_true, raw_prediction) @@ -549,7 +549,7 @@ cdef inline double cgradient_half_tweedie_identity( double y_true, double raw_prediction, double power -) nogil: +) noexcept nogil: if power == 0.: return raw_prediction - y_true elif power == 1.: @@ -564,7 +564,7 @@ cdef inline double_pair closs_grad_half_tweedie_identity( double y_true, double raw_prediction, double power -) nogil: +) noexcept nogil: cdef double_pair lg cdef double tmp if power == 0.: @@ -596,7 +596,7 @@ cdef inline double_pair cgrad_hess_half_tweedie_identity( double y_true, double raw_prediction, double power -) nogil: +) noexcept nogil: cdef double_pair gh cdef double tmp if power == 0.: @@ -620,7 +620,7 @@ cdef inline double_pair cgrad_hess_half_tweedie_identity( cdef inline double closs_half_binomial( double y_true, double raw_prediction -) nogil: +) noexcept nogil: # log1p(exp(raw_prediction)) - y_true * raw_prediction return log1pexp(raw_prediction) - y_true * raw_prediction @@ -628,7 +628,7 @@ cdef inline double closs_half_binomial( cdef inline double cgradient_half_binomial( double y_true, double raw_prediction -) nogil: +) noexcept nogil: # y_pred - y_true = expit(raw_prediction) - y_true # Numerically more stable, see # http://fa.bianp.net/blog/2019/evaluate_logistic/ @@ -653,7 +653,7 @@ cdef inline double cgradient_half_binomial( cdef inline double_pair closs_grad_half_binomial( double y_true, double raw_prediction -) nogil: +) noexcept nogil: cdef double_pair lg if raw_prediction <= 0: lg.val2 = exp(raw_prediction) # used as temporary @@ -676,7 +676,7 @@ cdef inline double_pair closs_grad_half_binomial( cdef inline double_pair cgrad_hess_half_binomial( double y_true, double raw_prediction -) nogil: +) noexcept nogil: # with y_pred = expit(raw) # hessian = y_pred * (1 - y_pred) = exp(raw) / (1 + exp(raw))**2 # = exp(-raw) / (1 + exp(-raw))**2 @@ -693,7 +693,7 @@ cdef inline double_pair cgrad_hess_half_binomial( cdef class CyLossFunction: """Base class for convex loss functions.""" - cdef double cy_loss(self, double y_true, double raw_prediction) nogil: + cdef double cy_loss(self, double y_true, double raw_prediction) noexcept nogil: """Compute the loss for a single sample. Parameters @@ -710,7 +710,7 @@ cdef class CyLossFunction: """ pass - cdef double cy_gradient(self, double y_true, double raw_prediction) nogil: + cdef double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil: """Compute gradient of loss w.r.t. raw_prediction for a single sample. Parameters @@ -727,7 +727,7 @@ cdef class CyLossFunction: """ pass - cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil: + cdef double_pair cy_grad_hess(self, double y_true, double raw_prediction) noexcept nogil: """Compute gradient and hessian. Gradient and hessian of loss w.r.t. raw_prediction for a single sample. @@ -903,13 +903,13 @@ cdef class {{name}}(CyLossFunction): self.{{param}} = {{param}} {{endif}} - cdef inline double cy_loss(self, double y_true, double raw_prediction) nogil: + cdef inline double cy_loss(self, double y_true, double raw_prediction) noexcept nogil: return {{closs}}(y_true, raw_prediction{{with_param}}) - cdef inline double cy_gradient(self, double y_true, double raw_prediction) nogil: + cdef inline double cy_gradient(self, double y_true, double raw_prediction) noexcept nogil: return {{cgrad}}(y_true, raw_prediction{{with_param}}) - cdef inline double_pair cy_grad_hess(self, double y_true, double raw_prediction) nogil: + cdef inline double_pair cy_grad_hess(self, double y_true, double raw_prediction) noexcept nogil: return {{cgrad_hess}}(y_true, raw_prediction{{with_param}}) def loss( diff --git a/sklearn/cluster/_k_means_common.pxd b/sklearn/cluster/_k_means_common.pxd index 7ecc81966ad42..0ef38dbcf2b7c 100644 --- a/sklearn/cluster/_k_means_common.pxd +++ b/sklearn/cluster/_k_means_common.pxd @@ -6,7 +6,7 @@ cdef floating _euclidean_dense_dense( const floating*, int, bint -) nogil +) noexcept nogil cdef floating _euclidean_sparse_dense( const floating[::1], @@ -14,7 +14,7 @@ cdef floating _euclidean_sparse_dense( const floating[::1], floating, bint -) nogil +) noexcept nogil cpdef void _relocate_empty_clusters_dense( const floating[:, ::1], diff --git a/sklearn/cluster/_k_means_common.pyx b/sklearn/cluster/_k_means_common.pyx index b5bd06b3b558b..ba78e038feb98 100644 --- a/sklearn/cluster/_k_means_common.pyx +++ b/sklearn/cluster/_k_means_common.pyx @@ -25,7 +25,7 @@ cdef floating _euclidean_dense_dense( const floating* b, # IN int n_features, bint squared -) nogil: +) noexcept nogil: """Euclidean distance between a dense and b dense""" cdef: int i @@ -62,7 +62,7 @@ cdef floating _euclidean_sparse_dense( const floating[::1] b, # IN floating b_squared_norm, bint squared -) nogil: +) noexcept nogil: """Euclidean distance between a sparse and b dense""" cdef: int nnz = a_indices.shape[0] diff --git a/sklearn/cluster/_k_means_elkan.pyx b/sklearn/cluster/_k_means_elkan.pyx index 3f33fe91e2693..abde900903c50 100644 --- a/sklearn/cluster/_k_means_elkan.pyx +++ b/sklearn/cluster/_k_means_elkan.pyx @@ -360,7 +360,7 @@ cdef void _update_chunk_dense( floating[:, ::1] lower_bounds, # INOUT floating *centers_new, # OUT floating *weight_in_clusters, # OUT - bint update_centers) nogil: + bint update_centers) noexcept nogil: """K-means combined EM step for one dense data chunk. Compute the partial contribution of a single data chunk to the labels and @@ -609,7 +609,7 @@ cdef void _update_chunk_sparse( floating[:, ::1] lower_bounds, # INOUT floating *centers_new, # OUT floating *weight_in_clusters, # OUT - bint update_centers) nogil: + bint update_centers) noexcept nogil: """K-means combined EM step for one sparse data chunk. Compute the partial contribution of a single data chunk to the labels and diff --git a/sklearn/cluster/_k_means_lloyd.pyx b/sklearn/cluster/_k_means_lloyd.pyx index 9d78e1617b815..63e5ee3530d6e 100644 --- a/sklearn/cluster/_k_means_lloyd.pyx +++ b/sklearn/cluster/_k_means_lloyd.pyx @@ -169,7 +169,7 @@ cdef void _update_chunk_dense( floating *centers_new, # OUT floating *weight_in_clusters, # OUT floating *pairwise_distances, # OUT - bint update_centers) nogil: + bint update_centers) noexcept nogil: """K-means combined EM step for one dense data chunk. Compute the partial contribution of a single data chunk to the labels and @@ -368,7 +368,7 @@ cdef void _update_chunk_sparse( int[::1] labels, # OUT floating *centers_new, # OUT floating *weight_in_clusters, # OUT - bint update_centers) nogil: + bint update_centers) noexcept nogil: """K-means combined EM step for one sparse data chunk. Compute the partial contribution of a single data chunk to the labels and diff --git a/sklearn/cluster/_k_means_minibatch.pyx b/sklearn/cluster/_k_means_minibatch.pyx index 4c3b893ecb783..503413a469e3e 100644 --- a/sklearn/cluster/_k_means_minibatch.pyx +++ b/sklearn/cluster/_k_means_minibatch.pyx @@ -68,7 +68,7 @@ cdef void update_center_dense( floating[:, ::1] centers_new, # OUT floating[::1] weight_sums, # INOUT const int[::1] labels, # IN - int *indices) nogil: # TMP + int *indices) noexcept nogil: # TMP """Update of a single center for dense MinibatchKMeans""" cdef: int n_samples = sample_weight.shape[0] @@ -178,7 +178,7 @@ cdef void update_center_sparse( floating[:, ::1] centers_new, # OUT floating[::1] weight_sums, # INOUT const int[::1] labels, # IN - int *indices) nogil: # TMP + int *indices) noexcept nogil: # TMP """Update of a single center for sparse MinibatchKMeans""" cdef: int n_samples = sample_weight.shape[0] diff --git a/sklearn/decomposition/_online_lda_fast.pyx b/sklearn/decomposition/_online_lda_fast.pyx index 9fbfd48d42428..0ef34dd395990 100644 --- a/sklearn/decomposition/_online_lda_fast.pyx +++ b/sklearn/decomposition/_online_lda_fast.pyx @@ -90,7 +90,7 @@ def _dirichlet_expectation_2d(const floating[:, :] arr): # # After: J. Bernardo (1976). Algorithm AS 103: Psi (Digamma) Function. # https://www.uv.es/~bernardo/1976AppStatist.pdf -cdef floating psi(floating x) nogil: +cdef floating psi(floating x) noexcept nogil: if x <= 1e-6: # psi(x) = -EULER - 1/x + O(x) return -EULER - 1. / x diff --git a/sklearn/ensemble/_gradient_boosting.pyx b/sklearn/ensemble/_gradient_boosting.pyx index e78aec8f63ea5..c738966e0332a 100644 --- a/sklearn/ensemble/_gradient_boosting.pyx +++ b/sklearn/ensemble/_gradient_boosting.pyx @@ -35,7 +35,7 @@ cdef void _predict_regression_tree_inplace_fast_dense( Py_ssize_t n_samples, Py_ssize_t n_features, cnp.float64_t[:, :] out -) nogil: +) noexcept nogil: """Predicts output for regression tree and stores it in ``out[i, k]``. This function operates directly on the data arrays of the tree diff --git a/sklearn/ensemble/_hist_gradient_boosting/_bitset.pxd b/sklearn/ensemble/_hist_gradient_boosting/_bitset.pxd index 4aea8276c4398..343ffa1191b22 100644 --- a/sklearn/ensemble/_hist_gradient_boosting/_bitset.pxd +++ b/sklearn/ensemble/_hist_gradient_boosting/_bitset.pxd @@ -3,16 +3,16 @@ from .common cimport BITSET_DTYPE_C from .common cimport BITSET_INNER_DTYPE_C from .common cimport X_DTYPE_C -cdef void init_bitset(BITSET_DTYPE_C bitset) nogil +cdef void init_bitset(BITSET_DTYPE_C bitset) noexcept nogil -cdef void set_bitset(BITSET_DTYPE_C bitset, X_BINNED_DTYPE_C val) nogil +cdef void set_bitset(BITSET_DTYPE_C bitset, X_BINNED_DTYPE_C val) noexcept nogil -cdef unsigned char in_bitset(BITSET_DTYPE_C bitset, X_BINNED_DTYPE_C val) nogil +cdef unsigned char in_bitset(BITSET_DTYPE_C bitset, X_BINNED_DTYPE_C val) noexcept nogil cpdef unsigned char in_bitset_memoryview(const BITSET_INNER_DTYPE_C[:] bitset, - X_BINNED_DTYPE_C val) nogil + X_BINNED_DTYPE_C val) noexcept nogil cdef unsigned char in_bitset_2d_memoryview( const BITSET_INNER_DTYPE_C [:, :] bitset, X_BINNED_DTYPE_C val, - unsigned int row) nogil + unsigned int row) noexcept nogil diff --git a/sklearn/ensemble/_hist_gradient_boosting/_bitset.pyx b/sklearn/ensemble/_hist_gradient_boosting/_bitset.pyx index 0d3b630f3314f..e92d137366433 100644 --- a/sklearn/ensemble/_hist_gradient_boosting/_bitset.pyx +++ b/sklearn/ensemble/_hist_gradient_boosting/_bitset.pyx @@ -12,7 +12,7 @@ from .common cimport X_BINNED_DTYPE_C # https://en.wikipedia.org/wiki/Bitwise_operation -cdef inline void init_bitset(BITSET_DTYPE_C bitset) nogil: # OUT +cdef inline void init_bitset(BITSET_DTYPE_C bitset) noexcept nogil: # OUT cdef: unsigned int i @@ -21,23 +21,23 @@ cdef inline void init_bitset(BITSET_DTYPE_C bitset) nogil: # OUT cdef inline void set_bitset(BITSET_DTYPE_C bitset, # OUT - X_BINNED_DTYPE_C val) nogil: + X_BINNED_DTYPE_C val) noexcept nogil: bitset[val // 32] |= (1 << (val % 32)) cdef inline unsigned char in_bitset(BITSET_DTYPE_C bitset, - X_BINNED_DTYPE_C val) nogil: + X_BINNED_DTYPE_C val) noexcept nogil: return (bitset[val // 32] >> (val % 32)) & 1 cpdef inline unsigned char in_bitset_memoryview(const BITSET_INNER_DTYPE_C[:] bitset, - X_BINNED_DTYPE_C val) nogil: + X_BINNED_DTYPE_C val) noexcept nogil: return (bitset[val // 32] >> (val % 32)) & 1 cdef inline unsigned char in_bitset_2d_memoryview(const BITSET_INNER_DTYPE_C [:, :] bitset, X_BINNED_DTYPE_C val, - unsigned int row) nogil: + unsigned int row) noexcept nogil: # Same as above but works on 2d memory views to avoid the creation of 1d # memory views. See https://github.com/scikit-learn/scikit-learn/issues/17299 diff --git a/sklearn/ensemble/_hist_gradient_boosting/_predictor.pyx b/sklearn/ensemble/_hist_gradient_boosting/_predictor.pyx index dab18bdd1d49c..5a419d7487db1 100644 --- a/sklearn/ensemble/_hist_gradient_boosting/_predictor.pyx +++ b/sklearn/ensemble/_hist_gradient_boosting/_predictor.pyx @@ -39,7 +39,7 @@ cdef inline Y_DTYPE_C _predict_one_from_raw_data( const BITSET_INNER_DTYPE_C [:, ::1] raw_left_cat_bitsets, const BITSET_INNER_DTYPE_C [:, ::1] known_cat_bitsets, const unsigned int [::1] f_idx_map, - const int row) nogil: + const int row) noexcept nogil: # Need to pass the whole array and the row index, else prange won't work. # See issue Cython #2798 @@ -108,7 +108,7 @@ cdef inline Y_DTYPE_C _predict_one_from_binned_data( const X_BINNED_DTYPE_C [:, :] binned_data, const BITSET_INNER_DTYPE_C [:, :] binned_left_cat_bitsets, const int row, - const unsigned char missing_values_bin_idx) nogil: + const unsigned char missing_values_bin_idx) noexcept nogil: # Need to pass the whole array and the row index, else prange won't work. # See issue Cython #2798 diff --git a/sklearn/ensemble/_hist_gradient_boosting/histogram.pyx b/sklearn/ensemble/_hist_gradient_boosting/histogram.pyx index 26510e19c8b8d..1dbe64a4a5dfb 100644 --- a/sklearn/ensemble/_hist_gradient_boosting/histogram.pyx +++ b/sklearn/ensemble/_hist_gradient_boosting/histogram.pyx @@ -184,7 +184,7 @@ cdef class HistogramBuilder: HistogramBuilder self, const int feature_idx, const unsigned int [::1] sample_indices, # IN - hist_struct [:, ::1] histograms) nogil: # OUT + hist_struct [:, ::1] histograms) noexcept nogil: # OUT """Compute the histogram for a given feature.""" cdef: @@ -295,7 +295,7 @@ cpdef void _build_histogram_naive( X_BINNED_DTYPE_C [:] binned_feature, # IN G_H_DTYPE_C [:] ordered_gradients, # IN G_H_DTYPE_C [:] ordered_hessians, # IN - hist_struct [:, :] out) nogil: # OUT + hist_struct [:, :] out) noexcept nogil: # OUT """Build histogram in a naive way, without optimizing for cache hit. Used in tests to compare with the optimized version.""" @@ -318,7 +318,7 @@ cpdef void _subtract_histograms( unsigned int n_bins, hist_struct [:, ::1] hist_a, # IN hist_struct [:, ::1] hist_b, # IN - hist_struct [:, ::1] out) nogil: # OUT + hist_struct [:, ::1] out) noexcept nogil: # OUT """compute (hist_a - hist_b) in out""" cdef: unsigned int i = 0 @@ -343,7 +343,7 @@ cpdef void _build_histogram( const X_BINNED_DTYPE_C [::1] binned_feature, # IN const G_H_DTYPE_C [::1] ordered_gradients, # IN const G_H_DTYPE_C [::1] ordered_hessians, # IN - hist_struct [:, ::1] out) nogil: # OUT + hist_struct [:, ::1] out) noexcept nogil: # OUT """Return histogram for a given feature.""" cdef: unsigned int i = 0 @@ -389,7 +389,7 @@ cpdef void _build_histogram_no_hessian( const unsigned int [::1] sample_indices, # IN const X_BINNED_DTYPE_C [::1] binned_feature, # IN const G_H_DTYPE_C [::1] ordered_gradients, # IN - hist_struct [:, ::1] out) nogil: # OUT + hist_struct [:, ::1] out) noexcept nogil: # OUT """Return histogram for a given feature, not updating hessians. Used when the hessians of the loss are constant (typically LS loss). @@ -433,7 +433,7 @@ cpdef void _build_histogram_root( const X_BINNED_DTYPE_C [::1] binned_feature, # IN const G_H_DTYPE_C [::1] all_gradients, # IN const G_H_DTYPE_C [::1] all_hessians, # IN - hist_struct [:, ::1] out) nogil: # OUT + hist_struct [:, ::1] out) noexcept nogil: # OUT """Compute histogram of the root node. Unlike other nodes, the root node has to find the split among *all* the @@ -485,7 +485,7 @@ cpdef void _build_histogram_root_no_hessian( const int feature_idx, const X_BINNED_DTYPE_C [::1] binned_feature, # IN const G_H_DTYPE_C [::1] all_gradients, # IN - hist_struct [:, ::1] out) nogil: # OUT + hist_struct [:, ::1] out) noexcept nogil: # OUT """Compute histogram of the root node, not updating hessians. Used when the hessians of the loss are constant (typically LS loss). diff --git a/sklearn/ensemble/_hist_gradient_boosting/splitting.pyx b/sklearn/ensemble/_hist_gradient_boosting/splitting.pyx index f6630efd28a0f..cdeb373350ed4 100644 --- a/sklearn/ensemble/_hist_gradient_boosting/splitting.pyx +++ b/sklearn/ensemble/_hist_gradient_boosting/splitting.pyx @@ -573,7 +573,7 @@ cdef class Splitter: self, split_info_struct * split_infos, # IN int n_allowed_features, - ) nogil: + ) noexcept nogil: """Return the index of split_infos with the best feature split.""" cdef: unsigned int split_info_idx @@ -596,7 +596,7 @@ cdef class Splitter: signed char monotonic_cst, Y_DTYPE_C lower_bound, Y_DTYPE_C upper_bound, - split_info_struct * split_info) nogil: # OUT + split_info_struct * split_info) noexcept nogil: # OUT """Find best bin to split on for a given feature. Splits that do not satisfy the splitting constraints @@ -710,7 +710,7 @@ cdef class Splitter: signed char monotonic_cst, Y_DTYPE_C lower_bound, Y_DTYPE_C upper_bound, - split_info_struct * split_info) nogil: # OUT + split_info_struct * split_info) noexcept nogil: # OUT """Find best bin to split on for a given feature. Splits that do not satisfy the splitting constraints @@ -825,7 +825,7 @@ cdef class Splitter: char monotonic_cst, Y_DTYPE_C lower_bound, Y_DTYPE_C upper_bound, - split_info_struct * split_info) nogil: # OUT + split_info_struct * split_info) noexcept nogil: # OUT """Find best split for categorical features. Categories are first sorted according to their variance, and then @@ -1038,7 +1038,7 @@ cdef class Splitter: free(cat_infos) -cdef int compare_cat_infos(const void * a, const void * b) nogil: +cdef int compare_cat_infos(const void * a, const void * b) noexcept nogil: return -1 if (a).value < (b).value else 1 cdef inline Y_DTYPE_C _split_gain( @@ -1050,7 +1050,7 @@ cdef inline Y_DTYPE_C _split_gain( signed char monotonic_cst, Y_DTYPE_C lower_bound, Y_DTYPE_C upper_bound, - Y_DTYPE_C l2_regularization) nogil: + Y_DTYPE_C l2_regularization) noexcept nogil: """Loss reduction Compute the reduction in loss after taking a split, compared to keeping @@ -1092,7 +1092,7 @@ cdef inline Y_DTYPE_C _split_gain( cdef inline Y_DTYPE_C _loss_from_value( Y_DTYPE_C value, - Y_DTYPE_C sum_gradient) nogil: + Y_DTYPE_C sum_gradient) noexcept nogil: """Return loss of a node from its (bounded) value See Equation 6 of: @@ -1107,7 +1107,7 @@ cdef inline unsigned char sample_goes_left( X_BINNED_DTYPE_C split_bin_idx, X_BINNED_DTYPE_C bin_value, unsigned char is_categorical, - BITSET_DTYPE_C left_cat_bitset) nogil: + BITSET_DTYPE_C left_cat_bitset) noexcept nogil: """Helper to decide whether sample should go to left or right child.""" if is_categorical: @@ -1129,7 +1129,7 @@ cpdef inline Y_DTYPE_C compute_node_value( Y_DTYPE_C sum_hessian, Y_DTYPE_C lower_bound, Y_DTYPE_C upper_bound, - Y_DTYPE_C l2_regularization) nogil: + Y_DTYPE_C l2_regularization) noexcept nogil: """Compute a node's value. The value is capped in the [lower_bound, upper_bound] interval to respect diff --git a/sklearn/linear_model/_cd_fast.pyx b/sklearn/linear_model/_cd_fast.pyx index ba9b922461775..b580e865cce4f 100644 --- a/sklearn/linear_model/_cd_fast.pyx +++ b/sklearn/linear_model/_cd_fast.pyx @@ -35,18 +35,18 @@ cdef enum: RAND_R_MAX = 0x7FFFFFFF -cdef inline UINT32_t rand_int(UINT32_t end, UINT32_t* random_state) nogil: +cdef inline UINT32_t rand_int(UINT32_t end, UINT32_t* random_state) noexcept nogil: """Generate a random integer in [0; end).""" return our_rand_r(random_state) % end -cdef inline floating fmax(floating x, floating y) nogil: +cdef inline floating fmax(floating x, floating y) noexcept nogil: if x > y: return x return y -cdef inline floating fsign(floating f) nogil: +cdef inline floating fsign(floating f) noexcept nogil: if f == 0: return 0 elif f > 0: @@ -55,7 +55,7 @@ cdef inline floating fsign(floating f) nogil: return -1.0 -cdef floating abs_max(int n, floating* a) nogil: +cdef floating abs_max(int n, floating* a) noexcept nogil: """np.max(np.abs(a))""" cdef int i cdef floating m = fabs(a[0]) @@ -67,7 +67,7 @@ cdef floating abs_max(int n, floating* a) nogil: return m -cdef floating max(int n, floating* a) nogil: +cdef floating max(int n, floating* a) noexcept nogil: """np.max(a)""" cdef int i cdef floating m = a[0] @@ -79,7 +79,7 @@ cdef floating max(int n, floating* a) nogil: return m -cdef floating diff_abs_max(int n, floating* a, floating* b) nogil: +cdef floating diff_abs_max(int n, floating* a, floating* b) noexcept nogil: """np.max(np.abs(a - b))""" cdef int i cdef floating m = fabs(a[0] - b[0]) diff --git a/sklearn/linear_model/_sag_fast.pyx.tp b/sklearn/linear_model/_sag_fast.pyx.tp index 9e7f6a11c2fee..5449d5bf4ad02 100644 --- a/sklearn/linear_model/_sag_fast.pyx.tp +++ b/sklearn/linear_model/_sag_fast.pyx.tp @@ -60,7 +60,7 @@ cdef extern from "_sgd_fast_helpers.h": {{for name_suffix, c_type, np_type in dtypes}} -cdef inline {{c_type}} fmax{{name_suffix}}({{c_type}} x, {{c_type}} y) nogil: +cdef inline {{c_type}} fmax{{name_suffix}}({{c_type}} x, {{c_type}} y) noexcept nogil: if x > y: return x return y @@ -70,7 +70,7 @@ cdef inline {{c_type}} fmax{{name_suffix}}({{c_type}} x, {{c_type}} y) nogil: {{for name_suffix, c_type, np_type in dtypes}} -cdef {{c_type}} _logsumexp{{name_suffix}}({{c_type}}* arr, int n_classes) nogil: +cdef {{c_type}} _logsumexp{{name_suffix}}({{c_type}}* arr, int n_classes) noexcept nogil: """Computes the sum of arr assuming arr is in the log domain. Returns log(sum(exp(arr))) while minimizing the possibility of @@ -98,7 +98,7 @@ cdef {{c_type}} _logsumexp{{name_suffix}}({{c_type}}* arr, int n_classes) nogil: cdef class MultinomialLogLoss{{name_suffix}}: cdef {{c_type}} _loss(self, {{c_type}}* prediction, {{c_type}} y, int n_classes, - {{c_type}} sample_weight) nogil: + {{c_type}} sample_weight) noexcept nogil: r"""Multinomial Logistic regression loss. The multinomial logistic loss for one sample is: @@ -142,7 +142,7 @@ cdef class MultinomialLogLoss{{name_suffix}}: return loss cdef void dloss(self, {{c_type}}* prediction, {{c_type}} y, int n_classes, - {{c_type}} sample_weight, {{c_type}}* gradient_ptr) nogil: + {{c_type}} sample_weight, {{c_type}}* gradient_ptr) noexcept nogil: r"""Multinomial Logistic regression gradient of the loss. The gradient of the multinomial logistic loss with respect to a class c, @@ -200,7 +200,7 @@ cdef class MultinomialLogLoss{{name_suffix}}: {{for name_suffix, c_type, np_type in dtypes}} -cdef inline {{c_type}} _soft_thresholding{{name_suffix}}({{c_type}} x, {{c_type}} shrinkage) nogil: +cdef inline {{c_type}} _soft_thresholding{{name_suffix}}({{c_type}} x, {{c_type}} shrinkage) noexcept nogil: return fmax{{name_suffix}}(x - shrinkage, 0) - fmax{{name_suffix}}(- x - shrinkage, 0) {{endfor}} @@ -595,7 +595,7 @@ cdef int scale_weights{{name_suffix}}( bint prox, {{c_type}}* sum_gradient, int n_iter -) nogil: +) noexcept nogil: """Scale the weights and reset wscale to 1.0 for numerical stability, and reset the just-in-time (JIT) update system. @@ -650,7 +650,7 @@ cdef int lagged_update{{name_suffix}}( int* x_ind_ptr, bint reset, int n_iter -) nogil: +) noexcept nogil: """Hard perform the JIT updates for non-zero features of present sample. See `sag{{name_suffix}}`'s docstring about the JIT update system. @@ -744,7 +744,7 @@ cdef void predict_sample{{name_suffix}}( {{c_type}}* intercept, {{c_type}}* prediction, int n_classes -) nogil: +) noexcept nogil: """Compute the prediction given sparse sample x and dense weight w. Parameters diff --git a/sklearn/linear_model/_sgd_fast.pxd b/sklearn/linear_model/_sgd_fast.pxd index 3c02f5ab1a834..7ae704eee18db 100644 --- a/sklearn/linear_model/_sgd_fast.pxd +++ b/sklearn/linear_model/_sgd_fast.pxd @@ -2,25 +2,25 @@ """Helper to load LossFunction from sgd_fast.pyx to sag_fast.pyx""" cdef class LossFunction: - cdef double loss(self, double p, double y) nogil - cdef double dloss(self, double p, double y) nogil + cdef double loss(self, double p, double y) noexcept nogil + cdef double dloss(self, double p, double y) noexcept nogil cdef class Regression(LossFunction): - cdef double loss(self, double p, double y) nogil - cdef double dloss(self, double p, double y) nogil + cdef double loss(self, double p, double y) noexcept nogil + cdef double dloss(self, double p, double y) noexcept nogil cdef class Classification(LossFunction): - cdef double loss(self, double p, double y) nogil - cdef double dloss(self, double p, double y) nogil + cdef double loss(self, double p, double y) noexcept nogil + cdef double dloss(self, double p, double y) noexcept nogil cdef class Log(Classification): - cdef double loss(self, double p, double y) nogil - cdef double dloss(self, double p, double y) nogil + cdef double loss(self, double p, double y) noexcept nogil + cdef double dloss(self, double p, double y) noexcept nogil cdef class SquaredLoss(Regression): - cdef double loss(self, double p, double y) nogil - cdef double dloss(self, double p, double y) nogil + cdef double loss(self, double p, double y) noexcept nogil + cdef double dloss(self, double p, double y) noexcept nogil diff --git a/sklearn/linear_model/_sgd_fast.pyx b/sklearn/linear_model/_sgd_fast.pyx index 84e54c40e1d28..182635bfb5136 100644 --- a/sklearn/linear_model/_sgd_fast.pyx +++ b/sklearn/linear_model/_sgd_fast.pyx @@ -43,7 +43,7 @@ DEF PA2 = 6 cdef class LossFunction: """Base class for convex loss functions""" - cdef double loss(self, double p, double y) nogil: + cdef double loss(self, double p, double y) noexcept nogil: """Evaluate the loss function. Parameters @@ -98,7 +98,7 @@ cdef class LossFunction: """ return self.loss(p, y) - cdef double dloss(self, double p, double y) nogil: + cdef double dloss(self, double p, double y) noexcept nogil: """Evaluate the derivative of the loss function with respect to the prediction `p`. @@ -120,20 +120,20 @@ cdef class LossFunction: cdef class Regression(LossFunction): """Base class for loss functions for regression""" - cdef double loss(self, double p, double y) nogil: + cdef double loss(self, double p, double y) noexcept nogil: return 0. - cdef double dloss(self, double p, double y) nogil: + cdef double dloss(self, double p, double y) noexcept nogil: return 0. cdef class Classification(LossFunction): """Base class for loss functions for classification""" - cdef double loss(self, double p, double y) nogil: + cdef double loss(self, double p, double y) noexcept nogil: return 0. - cdef double dloss(self, double p, double y) nogil: + cdef double dloss(self, double p, double y) noexcept nogil: return 0. @@ -145,7 +145,7 @@ cdef class ModifiedHuber(Classification): See T. Zhang 'Solving Large Scale Linear Prediction Problems Using Stochastic Gradient Descent', ICML'04. """ - cdef double loss(self, double p, double y) nogil: + cdef double loss(self, double p, double y) noexcept nogil: cdef double z = p * y if z >= 1.0: return 0.0 @@ -154,7 +154,7 @@ cdef class ModifiedHuber(Classification): else: return -4.0 * z - cdef double dloss(self, double p, double y) nogil: + cdef double dloss(self, double p, double y) noexcept nogil: cdef double z = p * y if z >= 1.0: return 0.0 @@ -183,13 +183,13 @@ cdef class Hinge(Classification): def __init__(self, double threshold=1.0): self.threshold = threshold - cdef double loss(self, double p, double y) nogil: + cdef double loss(self, double p, double y) noexcept nogil: cdef double z = p * y if z <= self.threshold: return self.threshold - z return 0.0 - cdef double dloss(self, double p, double y) nogil: + cdef double dloss(self, double p, double y) noexcept nogil: cdef double z = p * y if z <= self.threshold: return -y @@ -215,13 +215,13 @@ cdef class SquaredHinge(Classification): def __init__(self, double threshold=1.0): self.threshold = threshold - cdef double loss(self, double p, double y) nogil: + cdef double loss(self, double p, double y) noexcept nogil: cdef double z = self.threshold - p * y if z > 0: return z * z return 0.0 - cdef double dloss(self, double p, double y) nogil: + cdef double dloss(self, double p, double y) noexcept nogil: cdef double z = self.threshold - p * y if z > 0: return -2 * y * z @@ -234,7 +234,7 @@ cdef class SquaredHinge(Classification): cdef class Log(Classification): """Logistic regression loss for binary classification with y in {-1, 1}""" - cdef double loss(self, double p, double y) nogil: + cdef double loss(self, double p, double y) noexcept nogil: cdef double z = p * y # approximately equal and saves the computation of the log if z > 18: @@ -243,7 +243,7 @@ cdef class Log(Classification): return -z return log(1.0 + exp(-z)) - cdef double dloss(self, double p, double y) nogil: + cdef double dloss(self, double p, double y) noexcept nogil: cdef double z = p * y # approximately equal and saves the computation of the log if z > 18.0: @@ -258,10 +258,10 @@ cdef class Log(Classification): cdef class SquaredLoss(Regression): """Squared loss traditional used in linear regression.""" - cdef double loss(self, double p, double y) nogil: + cdef double loss(self, double p, double y) noexcept nogil: return 0.5 * (p - y) * (p - y) - cdef double dloss(self, double p, double y) nogil: + cdef double dloss(self, double p, double y) noexcept nogil: return p - y def __reduce__(self): @@ -282,7 +282,7 @@ cdef class Huber(Regression): def __init__(self, double c): self.c = c - cdef double loss(self, double p, double y) nogil: + cdef double loss(self, double p, double y) noexcept nogil: cdef double r = p - y cdef double abs_r = fabs(r) if abs_r <= self.c: @@ -290,7 +290,7 @@ cdef class Huber(Regression): else: return self.c * abs_r - (0.5 * self.c * self.c) - cdef double dloss(self, double p, double y) nogil: + cdef double dloss(self, double p, double y) noexcept nogil: cdef double r = p - y cdef double abs_r = fabs(r) if abs_r <= self.c: @@ -315,11 +315,11 @@ cdef class EpsilonInsensitive(Regression): def __init__(self, double epsilon): self.epsilon = epsilon - cdef double loss(self, double p, double y) nogil: + cdef double loss(self, double p, double y) noexcept nogil: cdef double ret = fabs(y - p) - self.epsilon return ret if ret > 0 else 0 - cdef double dloss(self, double p, double y) nogil: + cdef double dloss(self, double p, double y) noexcept nogil: if y - p > self.epsilon: return -1 elif p - y > self.epsilon: @@ -342,11 +342,11 @@ cdef class SquaredEpsilonInsensitive(Regression): def __init__(self, double epsilon): self.epsilon = epsilon - cdef double loss(self, double p, double y) nogil: + cdef double loss(self, double p, double y) noexcept nogil: cdef double ret = fabs(y - p) - self.epsilon return ret * ret if ret > 0 else 0 - cdef double dloss(self, double p, double y) nogil: + cdef double dloss(self, double p, double y) noexcept nogil: cdef double z z = y - p if z > self.epsilon: @@ -682,14 +682,14 @@ def _plain_sgd(const double[::1] weights, ) -cdef bint any_nonfinite(const double *w, int n) nogil: +cdef bint any_nonfinite(const double *w, int n) noexcept nogil: for i in range(n): if not skl_isfinite(w[i]): return True return 0 -cdef double sqnorm(double * x_data_ptr, int * x_ind_ptr, int xnnz) nogil: +cdef double sqnorm(double * x_data_ptr, int * x_ind_ptr, int xnnz) noexcept nogil: cdef double x_norm = 0.0 cdef int j cdef double z @@ -700,7 +700,7 @@ cdef double sqnorm(double * x_data_ptr, int * x_ind_ptr, int xnnz) nogil: cdef void l1penalty(WeightVector w, double * q_data_ptr, - int *x_ind_ptr, int xnnz, double u) nogil: + int *x_ind_ptr, int xnnz, double u) noexcept nogil: """Apply the L1 penalty to each updated feature This implements the truncated gradient approach by diff --git a/sklearn/manifold/_barnes_hut_tsne.pyx b/sklearn/manifold/_barnes_hut_tsne.pyx index d4e658b249a39..4abf9f1c28805 100644 --- a/sklearn/manifold/_barnes_hut_tsne.pyx +++ b/sklearn/manifold/_barnes_hut_tsne.pyx @@ -54,7 +54,7 @@ cdef float compute_gradient(float[:] val_P, long start, long stop, bint compute_error, - int num_threads) nogil: + int num_threads) noexcept nogil: # Having created the tree, calculate the gradient # in two components, the positive and negative forces cdef: @@ -112,7 +112,7 @@ cdef float compute_gradient_positive(float[:] val_P, cnp.int64_t start, int verbose, bint compute_error, - int num_threads) nogil: + int num_threads) noexcept nogil: # Sum over the following expression for i not equal to j # grad_i = p_ij (1 + ||y_i - y_j||^2)^-1 (y_i - y_j) # This is equivalent to compute_edge_forces in the authors' code @@ -177,7 +177,7 @@ cdef double compute_gradient_negative(float[:, :] pos_reference, float theta, long start, long stop, - int num_threads) nogil: + int num_threads) noexcept nogil: if stop == -1: stop = pos_reference.shape[0] cdef: diff --git a/sklearn/metrics/_dist_metrics.pxd.tp b/sklearn/metrics/_dist_metrics.pxd.tp index a4fb7a4057757..cb1aec99b2e9a 100644 --- a/sklearn/metrics/_dist_metrics.pxd.tp +++ b/sklearn/metrics/_dist_metrics.pxd.tp @@ -41,7 +41,7 @@ cdef inline DTYPE_t euclidean_dist{{name_suffix}}( const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, -) nogil except -1: +) except -1 nogil: cdef DTYPE_t tmp, d=0 cdef cnp.intp_t j for j in range(size): @@ -54,7 +54,7 @@ cdef inline DTYPE_t euclidean_rdist{{name_suffix}}( const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, -) nogil except -1: +) except -1 nogil: cdef DTYPE_t tmp, d=0 cdef cnp.intp_t j for j in range(size): @@ -63,11 +63,11 @@ cdef inline DTYPE_t euclidean_rdist{{name_suffix}}( return d -cdef inline DTYPE_t euclidean_dist_to_rdist{{name_suffix}}(const {{INPUT_DTYPE_t}} dist) nogil except -1: +cdef inline DTYPE_t euclidean_dist_to_rdist{{name_suffix}}(const {{INPUT_DTYPE_t}} dist) except -1 nogil: return dist * dist -cdef inline DTYPE_t euclidean_rdist_to_dist{{name_suffix}}(const {{INPUT_DTYPE_t}} dist) nogil except -1: +cdef inline DTYPE_t euclidean_rdist_to_dist{{name_suffix}}(const {{INPUT_DTYPE_t}} dist) except -1 nogil: return sqrt(dist) @@ -90,14 +90,14 @@ cdef class DistanceMetric{{name_suffix}}: const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1 + ) except -1 nogil cdef DTYPE_t rdist( self, const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1 + ) except -1 nogil cdef DTYPE_t dist_csr( self, @@ -110,7 +110,7 @@ cdef class DistanceMetric{{name_suffix}}: const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1 + ) except -1 nogil cdef DTYPE_t rdist_csr( self, @@ -123,7 +123,7 @@ cdef class DistanceMetric{{name_suffix}}: const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1 + ) except -1 nogil cdef int pdist( self, @@ -145,7 +145,7 @@ cdef class DistanceMetric{{name_suffix}}: const SPARSE_INDEX_TYPE_t[:] x1_indptr, const ITYPE_t size, DTYPE_t[:, ::1] D, - ) nogil except -1 + ) except -1 nogil cdef int cdist_csr( self, @@ -157,10 +157,10 @@ cdef class DistanceMetric{{name_suffix}}: const SPARSE_INDEX_TYPE_t[:] x2_indptr, const ITYPE_t size, DTYPE_t[:, ::1] D, - ) nogil except -1 + ) except -1 nogil - cdef DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) nogil except -1 + cdef DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil - cdef DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) nogil except -1 + cdef DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil {{endfor}} diff --git a/sklearn/metrics/_dist_metrics.pyx.tp b/sklearn/metrics/_dist_metrics.pyx.tp index f3f7ce402e64b..3c6c38f052bee 100644 --- a/sklearn/metrics/_dist_metrics.pyx.tp +++ b/sklearn/metrics/_dist_metrics.pyx.tp @@ -43,7 +43,7 @@ from ..utils._typedefs import DTYPE, ITYPE from ..utils import check_array from ..utils.fixes import parse_version, sp_base_version -cdef inline double fmax(double a, double b) nogil: +cdef inline double fmax(double a, double b) noexcept nogil: return max(a, b) @@ -335,7 +335,7 @@ cdef class DistanceMetric{{name_suffix}}: const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: """Compute the distance between vectors x1 and x2 This should be overridden in a base class. @@ -347,7 +347,7 @@ cdef class DistanceMetric{{name_suffix}}: const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: """Compute the rank-preserving surrogate distance between vectors x1 and x2. This can optionally be overridden in a base class. @@ -399,7 +399,7 @@ cdef class DistanceMetric{{name_suffix}}: const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: """Compute the distance between vectors x1 and x2 represented under the CSR format. @@ -424,7 +424,7 @@ cdef class DistanceMetric{{name_suffix}}: const SPARSE_INDEX_TYPE_t[:] x1_indices, const {{INPUT_DTYPE_t}}* x2_data, const SPARSE_INDEX_TYPE_t[:] x2_indices, - ) nogil except -1: + ) except -1 nogil: Where callers would use slicing on the original CSR data and indices memoryviews: @@ -465,7 +465,7 @@ cdef class DistanceMetric{{name_suffix}}: const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: """Distance between rows of CSR matrices x1 and x2. This can optionally be overridden in a subclass. @@ -502,7 +502,7 @@ cdef class DistanceMetric{{name_suffix}}: const SPARSE_INDEX_TYPE_t[:] x1_indptr, const ITYPE_t size, DTYPE_t[:, ::1] D, - ) nogil except -1: + ) except -1 nogil: """Pairwise distances between rows in CSR matrix X. Note that this implementation is twice faster than cdist_csr(X, X) @@ -542,7 +542,7 @@ cdef class DistanceMetric{{name_suffix}}: const SPARSE_INDEX_TYPE_t[:] x2_indptr, const ITYPE_t size, DTYPE_t[:, ::1] D, - ) nogil except -1: + ) except -1 nogil: """Compute the cross-pairwise distances between arrays X and Y represented in the CSR format.""" cdef: @@ -571,11 +571,11 @@ cdef class DistanceMetric{{name_suffix}}: ) return 0 - cdef DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) nogil except -1: + cdef DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: """Convert the rank-preserving surrogate distance to the distance""" return rdist - cdef DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) nogil except -1: + cdef DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: """Convert the distance to the rank-preserving surrogate distance""" return dist @@ -869,20 +869,20 @@ cdef class EuclideanDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return euclidean_dist{{name_suffix}}(x1, x2, size) cdef inline DTYPE_t rdist(self, const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return euclidean_rdist{{name_suffix}}(x1, x2, size) - cdef inline DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) nogil except -1: + cdef inline DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: return sqrt(rdist) - cdef inline DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) nogil except -1: + cdef inline DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: return dist * dist def rdist_to_dist(self, rdist): @@ -902,7 +902,7 @@ cdef class EuclideanDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -954,7 +954,7 @@ cdef class EuclideanDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return sqrt( self.rdist_csr( x1_data, @@ -991,7 +991,7 @@ cdef class SEuclideanDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef DTYPE_t tmp, d=0 cdef cnp.intp_t j for j in range(size): @@ -1004,13 +1004,13 @@ cdef class SEuclideanDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return sqrt(self.rdist(x1, x2, size)) - cdef inline DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) nogil except -1: + cdef inline DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: return sqrt(rdist) - cdef inline DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) nogil except -1: + cdef inline DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: return dist * dist def rdist_to_dist(self, rdist): @@ -1030,7 +1030,7 @@ cdef class SEuclideanDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -1083,7 +1083,7 @@ cdef class SEuclideanDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return sqrt( self.rdist_csr( x1_data, @@ -1114,7 +1114,7 @@ cdef class ManhattanDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef DTYPE_t d = 0 cdef cnp.intp_t j for j in range(size): @@ -1132,7 +1132,7 @@ cdef class ManhattanDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -1197,7 +1197,7 @@ cdef class ChebyshevDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef DTYPE_t d = 0 cdef cnp.intp_t j for j in range(size): @@ -1216,7 +1216,7 @@ cdef class ChebyshevDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -1310,7 +1310,7 @@ cdef class MinkowskiDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef DTYPE_t d=0 cdef cnp.intp_t j cdef bint has_w = self.size > 0 @@ -1327,13 +1327,13 @@ cdef class MinkowskiDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return pow(self.rdist(x1, x2, size), 1. / self.p) - cdef inline DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) nogil except -1: + cdef inline DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: return pow(rdist, 1. / self.p) - cdef inline DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) nogil except -1: + cdef inline DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: return pow(dist, self.p) def rdist_to_dist(self, rdist): @@ -1353,7 +1353,7 @@ cdef class MinkowskiDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -1433,7 +1433,7 @@ cdef class MinkowskiDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return pow( self.rdist_csr( x1_data, @@ -1498,7 +1498,7 @@ cdef class WMinkowskiDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef DTYPE_t d = 0 cdef cnp.intp_t j @@ -1511,13 +1511,13 @@ cdef class WMinkowskiDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return pow(self.rdist(x1, x2, size), 1. / self.p) - cdef inline DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) nogil except -1: + cdef inline DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: return pow(rdist, 1. / self.p) - cdef inline DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) nogil except -1: + cdef inline DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: return pow(dist, self.p) def rdist_to_dist(self, rdist): @@ -1537,7 +1537,7 @@ cdef class WMinkowskiDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -1587,7 +1587,7 @@ cdef class WMinkowskiDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return pow( self.rdist_csr( x1_data, @@ -1653,7 +1653,7 @@ cdef class MahalanobisDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef DTYPE_t tmp, d = 0 cdef cnp.intp_t i, j @@ -1673,13 +1673,13 @@ cdef class MahalanobisDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return sqrt(self.rdist(x1, x2, size)) - cdef inline DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) nogil except -1: + cdef inline DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: return sqrt(rdist) - cdef inline DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) nogil except -1: + cdef inline DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: return dist * dist def rdist_to_dist(self, rdist): @@ -1699,7 +1699,7 @@ cdef class MahalanobisDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -1753,7 +1753,7 @@ cdef class MahalanobisDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return sqrt( self.rdist_csr( x1_data, @@ -1784,7 +1784,7 @@ cdef class HammingDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef int n_unequal = 0 cdef cnp.intp_t j for j in range(size): @@ -1804,7 +1804,7 @@ cdef class HammingDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -1859,7 +1859,7 @@ cdef class CanberraDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef DTYPE_t denom, d = 0 cdef cnp.intp_t j for j in range(size): @@ -1879,7 +1879,7 @@ cdef class CanberraDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -1934,7 +1934,7 @@ cdef class BrayCurtisDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef DTYPE_t num = 0, denom = 0 cdef cnp.intp_t j for j in range(size): @@ -1956,7 +1956,7 @@ cdef class BrayCurtisDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -2014,7 +2014,7 @@ cdef class JaccardDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef int tf1, tf2, n_eq = 0, nnz = 0 cdef cnp.intp_t j for j in range(size): @@ -2040,7 +2040,7 @@ cdef class JaccardDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -2103,7 +2103,7 @@ cdef class MatchingDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef int tf1, tf2, n_neq = 0 cdef cnp.intp_t j for j in range(size): @@ -2123,7 +2123,7 @@ cdef class MatchingDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -2178,7 +2178,7 @@ cdef class DiceDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef int tf1, tf2, n_neq = 0, n_tt = 0 cdef cnp.intp_t j for j in range(size): @@ -2199,7 +2199,7 @@ cdef class DiceDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -2259,7 +2259,7 @@ cdef class KulsinskiDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef int tf1, tf2, n_tt = 0, n_neq = 0 cdef cnp.intp_t j for j in range(size): @@ -2280,7 +2280,7 @@ cdef class KulsinskiDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -2338,7 +2338,7 @@ cdef class RogersTanimotoDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef int tf1, tf2, n_neq = 0 cdef cnp.intp_t j for j in range(size): @@ -2358,7 +2358,7 @@ cdef class RogersTanimotoDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -2415,7 +2415,7 @@ cdef class RussellRaoDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef int tf1, tf2, n_tt = 0 cdef cnp.intp_t j for j in range(size): @@ -2435,7 +2435,7 @@ cdef class RussellRaoDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -2485,7 +2485,7 @@ cdef class SokalMichenerDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef int tf1, tf2, n_neq = 0 cdef cnp.intp_t j for j in range(size): @@ -2505,7 +2505,7 @@ cdef class SokalMichenerDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -2562,7 +2562,7 @@ cdef class SokalSneathDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef int tf1, tf2, n_tt = 0, n_neq = 0 cdef cnp.intp_t j for j in range(size): @@ -2583,7 +2583,7 @@ cdef class SokalSneathDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -2650,7 +2650,7 @@ cdef class HaversineDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef DTYPE_t sin_0 = sin(0.5 * ((x1[0]) - (x2[0]))) cdef DTYPE_t sin_1 = sin(0.5 * ((x1[1]) - (x2[1]))) return (sin_0 * sin_0 + cos(x1[0]) * cos(x2[0]) * sin_1 * sin_1) @@ -2659,13 +2659,13 @@ cdef class HaversineDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return 2 * asin(sqrt(self.rdist(x1, x2, size))) - cdef inline DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) nogil except -1: + cdef inline DTYPE_t _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: return 2 * asin(sqrt(rdist)) - cdef inline DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) nogil except -1: + cdef inline DTYPE_t _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: cdef DTYPE_t tmp = sin(0.5 * dist) return tmp * tmp @@ -2687,7 +2687,7 @@ cdef class HaversineDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return 2 * asin(sqrt(self.rdist_csr( x1_data, x1_indices, @@ -2711,7 +2711,7 @@ cdef class HaversineDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const SPARSE_INDEX_TYPE_t x2_start, const SPARSE_INDEX_TYPE_t x2_end, const ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: cdef: cnp.npy_intp ix1, ix2 @@ -2797,7 +2797,7 @@ cdef class PyFuncDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, ITYPE_t size, - ) nogil except -1: + ) except -1 nogil: return self._dist(x1, x2, size) cdef inline DTYPE_t _dist( diff --git a/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pyx.tp b/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pyx.tp index b8afe5c3cd5f8..246fa90f532fd 100644 --- a/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pyx.tp +++ b/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pyx.tp @@ -150,7 +150,7 @@ cdef class ArgKmin{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: cdef: ITYPE_t i, j ITYPE_t n_samples_X = X_end - X_start @@ -175,7 +175,7 @@ cdef class ArgKmin{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: # As this strategy is embarrassingly parallel, we can set each # thread's heaps pointer to the proper position on the main heaps. self.heaps_r_distances_chunks[thread_num] = &self.argkmin_distances[X_start, 0] @@ -187,7 +187,7 @@ cdef class ArgKmin{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: cdef: ITYPE_t idx @@ -202,7 +202,7 @@ cdef class ArgKmin{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): cdef void _parallel_on_Y_init( self, - ) nogil: + ) noexcept nogil: cdef: # Maximum number of scalar elements (the last chunks can be smaller) ITYPE_t heaps_size = self.X_n_samples_chunk * self.k @@ -230,7 +230,7 @@ cdef class ArgKmin{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: # Initialising heaps (memset can't be used here) for idx in range(self.X_n_samples_chunk * self.k): self.heaps_r_distances_chunks[thread_num][idx] = DBL_MAX @@ -241,7 +241,7 @@ cdef class ArgKmin{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): self, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: cdef: ITYPE_t idx, jdx, thread_num with nogil, parallel(num_threads=self.effective_n_threads): @@ -265,7 +265,7 @@ cdef class ArgKmin{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): cdef void _parallel_on_Y_finalize( self, - ) nogil: + ) noexcept nogil: cdef: ITYPE_t idx, thread_num @@ -285,7 +285,7 @@ cdef class ArgKmin{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): ) return - cdef void compute_exact_distances(self) nogil: + cdef void compute_exact_distances(self) noexcept nogil: cdef: ITYPE_t i, j DTYPE_t[:, ::1] distances = self.argkmin_distances @@ -393,7 +393,7 @@ cdef class EuclideanArgKmin{{name_suffix}}(ArgKmin{{name_suffix}}): self.use_squared_distances = use_squared_distances @final - cdef void compute_exact_distances(self) nogil: + cdef void compute_exact_distances(self) noexcept nogil: if not self.use_squared_distances: ArgKmin{{name_suffix}}.compute_exact_distances(self) @@ -401,7 +401,7 @@ cdef class EuclideanArgKmin{{name_suffix}}(ArgKmin{{name_suffix}}): cdef void _parallel_on_X_parallel_init( self, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: ArgKmin{{name_suffix}}._parallel_on_X_parallel_init(self, thread_num) self.middle_term_computer._parallel_on_X_parallel_init(thread_num) @@ -411,7 +411,7 @@ cdef class EuclideanArgKmin{{name_suffix}}(ArgKmin{{name_suffix}}): ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: ArgKmin{{name_suffix}}._parallel_on_X_init_chunk(self, thread_num, X_start, X_end) self.middle_term_computer._parallel_on_X_init_chunk(thread_num, X_start, X_end) @@ -423,7 +423,7 @@ cdef class EuclideanArgKmin{{name_suffix}}(ArgKmin{{name_suffix}}): ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: ArgKmin{{name_suffix}}._parallel_on_X_pre_compute_and_reduce_distances_on_chunks( self, X_start, X_end, @@ -437,7 +437,7 @@ cdef class EuclideanArgKmin{{name_suffix}}(ArgKmin{{name_suffix}}): @final cdef void _parallel_on_Y_init( self, - ) nogil: + ) noexcept nogil: ArgKmin{{name_suffix}}._parallel_on_Y_init(self) self.middle_term_computer._parallel_on_Y_init() @@ -447,7 +447,7 @@ cdef class EuclideanArgKmin{{name_suffix}}(ArgKmin{{name_suffix}}): ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: ArgKmin{{name_suffix}}._parallel_on_Y_parallel_init(self, thread_num, X_start, X_end) self.middle_term_computer._parallel_on_Y_parallel_init(thread_num, X_start, X_end) @@ -459,7 +459,7 @@ cdef class EuclideanArgKmin{{name_suffix}}(ArgKmin{{name_suffix}}): ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: ArgKmin{{name_suffix}}._parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( self, X_start, X_end, @@ -478,7 +478,7 @@ cdef class EuclideanArgKmin{{name_suffix}}(ArgKmin{{name_suffix}}): ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: cdef: ITYPE_t i, j DTYPE_t sqeuclidean_dist_i_j diff --git a/sklearn/metrics/_pairwise_distances_reduction/_base.pxd.tp b/sklearn/metrics/_pairwise_distances_reduction/_base.pxd.tp index be44f3a98a263..4ce12e6a8f6df 100644 --- a/sklearn/metrics/_pairwise_distances_reduction/_base.pxd.tp +++ b/sklearn/metrics/_pairwise_distances_reduction/_base.pxd.tp @@ -53,10 +53,10 @@ cdef class BaseDistancesReduction{{name_suffix}}: bint execute_in_parallel_on_Y @final - cdef void _parallel_on_X(self) nogil + cdef void _parallel_on_X(self) noexcept nogil @final - cdef void _parallel_on_Y(self) nogil + cdef void _parallel_on_Y(self) noexcept nogil # Placeholder methods which have to be implemented @@ -67,24 +67,24 @@ cdef class BaseDistancesReduction{{name_suffix}}: ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil + ) noexcept nogil # Placeholder methods which can be implemented - cdef void compute_exact_distances(self) nogil + cdef void compute_exact_distances(self) noexcept nogil cdef void _parallel_on_X_parallel_init( self, ITYPE_t thread_num, - ) nogil + ) noexcept nogil cdef void _parallel_on_X_init_chunk( self, ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil + ) noexcept nogil cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( self, @@ -93,30 +93,30 @@ cdef class BaseDistancesReduction{{name_suffix}}: ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil + ) noexcept nogil cdef void _parallel_on_X_prange_iter_finalize( self, ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil + ) noexcept nogil cdef void _parallel_on_X_parallel_finalize( self, ITYPE_t thread_num - ) nogil + ) noexcept nogil cdef void _parallel_on_Y_init( self, - ) nogil + ) noexcept nogil cdef void _parallel_on_Y_parallel_init( self, ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil + ) noexcept nogil cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( self, @@ -125,15 +125,15 @@ cdef class BaseDistancesReduction{{name_suffix}}: ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil + ) noexcept nogil cdef void _parallel_on_Y_synchronize( self, ITYPE_t X_start, ITYPE_t X_end, - ) nogil + ) noexcept nogil cdef void _parallel_on_Y_finalize( self, - ) nogil + ) noexcept nogil {{endfor}} diff --git a/sklearn/metrics/_pairwise_distances_reduction/_base.pyx.tp b/sklearn/metrics/_pairwise_distances_reduction/_base.pyx.tp index 1b2a8a31fb679..dec1e96dbbb9f 100644 --- a/sklearn/metrics/_pairwise_distances_reduction/_base.pyx.tp +++ b/sklearn/metrics/_pairwise_distances_reduction/_base.pyx.tp @@ -224,7 +224,7 @@ cdef class BaseDistancesReduction{{name_suffix}}: ) @final - cdef void _parallel_on_X(self) nogil: + cdef void _parallel_on_X(self) noexcept nogil: """Perform computation and reduction in parallel on chunks of X. This strategy dispatches tasks statically on threads. Each task @@ -291,7 +291,7 @@ cdef class BaseDistancesReduction{{name_suffix}}: return @final - cdef void _parallel_on_Y(self) nogil: + cdef void _parallel_on_Y(self) noexcept nogil: """Perform computation and reduction in parallel on chunks of Y. This strategy is a sequence of embarrassingly parallel subtasks: @@ -368,7 +368,7 @@ cdef class BaseDistancesReduction{{name_suffix}}: ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: """Compute the pairwise distances on two chunks of X and Y and reduce them. This is THE core computational method of BaseDistancesReduction{{name_suffix}}. @@ -386,14 +386,14 @@ cdef class BaseDistancesReduction{{name_suffix}}: # Placeholder methods which can be implemented - cdef void compute_exact_distances(self) nogil: + cdef void compute_exact_distances(self) noexcept nogil: """Convert rank-preserving distances to exact distances or recompute them.""" return cdef void _parallel_on_X_parallel_init( self, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: """Allocate datastructures used in a thread given its number.""" return @@ -402,7 +402,7 @@ cdef class BaseDistancesReduction{{name_suffix}}: ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: """Initialize datastructures used in a thread given its number. In this method, EuclideanDistance specialisations of subclass of @@ -425,7 +425,7 @@ cdef class BaseDistancesReduction{{name_suffix}}: ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: """Initialize datastructures just before the _compute_and_reduce_distances_on_chunks. In this method, EuclideanDistance specialisations of subclass of @@ -446,20 +446,20 @@ cdef class BaseDistancesReduction{{name_suffix}}: ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: """Interact with datastructures after a reduction on chunks.""" return cdef void _parallel_on_X_parallel_finalize( self, ITYPE_t thread_num - ) nogil: + ) noexcept nogil: """Interact with datastructures after executing all the reductions.""" return cdef void _parallel_on_Y_init( self, - ) nogil: + ) noexcept nogil: """Allocate datastructures used in all threads.""" return @@ -468,7 +468,7 @@ cdef class BaseDistancesReduction{{name_suffix}}: ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: """Initialize datastructures used in a thread given its number. In this method, EuclideanDistance specialisations of subclass of @@ -491,7 +491,7 @@ cdef class BaseDistancesReduction{{name_suffix}}: ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: """Initialize datastructures just before the _compute_and_reduce_distances_on_chunks. In this method, EuclideanDistance specialisations of subclass of @@ -511,13 +511,13 @@ cdef class BaseDistancesReduction{{name_suffix}}: self, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: """Update thread datastructures before leaving a parallel region.""" return cdef void _parallel_on_Y_finalize( self, - ) nogil: + ) noexcept nogil: """Update datastructures after executing all the reductions.""" return diff --git a/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pxd.tp b/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pxd.tp index e220f730e7529..416263d1c3134 100644 --- a/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pxd.tp +++ b/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pxd.tp @@ -25,13 +25,13 @@ cdef class DatasetsPair{{name_suffix}}: {{DistanceMetric}} distance_metric ITYPE_t n_features - cdef ITYPE_t n_samples_X(self) nogil + cdef ITYPE_t n_samples_X(self) noexcept nogil - cdef ITYPE_t n_samples_Y(self) nogil + cdef ITYPE_t n_samples_Y(self) noexcept nogil - cdef DTYPE_t dist(self, ITYPE_t i, ITYPE_t j) nogil + cdef DTYPE_t dist(self, ITYPE_t i, ITYPE_t j) noexcept nogil - cdef DTYPE_t surrogate_dist(self, ITYPE_t i, ITYPE_t j) nogil + cdef DTYPE_t surrogate_dist(self, ITYPE_t i, ITYPE_t j) noexcept nogil cdef class DenseDenseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): diff --git a/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pyx.tp b/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pyx.tp index 78857341f9c97..5442d2883ac5b 100644 --- a/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pyx.tp +++ b/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pyx.tp @@ -134,24 +134,24 @@ cdef class DatasetsPair{{name_suffix}}: self.distance_metric = distance_metric self.n_features = n_features - cdef ITYPE_t n_samples_X(self) nogil: + cdef ITYPE_t n_samples_X(self) noexcept nogil: """Number of samples in X.""" # This is a abstract method. # This _must_ always be overwritten in subclasses. # TODO: add "with gil: raise" here when supporting Cython 3.0 return -999 - cdef ITYPE_t n_samples_Y(self) nogil: + cdef ITYPE_t n_samples_Y(self) noexcept nogil: """Number of samples in Y.""" # This is a abstract method. # This _must_ always be overwritten in subclasses. # TODO: add "with gil: raise" here when supporting Cython 3.0 return -999 - cdef DTYPE_t surrogate_dist(self, ITYPE_t i, ITYPE_t j) nogil: + cdef DTYPE_t surrogate_dist(self, ITYPE_t i, ITYPE_t j) noexcept nogil: return self.dist(i, j) - cdef DTYPE_t dist(self, ITYPE_t i, ITYPE_t j) nogil: + cdef DTYPE_t dist(self, ITYPE_t i, ITYPE_t j) noexcept nogil: # This is a abstract method. # This _must_ always be overwritten in subclasses. # TODO: add "with gil: raise" here when supporting Cython 3.0 @@ -186,19 +186,19 @@ cdef class DenseDenseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): self.Y = Y @final - cdef ITYPE_t n_samples_X(self) nogil: + cdef ITYPE_t n_samples_X(self) noexcept nogil: return self.X.shape[0] @final - cdef ITYPE_t n_samples_Y(self) nogil: + cdef ITYPE_t n_samples_Y(self) noexcept nogil: return self.Y.shape[0] @final - cdef DTYPE_t surrogate_dist(self, ITYPE_t i, ITYPE_t j) nogil: + cdef DTYPE_t surrogate_dist(self, ITYPE_t i, ITYPE_t j) noexcept nogil: return self.distance_metric.rdist(&self.X[i, 0], &self.Y[j, 0], self.n_features) @final - cdef DTYPE_t dist(self, ITYPE_t i, ITYPE_t j) nogil: + cdef DTYPE_t dist(self, ITYPE_t i, ITYPE_t j) noexcept nogil: return self.distance_metric.dist(&self.X[i, 0], &self.Y[j, 0], self.n_features) @@ -226,15 +226,15 @@ cdef class SparseSparseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): self.Y_data, self.Y_indices, self.Y_indptr = self.unpack_csr_matrix(Y) @final - cdef ITYPE_t n_samples_X(self) nogil: + cdef ITYPE_t n_samples_X(self) noexcept nogil: return self.X_indptr.shape[0] - 1 @final - cdef ITYPE_t n_samples_Y(self) nogil: + cdef ITYPE_t n_samples_Y(self) noexcept nogil: return self.Y_indptr.shape[0] - 1 @final - cdef DTYPE_t surrogate_dist(self, ITYPE_t i, ITYPE_t j) nogil: + cdef DTYPE_t surrogate_dist(self, ITYPE_t i, ITYPE_t j) noexcept nogil: return self.distance_metric.rdist_csr( x1_data=&self.X_data[0], x1_indices=self.X_indices, @@ -248,7 +248,7 @@ cdef class SparseSparseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): ) @final - cdef DTYPE_t dist(self, ITYPE_t i, ITYPE_t j) nogil: + cdef DTYPE_t dist(self, ITYPE_t i, ITYPE_t j) noexcept nogil: return self.distance_metric.dist_csr( x1_data=&self.X_data[0], x1_indices=self.X_indices, @@ -319,15 +319,15 @@ cdef class SparseDenseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): self.Y_indices = np.arange(self.n_features, dtype=SPARSE_INDEX_TYPE) @final - cdef ITYPE_t n_samples_X(self) nogil: + cdef ITYPE_t n_samples_X(self) noexcept nogil: return self.X_indptr.shape[0] - 1 @final - cdef ITYPE_t n_samples_Y(self) nogil: + cdef ITYPE_t n_samples_Y(self) noexcept nogil: return self.n_Y @final - cdef DTYPE_t surrogate_dist(self, ITYPE_t i, ITYPE_t j) nogil: + cdef DTYPE_t surrogate_dist(self, ITYPE_t i, ITYPE_t j) noexcept nogil: return self.distance_metric.rdist_csr( x1_data=&self.X_data[0], x1_indices=self.X_indices, @@ -343,7 +343,7 @@ cdef class SparseDenseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): ) @final - cdef DTYPE_t dist(self, ITYPE_t i, ITYPE_t j) nogil: + cdef DTYPE_t dist(self, ITYPE_t i, ITYPE_t j) noexcept nogil: return self.distance_metric.dist_csr( x1_data=&self.X_data[0], @@ -383,22 +383,22 @@ cdef class DenseSparseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): self.datasets_pair = SparseDenseDatasetsPair{{name_suffix}}(Y, X, distance_metric) @final - cdef ITYPE_t n_samples_X(self) nogil: + cdef ITYPE_t n_samples_X(self) noexcept nogil: # Swapping interface return self.datasets_pair.n_samples_Y() @final - cdef ITYPE_t n_samples_Y(self) nogil: + cdef ITYPE_t n_samples_Y(self) noexcept nogil: # Swapping interface return self.datasets_pair.n_samples_X() @final - cdef DTYPE_t surrogate_dist(self, ITYPE_t i, ITYPE_t j) nogil: + cdef DTYPE_t surrogate_dist(self, ITYPE_t i, ITYPE_t j) noexcept nogil: # Swapping arguments on the same interface return self.datasets_pair.surrogate_dist(j, i) @final - cdef DTYPE_t dist(self, ITYPE_t i, ITYPE_t j) nogil: + cdef DTYPE_t dist(self, ITYPE_t i, ITYPE_t j) noexcept nogil: # Swapping arguments on the same interface return self.datasets_pair.dist(j, i) diff --git a/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pxd.tp b/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pxd.tp index e6ef5de2727b5..da158199201f2 100644 --- a/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pxd.tp +++ b/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pxd.tp @@ -32,7 +32,7 @@ cdef void _middle_term_sparse_sparse_64( ITYPE_t Y_start, ITYPE_t Y_end, DTYPE_t * D, -) nogil +) noexcept nogil {{for name_suffix, upcast_to_float64, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}} @@ -56,25 +56,25 @@ cdef class MiddleTermComputer{{name_suffix}}: ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil + ) noexcept nogil - cdef void _parallel_on_X_parallel_init(self, ITYPE_t thread_num) nogil + cdef void _parallel_on_X_parallel_init(self, ITYPE_t thread_num) noexcept nogil cdef void _parallel_on_X_init_chunk( self, ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil + ) noexcept nogil - cdef void _parallel_on_Y_init(self) nogil + cdef void _parallel_on_Y_init(self) noexcept nogil cdef void _parallel_on_Y_parallel_init( self, ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil + ) noexcept nogil cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( self, @@ -83,7 +83,7 @@ cdef class MiddleTermComputer{{name_suffix}}: ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num - ) nogil + ) noexcept nogil cdef DTYPE_t * _compute_dist_middle_terms( self, @@ -92,7 +92,7 @@ cdef class MiddleTermComputer{{name_suffix}}: ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil + ) noexcept nogil cdef class DenseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_suffix}}): @@ -113,21 +113,21 @@ cdef class DenseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_ ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil + ) noexcept nogil cdef void _parallel_on_X_init_chunk( self, ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil + ) noexcept nogil cdef void _parallel_on_Y_parallel_init( self, ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil + ) noexcept nogil cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( self, @@ -136,7 +136,7 @@ cdef class DenseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_ ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num - ) nogil + ) noexcept nogil cdef DTYPE_t * _compute_dist_middle_terms( self, @@ -145,7 +145,7 @@ cdef class DenseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_ ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil + ) noexcept nogil cdef class SparseSparseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_suffix}}): @@ -165,7 +165,7 @@ cdef class SparseSparseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{nam ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num - ) nogil + ) noexcept nogil cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( self, @@ -174,7 +174,7 @@ cdef class SparseSparseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{nam ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num - ) nogil + ) noexcept nogil cdef DTYPE_t * _compute_dist_middle_terms( self, @@ -183,7 +183,7 @@ cdef class SparseSparseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{nam ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil + ) noexcept nogil {{endfor}} diff --git a/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pyx.tp b/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pyx.tp index dd8b205c753e0..79a15d0fd6e26 100644 --- a/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pyx.tp +++ b/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pyx.tp @@ -50,7 +50,7 @@ cdef void _middle_term_sparse_sparse_64( ITYPE_t Y_start, ITYPE_t Y_end, DTYPE_t * D, -) nogil: +) noexcept nogil: # This routine assumes that D points to the first element of a # zeroed buffer of length at least equal to n_X × n_Y, conceptually # representing a 2-d C-ordered array. @@ -180,10 +180,10 @@ cdef class MiddleTermComputer{{name_suffix}}: ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: return - cdef void _parallel_on_X_parallel_init(self, ITYPE_t thread_num) nogil: + cdef void _parallel_on_X_parallel_init(self, ITYPE_t thread_num) noexcept nogil: self.dist_middle_terms_chunks[thread_num].resize(self.dist_middle_terms_chunks_size) cdef void _parallel_on_X_init_chunk( @@ -191,10 +191,10 @@ cdef class MiddleTermComputer{{name_suffix}}: ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: return - cdef void _parallel_on_Y_init(self) nogil: + cdef void _parallel_on_Y_init(self) noexcept nogil: for thread_num in range(self.chunks_n_threads): self.dist_middle_terms_chunks[thread_num].resize( self.dist_middle_terms_chunks_size @@ -205,7 +205,7 @@ cdef class MiddleTermComputer{{name_suffix}}: ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: return cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( @@ -215,7 +215,7 @@ cdef class MiddleTermComputer{{name_suffix}}: ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num - ) nogil: + ) noexcept nogil: return cdef DTYPE_t * _compute_dist_middle_terms( @@ -225,7 +225,7 @@ cdef class MiddleTermComputer{{name_suffix}}: ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: return NULL @@ -278,7 +278,7 @@ cdef class DenseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_ ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: {{if upcast_to_float64}} cdef: ITYPE_t i, j @@ -297,7 +297,7 @@ cdef class DenseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_ ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: {{if upcast_to_float64}} cdef: ITYPE_t i, j @@ -316,7 +316,7 @@ cdef class DenseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_ ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: {{if upcast_to_float64}} cdef: ITYPE_t i, j @@ -337,7 +337,7 @@ cdef class DenseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_ ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num - ) nogil: + ) noexcept nogil: {{if upcast_to_float64}} cdef: ITYPE_t i, j @@ -358,7 +358,7 @@ cdef class DenseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_ ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: cdef: DTYPE_t *dist_middle_terms = self.dist_middle_terms_chunks[thread_num].data() @@ -434,7 +434,7 @@ cdef class SparseSparseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{nam ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: # Flush the thread dist_middle_terms_chunks to 0.0 fill( self.dist_middle_terms_chunks[thread_num].begin(), @@ -449,7 +449,7 @@ cdef class SparseSparseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{nam ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: # Flush the thread dist_middle_terms_chunks to 0.0 fill( self.dist_middle_terms_chunks[thread_num].begin(), @@ -464,7 +464,7 @@ cdef class SparseSparseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{nam ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: cdef: DTYPE_t *dist_middle_terms = ( self.dist_middle_terms_chunks[thread_num].data() diff --git a/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pxd.tp b/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pxd.tp index b6e4508468d2b..4f333327a6c52 100644 --- a/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pxd.tp +++ b/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pxd.tp @@ -75,7 +75,7 @@ cdef class RadiusNeighbors{{name_suffix}}(BaseDistancesReduction{{name_suffix}}) self, ITYPE_t idx, ITYPE_t num_threads, - ) nogil + ) noexcept nogil cdef class EuclideanRadiusNeighbors{{name_suffix}}(RadiusNeighbors{{name_suffix}}): diff --git a/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pyx.tp b/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pyx.tp index b3f20cac3ea08..59c05cb90c839 100644 --- a/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pyx.tp +++ b/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pyx.tp @@ -172,7 +172,7 @@ cdef class RadiusNeighbors{{name_suffix}}(BaseDistancesReduction{{name_suffix}}) ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: cdef: ITYPE_t i, j DTYPE_t r_dist_i_j @@ -201,7 +201,7 @@ cdef class RadiusNeighbors{{name_suffix}}(BaseDistancesReduction{{name_suffix}}) ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: # As this strategy is embarrassingly parallel, we can set the # thread vectors' pointers to the main vectors'. @@ -214,7 +214,7 @@ cdef class RadiusNeighbors{{name_suffix}}(BaseDistancesReduction{{name_suffix}}) ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: cdef: ITYPE_t idx @@ -229,7 +229,7 @@ cdef class RadiusNeighbors{{name_suffix}}(BaseDistancesReduction{{name_suffix}}) cdef void _parallel_on_Y_init( self, - ) nogil: + ) noexcept nogil: cdef: ITYPE_t thread_num # As chunks of X are shared across threads, so must datastructures to avoid race @@ -244,7 +244,7 @@ cdef class RadiusNeighbors{{name_suffix}}(BaseDistancesReduction{{name_suffix}}) self, ITYPE_t idx, ITYPE_t num_threads, - ) nogil: + ) noexcept nogil: cdef: ITYPE_t thread_num ITYPE_t idx_n_elements = 0 @@ -274,7 +274,7 @@ cdef class RadiusNeighbors{{name_suffix}}(BaseDistancesReduction{{name_suffix}}) cdef void _parallel_on_Y_finalize( self, - ) nogil: + ) noexcept nogil: cdef: ITYPE_t idx @@ -300,7 +300,7 @@ cdef class RadiusNeighbors{{name_suffix}}(BaseDistancesReduction{{name_suffix}}) return - cdef void compute_exact_distances(self) nogil: + cdef void compute_exact_distances(self) noexcept nogil: """Convert rank-preserving distances to pairwise distances in parallel.""" cdef: ITYPE_t i, j @@ -408,7 +408,7 @@ cdef class EuclideanRadiusNeighbors{{name_suffix}}(RadiusNeighbors{{name_suffix} cdef void _parallel_on_X_parallel_init( self, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: RadiusNeighbors{{name_suffix}}._parallel_on_X_parallel_init(self, thread_num) self.middle_term_computer._parallel_on_X_parallel_init(thread_num) @@ -418,7 +418,7 @@ cdef class EuclideanRadiusNeighbors{{name_suffix}}(RadiusNeighbors{{name_suffix} ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: RadiusNeighbors{{name_suffix}}._parallel_on_X_init_chunk(self, thread_num, X_start, X_end) self.middle_term_computer._parallel_on_X_init_chunk(thread_num, X_start, X_end) @@ -430,7 +430,7 @@ cdef class EuclideanRadiusNeighbors{{name_suffix}}(RadiusNeighbors{{name_suffix} ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: RadiusNeighbors{{name_suffix}}._parallel_on_X_pre_compute_and_reduce_distances_on_chunks( self, X_start, X_end, @@ -444,7 +444,7 @@ cdef class EuclideanRadiusNeighbors{{name_suffix}}(RadiusNeighbors{{name_suffix} @final cdef void _parallel_on_Y_init( self, - ) nogil: + ) noexcept nogil: RadiusNeighbors{{name_suffix}}._parallel_on_Y_init(self) self.middle_term_computer._parallel_on_Y_init() @@ -454,7 +454,7 @@ cdef class EuclideanRadiusNeighbors{{name_suffix}}(RadiusNeighbors{{name_suffix} ITYPE_t thread_num, ITYPE_t X_start, ITYPE_t X_end, - ) nogil: + ) noexcept nogil: RadiusNeighbors{{name_suffix}}._parallel_on_Y_parallel_init(self, thread_num, X_start, X_end) self.middle_term_computer._parallel_on_Y_parallel_init(thread_num, X_start, X_end) @@ -466,7 +466,7 @@ cdef class EuclideanRadiusNeighbors{{name_suffix}}(RadiusNeighbors{{name_suffix} ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: RadiusNeighbors{{name_suffix}}._parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( self, X_start, X_end, @@ -478,7 +478,7 @@ cdef class EuclideanRadiusNeighbors{{name_suffix}}(RadiusNeighbors{{name_suffix} ) @final - cdef void compute_exact_distances(self) nogil: + cdef void compute_exact_distances(self) noexcept nogil: if not self.use_squared_distances: RadiusNeighbors{{name_suffix}}.compute_exact_distances(self) @@ -490,7 +490,7 @@ cdef class EuclideanRadiusNeighbors{{name_suffix}}(RadiusNeighbors{{name_suffix} ITYPE_t Y_start, ITYPE_t Y_end, ITYPE_t thread_num, - ) nogil: + ) noexcept nogil: cdef: ITYPE_t i, j DTYPE_t sqeuclidean_dist_i_j diff --git a/sklearn/neighbors/_ball_tree.pyx b/sklearn/neighbors/_ball_tree.pyx index 6dcc6afa2127d..30b8376be9146 100644 --- a/sklearn/neighbors/_ball_tree.pyx +++ b/sklearn/neighbors/_ball_tree.pyx @@ -100,7 +100,7 @@ cdef int init_node(BinaryTree tree, NodeData_t[::1] node_data, ITYPE_t i_node, cdef inline DTYPE_t min_dist(BinaryTree tree, ITYPE_t i_node, - DTYPE_t* pt) nogil except -1: + DTYPE_t* pt) except -1 nogil: """Compute the minimum distance between a point and a node""" cdef DTYPE_t dist_pt = tree.dist(pt, &tree.node_bounds[0, i_node, 0], tree.data.shape[1]) @@ -116,7 +116,7 @@ cdef inline DTYPE_t max_dist(BinaryTree tree, ITYPE_t i_node, cdef inline int min_max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt, - DTYPE_t* min_dist, DTYPE_t* max_dist) nogil except -1: + DTYPE_t* min_dist, DTYPE_t* max_dist) except -1 nogil: """Compute the minimum and maximum distance between a point and a node""" cdef DTYPE_t dist_pt = tree.dist(pt, &tree.node_bounds[0, i_node, 0], tree.data.shape[1]) @@ -127,7 +127,7 @@ cdef inline int min_max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt, cdef inline DTYPE_t min_rdist(BinaryTree tree, ITYPE_t i_node, - DTYPE_t* pt) nogil except -1: + DTYPE_t* pt) except -1 nogil: """Compute the minimum reduced-distance between a point and a node""" if tree.euclidean: return euclidean_dist_to_rdist(min_dist(tree, i_node, pt)) diff --git a/sklearn/neighbors/_binary_tree.pxi b/sklearn/neighbors/_binary_tree.pxi index 1251932ab73f9..99ed4341ad155 100644 --- a/sklearn/neighbors/_binary_tree.pxi +++ b/sklearn/neighbors/_binary_tree.pxi @@ -538,7 +538,7 @@ cdef class NeighborsHeap: self._sort() return self.distances.base, self.indices.base - cdef inline DTYPE_t largest(self, ITYPE_t row) nogil except -1: + cdef inline DTYPE_t largest(self, ITYPE_t row) except -1 nogil: """Return the largest distance in the given row""" return self.distances[row, 0] @@ -546,7 +546,7 @@ cdef class NeighborsHeap: return self._push(row, val, i_val) cdef int _push(self, ITYPE_t row, DTYPE_t val, - ITYPE_t i_val) nogil except -1: + ITYPE_t i_val) except -1 nogil: """push (val, i_val) into the given row""" return heap_push( values=&self.distances[row, 0], @@ -993,7 +993,7 @@ cdef class BinaryTree: return cls._valid_metrics cdef inline DTYPE_t dist(self, DTYPE_t* x1, DTYPE_t* x2, - ITYPE_t size) nogil except -1: + ITYPE_t size) except -1 nogil: """Compute the distance between arrays x1 and x2""" self.n_calls += 1 if self.euclidean: @@ -1002,7 +1002,7 @@ cdef class BinaryTree: return self.dist_metric.dist(x1, x2, size) cdef inline DTYPE_t rdist(self, DTYPE_t* x1, DTYPE_t* x2, - ITYPE_t size) nogil except -1: + ITYPE_t size) except -1 nogil: """Compute the reduced distance between arrays x1 and x2. The reduced distance, defined for some metrics, is a quantity which @@ -1587,7 +1587,7 @@ cdef class BinaryTree: cdef int _query_single_depthfirst(self, ITYPE_t i_node, DTYPE_t* pt, ITYPE_t i_pt, NeighborsHeap heap, - DTYPE_t reduced_dist_LB) nogil except -1: + DTYPE_t reduced_dist_LB) except -1 nogil: """Recursive Single-tree k-neighbors query, depth-first approach""" cdef NodeData_t node_info = self.node_data[i_node] @@ -1876,7 +1876,7 @@ cdef class BinaryTree: DTYPE_t* distances, ITYPE_t count, int count_only, - int return_distance) nogil: + int return_distance) noexcept nogil: """recursive single-tree radius query, depth-first""" cdef DTYPE_t* data = &self.data[0, 0] cdef ITYPE_t* idx_array = &self.idx_array[0] diff --git a/sklearn/neighbors/_kd_tree.pyx b/sklearn/neighbors/_kd_tree.pyx index f8351afcd98be..a5db18b4ad772 100644 --- a/sklearn/neighbors/_kd_tree.pyx +++ b/sklearn/neighbors/_kd_tree.pyx @@ -82,7 +82,7 @@ cdef int init_node(BinaryTree tree, NodeData_t[::1] node_data, ITYPE_t i_node, cdef DTYPE_t min_rdist(BinaryTree tree, ITYPE_t i_node, - DTYPE_t* pt) nogil except -1: + DTYPE_t* pt) except -1 nogil: """Compute the minimum reduced-distance between a point and a node""" cdef ITYPE_t n_features = tree.data.shape[1] cdef DTYPE_t d, d_lo, d_hi, rdist=0.0 @@ -143,7 +143,7 @@ cdef DTYPE_t max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt) except -1: cdef inline int min_max_dist(BinaryTree tree, ITYPE_t i_node, DTYPE_t* pt, - DTYPE_t* min_dist, DTYPE_t* max_dist) nogil except -1: + DTYPE_t* min_dist, DTYPE_t* max_dist) except -1 nogil: """Compute the minimum and maximum distance between a point and a node""" cdef ITYPE_t n_features = tree.data.shape[1] diff --git a/sklearn/neighbors/_quad_tree.pxd b/sklearn/neighbors/_quad_tree.pxd index 57f4ed453a633..59008968280f6 100644 --- a/sklearn/neighbors/_quad_tree.pxd +++ b/sklearn/neighbors/_quad_tree.pxd @@ -68,29 +68,29 @@ cdef class _QuadTree: # Point insertion methods cdef int insert_point(self, DTYPE_t[3] point, SIZE_t point_index, - SIZE_t cell_id=*) nogil except -1 + SIZE_t cell_id=*) except -1 nogil cdef SIZE_t _insert_point_in_new_child(self, DTYPE_t[3] point, Cell* cell, SIZE_t point_index, SIZE_t size=* - ) nogil - cdef SIZE_t _select_child(self, DTYPE_t[3] point, Cell* cell) nogil - cdef bint _is_duplicate(self, DTYPE_t[3] point1, DTYPE_t[3] point2) nogil + ) noexcept nogil + cdef SIZE_t _select_child(self, DTYPE_t[3] point, Cell* cell) noexcept nogil + cdef bint _is_duplicate(self, DTYPE_t[3] point1, DTYPE_t[3] point2) noexcept nogil # Create a summary of the Tree compare to a query point cdef long summarize(self, DTYPE_t[3] point, DTYPE_t* results, float squared_theta=*, SIZE_t cell_id=*, long idx=* - ) nogil + ) noexcept nogil # Internal cell initialization methods - cdef void _init_cell(self, Cell* cell, SIZE_t parent, SIZE_t depth) nogil + cdef void _init_cell(self, Cell* cell, SIZE_t parent, SIZE_t depth) noexcept nogil cdef void _init_root(self, DTYPE_t[3] min_bounds, DTYPE_t[3] max_bounds - ) nogil + ) noexcept nogil # Private methods cdef int _check_point_in_cell(self, DTYPE_t[3] point, Cell* cell - ) nogil except -1 + ) except -1 nogil # Private array manipulation to manage the ``cells`` array - cdef int _resize(self, SIZE_t capacity) nogil except -1 - cdef int _resize_c(self, SIZE_t capacity=*) nogil except -1 - cdef int _get_cell(self, DTYPE_t[3] point, SIZE_t cell_id=*) nogil except -1 + cdef int _resize(self, SIZE_t capacity) except -1 nogil + cdef int _resize_c(self, SIZE_t capacity=*) except -1 nogil + cdef int _get_cell(self, DTYPE_t[3] point, SIZE_t cell_id=*) except -1 nogil cdef Cell[:] _get_cell_ndarray(self) diff --git a/sklearn/neighbors/_quad_tree.pyx b/sklearn/neighbors/_quad_tree.pyx index 7771404e2af7a..cb2e77ac3307c 100644 --- a/sklearn/neighbors/_quad_tree.pyx +++ b/sklearn/neighbors/_quad_tree.pyx @@ -114,7 +114,7 @@ cdef class _QuadTree: self._resize(capacity=self.cell_count) cdef int insert_point(self, DTYPE_t[3] point, SIZE_t point_index, - SIZE_t cell_id=0) nogil except -1: + SIZE_t cell_id=0) except -1 nogil: """Insert a point in the QuadTree.""" cdef int ax cdef SIZE_t selected_child @@ -179,7 +179,7 @@ cdef class _QuadTree: # XXX: This operation is not Thread safe cdef SIZE_t _insert_point_in_new_child(self, DTYPE_t[3] point, Cell* cell, SIZE_t point_index, SIZE_t size=1 - ) nogil: + ) noexcept nogil: """Create a child of cell which will contain point.""" # Local variable definition @@ -248,7 +248,7 @@ cdef class _QuadTree: return cell_id - cdef bint _is_duplicate(self, DTYPE_t[3] point1, DTYPE_t[3] point2) nogil: + cdef bint _is_duplicate(self, DTYPE_t[3] point1, DTYPE_t[3] point2) noexcept nogil: """Check if the two given points are equals.""" cdef int i cdef bint res = True @@ -258,7 +258,7 @@ cdef class _QuadTree: return res - cdef SIZE_t _select_child(self, DTYPE_t[3] point, Cell* cell) nogil: + cdef SIZE_t _select_child(self, DTYPE_t[3] point, Cell* cell) noexcept nogil: """Select the child of cell which contains the given query point.""" cdef: int i @@ -272,7 +272,7 @@ cdef class _QuadTree: selected_child += 1 return cell.children[selected_child] - cdef void _init_cell(self, Cell* cell, SIZE_t parent, SIZE_t depth) nogil: + cdef void _init_cell(self, Cell* cell, SIZE_t parent, SIZE_t depth) noexcept nogil: """Initialize a cell structure with some constants.""" cell.parent = parent cell.is_leaf = True @@ -283,7 +283,7 @@ cdef class _QuadTree: cell.children[i] = SIZE_MAX cdef void _init_root(self, DTYPE_t[3] min_bounds, DTYPE_t[3] max_bounds - ) nogil: + ) noexcept nogil: """Initialize the root node with the given space boundaries""" cdef: int i @@ -302,7 +302,7 @@ cdef class _QuadTree: self.cell_count += 1 cdef int _check_point_in_cell(self, DTYPE_t[3] point, Cell* cell - ) nogil except -1: + ) except -1 nogil: """Check that the given point is in the cell boundaries.""" if self.verbose >= 50: @@ -370,7 +370,7 @@ cdef class _QuadTree: cdef long summarize(self, DTYPE_t[3] point, DTYPE_t* results, float squared_theta=.5, SIZE_t cell_id=0, long idx=0 - ) nogil: + ) noexcept nogil: """Summarize the tree compared to a query point. Input arguments @@ -461,7 +461,7 @@ cdef class _QuadTree: return self._get_cell(query_pt, 0) cdef int _get_cell(self, DTYPE_t[3] point, SIZE_t cell_id=0 - ) nogil except -1: + ) except -1 nogil: """guts of get_cell. Return the id of the cell containing the query point or raise ValueError @@ -566,7 +566,7 @@ cdef class _QuadTree: raise ValueError("Can't initialize array!") return arr - cdef int _resize(self, SIZE_t capacity) nogil except -1: + cdef int _resize(self, SIZE_t capacity) except -1 nogil: """Resize all inner arrays to `capacity`, if `capacity` == -1, then double the size of the inner arrays. @@ -578,7 +578,7 @@ cdef class _QuadTree: with gil: raise MemoryError() - cdef int _resize_c(self, SIZE_t capacity=SIZE_MAX) nogil except -1: + cdef int _resize_c(self, SIZE_t capacity=SIZE_MAX) except -1 nogil: """Guts of _resize Returns -1 in case of failure to allocate memory (and raise MemoryError) diff --git a/sklearn/preprocessing/_csr_polynomial_expansion.pyx b/sklearn/preprocessing/_csr_polynomial_expansion.pyx index 17ab1da537fff..784968c463953 100644 --- a/sklearn/preprocessing/_csr_polynomial_expansion.pyx +++ b/sklearn/preprocessing/_csr_polynomial_expansion.pyx @@ -20,7 +20,7 @@ cdef inline cnp.int32_t _deg2_column( cnp.int32_t i, cnp.int32_t j, cnp.int32_t interaction_only, -) nogil: +) noexcept nogil: """Compute the index of the column for a degree 2 expansion d is the dimensionality of the input data, i and j are the indices @@ -38,7 +38,7 @@ cdef inline cnp.int32_t _deg3_column( cnp.int32_t j, cnp.int32_t k, cnp.int32_t interaction_only -) nogil: +) noexcept nogil: """Compute the index of the column for a degree 3 expansion d is the dimensionality of the input data, i, j and k are the indices diff --git a/sklearn/tree/_criterion.pxd b/sklearn/tree/_criterion.pxd index 3c6217a8c272c..47f616c6bad50 100644 --- a/sklearn/tree/_criterion.pxd +++ b/sklearn/tree/_criterion.pxd @@ -49,27 +49,27 @@ cdef class Criterion: const SIZE_t[:] sample_indices, SIZE_t start, SIZE_t end - ) nogil except -1 - cdef int reset(self) nogil except -1 - cdef int reverse_reset(self) nogil except -1 - cdef int update(self, SIZE_t new_pos) nogil except -1 - cdef double node_impurity(self) nogil + ) except -1 nogil + cdef int reset(self) except -1 nogil + cdef int reverse_reset(self) except -1 nogil + cdef int update(self, SIZE_t new_pos) except -1 nogil + cdef double node_impurity(self) noexcept nogil cdef void children_impurity( self, double* impurity_left, double* impurity_right - ) nogil + ) noexcept nogil cdef void node_value( self, double* dest - ) nogil + ) noexcept nogil cdef double impurity_improvement( self, double impurity_parent, double impurity_left, double impurity_right - ) nogil - cdef double proxy_impurity_improvement(self) nogil + ) noexcept nogil + cdef double proxy_impurity_improvement(self) noexcept nogil cdef class ClassificationCriterion(Criterion): """Abstract criterion for classification.""" diff --git a/sklearn/tree/_criterion.pyx b/sklearn/tree/_criterion.pyx index e9f32b6e06ef9..ac58adca0c5a3 100644 --- a/sklearn/tree/_criterion.pyx +++ b/sklearn/tree/_criterion.pyx @@ -49,7 +49,7 @@ cdef class Criterion: const SIZE_t[:] sample_indices, SIZE_t start, SIZE_t end, - ) nogil except -1: + ) except -1 nogil: """Placeholder for a method which will initialize the criterion. Returns -1 in case of failure to allocate memory (and raise MemoryError) @@ -75,21 +75,21 @@ cdef class Criterion: """ pass - cdef int reset(self) nogil except -1: + cdef int reset(self) except -1 nogil: """Reset the criterion at pos=start. This method must be implemented by the subclass. """ pass - cdef int reverse_reset(self) nogil except -1: + cdef int reverse_reset(self) except -1 nogil: """Reset the criterion at pos=end. This method must be implemented by the subclass. """ pass - cdef int update(self, SIZE_t new_pos) nogil except -1: + cdef int update(self, SIZE_t new_pos) except -1 nogil: """Updated statistics by moving sample_indices[pos:new_pos] to the left child. This updates the collected statistics by moving sample_indices[pos:new_pos] @@ -103,7 +103,7 @@ cdef class Criterion: """ pass - cdef double node_impurity(self) nogil: + cdef double node_impurity(self) noexcept nogil: """Placeholder for calculating the impurity of the node. Placeholder for a method which will evaluate the impurity of @@ -114,7 +114,7 @@ cdef class Criterion: pass cdef void children_impurity(self, double* impurity_left, - double* impurity_right) nogil: + double* impurity_right) noexcept nogil: """Placeholder for calculating the impurity of children. Placeholder for a method which evaluates the impurity in @@ -132,7 +132,7 @@ cdef class Criterion: """ pass - cdef void node_value(self, double* dest) nogil: + cdef void node_value(self, double* dest) noexcept nogil: """Placeholder for storing the node value. Placeholder for a method which will compute the node value @@ -145,7 +145,7 @@ cdef class Criterion: """ pass - cdef double proxy_impurity_improvement(self) nogil: + cdef double proxy_impurity_improvement(self) noexcept nogil: """Compute a proxy of the impurity reduction. This method is used to speed up the search for the best split. @@ -165,7 +165,7 @@ cdef class Criterion: cdef double impurity_improvement(self, double impurity_parent, double impurity_left, - double impurity_right) nogil: + double impurity_right) noexcept nogil: """Compute the improvement in impurity. This method computes the improvement in impurity when a split occurs. @@ -257,7 +257,7 @@ cdef class ClassificationCriterion(Criterion): const SIZE_t[:] sample_indices, SIZE_t start, SIZE_t end - ) nogil except -1: + ) except -1 nogil: """Initialize the criterion. This initializes the criterion at node sample_indices[start:end] and children @@ -319,7 +319,7 @@ cdef class ClassificationCriterion(Criterion): self.reset() return 0 - cdef int reset(self) nogil except -1: + cdef int reset(self) except -1 nogil: """Reset the criterion at pos=start. Returns -1 in case of failure to allocate memory (and raise MemoryError) @@ -336,7 +336,7 @@ cdef class ClassificationCriterion(Criterion): memcpy(&self.sum_right[k, 0], &self.sum_total[k, 0], self.n_classes[k] * sizeof(double)) return 0 - cdef int reverse_reset(self) nogil except -1: + cdef int reverse_reset(self) except -1 nogil: """Reset the criterion at pos=end. Returns -1 in case of failure to allocate memory (and raise MemoryError) @@ -353,7 +353,7 @@ cdef class ClassificationCriterion(Criterion): memcpy(&self.sum_left[k, 0], &self.sum_total[k, 0], self.n_classes[k] * sizeof(double)) return 0 - cdef int update(self, SIZE_t new_pos) nogil except -1: + cdef int update(self, SIZE_t new_pos) except -1 nogil: """Updated statistics by moving sample_indices[pos:new_pos] to the left child. Returns -1 in case of failure to allocate memory (and raise MemoryError) @@ -419,14 +419,14 @@ cdef class ClassificationCriterion(Criterion): self.pos = new_pos return 0 - cdef double node_impurity(self) nogil: + cdef double node_impurity(self) noexcept nogil: pass cdef void children_impurity(self, double* impurity_left, - double* impurity_right) nogil: + double* impurity_right) noexcept nogil: pass - cdef void node_value(self, double* dest) nogil: + cdef void node_value(self, double* dest) noexcept nogil: """Compute the node value of sample_indices[start:end] and save it into dest. Parameters @@ -457,7 +457,7 @@ cdef class Entropy(ClassificationCriterion): cross-entropy = -\sum_{k=0}^{K-1} count_k log(count_k) """ - cdef double node_impurity(self) nogil: + cdef double node_impurity(self) noexcept nogil: """Evaluate the impurity of the current node. Evaluate the cross-entropy criterion as impurity of the current node, @@ -479,7 +479,7 @@ cdef class Entropy(ClassificationCriterion): return entropy / self.n_outputs cdef void children_impurity(self, double* impurity_left, - double* impurity_right) nogil: + double* impurity_right) noexcept nogil: """Evaluate the impurity in children nodes. i.e. the impurity of the left child (sample_indices[start:pos]) and the @@ -531,7 +531,7 @@ cdef class Gini(ClassificationCriterion): = 1 - \sum_{k=0}^{K-1} count_k ** 2 """ - cdef double node_impurity(self) nogil: + cdef double node_impurity(self) noexcept nogil: """Evaluate the impurity of the current node. Evaluate the Gini criterion as impurity of the current node, @@ -557,7 +557,7 @@ cdef class Gini(ClassificationCriterion): return gini / self.n_outputs cdef void children_impurity(self, double* impurity_left, - double* impurity_right) nogil: + double* impurity_right) noexcept nogil: """Evaluate the impurity in children nodes. i.e. the impurity of the left child (sample_indices[start:pos]) and the @@ -651,7 +651,7 @@ cdef class RegressionCriterion(Criterion): const SIZE_t[:] sample_indices, SIZE_t start, SIZE_t end, - ) nogil except -1: + ) except -1 nogil: """Initialize the criterion. This initializes the criterion at node sample_indices[start:end] and children @@ -694,7 +694,7 @@ cdef class RegressionCriterion(Criterion): self.reset() return 0 - cdef int reset(self) nogil except -1: + cdef int reset(self) except -1 nogil: """Reset the criterion at pos=start.""" cdef SIZE_t n_bytes = self.n_outputs * sizeof(double) memset(&self.sum_left[0], 0, n_bytes) @@ -705,7 +705,7 @@ cdef class RegressionCriterion(Criterion): self.pos = self.start return 0 - cdef int reverse_reset(self) nogil except -1: + cdef int reverse_reset(self) except -1 nogil: """Reset the criterion at pos=end.""" cdef SIZE_t n_bytes = self.n_outputs * sizeof(double) memset(&self.sum_right[0], 0, n_bytes) @@ -716,7 +716,7 @@ cdef class RegressionCriterion(Criterion): self.pos = self.end return 0 - cdef int update(self, SIZE_t new_pos) nogil except -1: + cdef int update(self, SIZE_t new_pos) except -1 nogil: """Updated statistics by moving sample_indices[pos:new_pos] to the left.""" cdef const DOUBLE_t[:] sample_weight = self.sample_weight cdef const SIZE_t[:] sample_indices = self.sample_indices @@ -768,14 +768,14 @@ cdef class RegressionCriterion(Criterion): self.pos = new_pos return 0 - cdef double node_impurity(self) nogil: + cdef double node_impurity(self) noexcept nogil: pass cdef void children_impurity(self, double* impurity_left, - double* impurity_right) nogil: + double* impurity_right) noexcept nogil: pass - cdef void node_value(self, double* dest) nogil: + cdef void node_value(self, double* dest) noexcept nogil: """Compute the node value of sample_indices[start:end] into dest.""" cdef SIZE_t k @@ -789,7 +789,7 @@ cdef class MSE(RegressionCriterion): MSE = var_left + var_right """ - cdef double node_impurity(self) nogil: + cdef double node_impurity(self) noexcept nogil: """Evaluate the impurity of the current node. Evaluate the MSE criterion as impurity of the current node, @@ -805,7 +805,7 @@ cdef class MSE(RegressionCriterion): return impurity / self.n_outputs - cdef double proxy_impurity_improvement(self) nogil: + cdef double proxy_impurity_improvement(self) noexcept nogil: """Compute a proxy of the impurity reduction. This method is used to speed up the search for the best split. @@ -837,7 +837,7 @@ cdef class MSE(RegressionCriterion): proxy_impurity_right / self.weighted_n_right) cdef void children_impurity(self, double* impurity_left, - double* impurity_right) nogil: + double* impurity_right) noexcept nogil: """Evaluate the impurity in children nodes. i.e. the impurity of the left child (sample_indices[start:pos]) and the @@ -931,7 +931,7 @@ cdef class MAE(RegressionCriterion): const SIZE_t[:] sample_indices, SIZE_t start, SIZE_t end, - ) nogil except -1: + ) except -1 nogil: """Initialize the criterion. This initializes the criterion at node sample_indices[start:end] and children @@ -981,7 +981,7 @@ cdef class MAE(RegressionCriterion): self.reset() return 0 - cdef int reset(self) nogil except -1: + cdef int reset(self) except -1 nogil: """Reset the criterion at pos=start. Returns -1 in case of failure to allocate memory (and raise MemoryError) @@ -1012,7 +1012,7 @@ cdef class MAE(RegressionCriterion): weight) return 0 - cdef int reverse_reset(self) nogil except -1: + cdef int reverse_reset(self) except -1 nogil: """Reset the criterion at pos=end. Returns -1 in case of failure to allocate memory (and raise MemoryError) @@ -1040,7 +1040,7 @@ cdef class MAE(RegressionCriterion): weight) return 0 - cdef int update(self, SIZE_t new_pos) nogil except -1: + cdef int update(self, SIZE_t new_pos) except -1 nogil: """Updated statistics by moving sample_indices[pos:new_pos] to the left. Returns -1 in case of failure to allocate memory (and raise MemoryError) @@ -1097,13 +1097,13 @@ cdef class MAE(RegressionCriterion): self.pos = new_pos return 0 - cdef void node_value(self, double* dest) nogil: + cdef void node_value(self, double* dest) noexcept nogil: """Computes the node value of sample_indices[start:end] into dest.""" cdef SIZE_t k for k in range(self.n_outputs): dest[k] = self.node_medians[k] - cdef double node_impurity(self) nogil: + cdef double node_impurity(self) noexcept nogil: """Evaluate the impurity of the current node. Evaluate the MAE criterion as impurity of the current node, @@ -1128,7 +1128,7 @@ cdef class MAE(RegressionCriterion): return impurity / (self.weighted_n_node_samples * self.n_outputs) cdef void children_impurity(self, double* p_impurity_left, - double* p_impurity_right) nogil: + double* p_impurity_right) noexcept nogil: """Evaluate the impurity in children nodes. i.e. the impurity of the left child (sample_indices[start:pos]) and the @@ -1184,7 +1184,7 @@ cdef class FriedmanMSE(MSE): improvement = n_left * n_right * diff^2 / (n_left + n_right) """ - cdef double proxy_impurity_improvement(self) nogil: + cdef double proxy_impurity_improvement(self) noexcept nogil: """Compute a proxy of the impurity reduction. This method is used to speed up the search for the best split. @@ -1211,7 +1211,7 @@ cdef class FriedmanMSE(MSE): return diff * diff / (self.weighted_n_left * self.weighted_n_right) cdef double impurity_improvement(self, double impurity_parent, double - impurity_left, double impurity_right) nogil: + impurity_left, double impurity_right) noexcept nogil: # Note: none of the arguments are used here cdef double total_sum_left = 0.0 cdef double total_sum_right = 0.0 @@ -1251,7 +1251,7 @@ cdef class Poisson(RegressionCriterion): # children_impurity would only need to go over left xor right split, not # both. This could be faster. - cdef double node_impurity(self) nogil: + cdef double node_impurity(self) noexcept nogil: """Evaluate the impurity of the current node. Evaluate the Poisson criterion as impurity of the current node, @@ -1261,7 +1261,7 @@ cdef class Poisson(RegressionCriterion): return self.poisson_loss(self.start, self.end, self.sum_total, self.weighted_n_node_samples) - cdef double proxy_impurity_improvement(self) nogil: + cdef double proxy_impurity_improvement(self) noexcept nogil: """Compute a proxy of the impurity reduction. This method is used to speed up the search for the best split. @@ -1308,7 +1308,7 @@ cdef class Poisson(RegressionCriterion): return - proxy_impurity_left - proxy_impurity_right cdef void children_impurity(self, double* impurity_left, - double* impurity_right) nogil: + double* impurity_right) noexcept nogil: """Evaluate the impurity in children nodes. i.e. the impurity of the left child (sample_indices[start:pos]) and the @@ -1328,7 +1328,7 @@ cdef class Poisson(RegressionCriterion): SIZE_t start, SIZE_t end, const double[::1] y_sum, - DOUBLE_t weight_sum) nogil: + DOUBLE_t weight_sum) noexcept nogil: """Helper function to compute Poisson loss (~deviance) of a given node. """ cdef const DOUBLE_t[:, ::1] y = self.y diff --git a/sklearn/tree/_splitter.pxd b/sklearn/tree/_splitter.pxd index f97761879922a..13fec5974c3c5 100644 --- a/sklearn/tree/_splitter.pxd +++ b/sklearn/tree/_splitter.pxd @@ -86,15 +86,15 @@ cdef class Splitter: SIZE_t start, SIZE_t end, double* weighted_n_node_samples - ) nogil except -1 + ) except -1 nogil cdef int node_split( self, double impurity, # Impurity of the node SplitRecord* split, SIZE_t* n_constant_features - ) nogil except -1 + ) except -1 nogil - cdef void node_value(self, double* dest) nogil + cdef void node_value(self, double* dest) noexcept nogil - cdef double node_impurity(self) nogil + cdef double node_impurity(self) noexcept nogil diff --git a/sklearn/tree/_splitter.pyx b/sklearn/tree/_splitter.pyx index 9f4301cd99dc0..83a80d90cc1b9 100644 --- a/sklearn/tree/_splitter.pyx +++ b/sklearn/tree/_splitter.pyx @@ -35,7 +35,7 @@ cdef DTYPE_t FEATURE_THRESHOLD = 1e-7 # in SparsePartitioner cdef DTYPE_t EXTRACT_NNZ_SWITCH = 0.1 -cdef inline void _init_split(SplitRecord* self, SIZE_t start_pos) nogil: +cdef inline void _init_split(SplitRecord* self, SIZE_t start_pos) noexcept nogil: self.impurity_left = INFINITY self.impurity_right = INFINITY self.pos = start_pos @@ -168,7 +168,7 @@ cdef class Splitter: return 0 cdef int node_reset(self, SIZE_t start, SIZE_t end, - double* weighted_n_node_samples) nogil except -1: + double* weighted_n_node_samples) except -1 nogil: """Reset splitter on node samples[start:end]. Returns -1 in case of failure to allocate memory (and raise MemoryError) @@ -200,7 +200,7 @@ cdef class Splitter: return 0 cdef int node_split(self, double impurity, SplitRecord* split, - SIZE_t* n_constant_features) nogil except -1: + SIZE_t* n_constant_features) except -1 nogil: """Find the best split on node samples[start:end]. This is a placeholder method. The majority of computation will be done @@ -211,12 +211,12 @@ cdef class Splitter: pass - cdef void node_value(self, double* dest) nogil: + cdef void node_value(self, double* dest) noexcept nogil: """Copy the value of node samples[start:end] into dest.""" self.criterion.node_value(dest) - cdef double node_impurity(self) nogil: + cdef double node_impurity(self) noexcept nogil: """Return the impurity of the current node.""" return self.criterion.node_impurity() @@ -237,7 +237,7 @@ cdef inline int node_split_best( double impurity, SplitRecord* split, SIZE_t* n_constant_features, -) nogil except -1: +) except -1 nogil: """Find the best split on node samples[start:end] Returns -1 in case of failure to allocate memory (and raise MemoryError) @@ -415,7 +415,7 @@ cdef inline int node_split_best( # Sort n-element arrays pointed to by feature_values and samples, simultaneously, # by the values in feature_values. Algorithm: Introsort (Musser, SP&E, 1997). -cdef inline void sort(DTYPE_t* feature_values, SIZE_t* samples, SIZE_t n) nogil: +cdef inline void sort(DTYPE_t* feature_values, SIZE_t* samples, SIZE_t n) noexcept nogil: if n == 0: return cdef int maxd = 2 * log(n) @@ -423,13 +423,13 @@ cdef inline void sort(DTYPE_t* feature_values, SIZE_t* samples, SIZE_t n) nogil: cdef inline void swap(DTYPE_t* feature_values, SIZE_t* samples, - SIZE_t i, SIZE_t j) nogil: + SIZE_t i, SIZE_t j) noexcept nogil: # Helper for sort feature_values[i], feature_values[j] = feature_values[j], feature_values[i] samples[i], samples[j] = samples[j], samples[i] -cdef inline DTYPE_t median3(DTYPE_t* feature_values, SIZE_t n) nogil: +cdef inline DTYPE_t median3(DTYPE_t* feature_values, SIZE_t n) noexcept nogil: # Median of three pivot selection, after Bentley and McIlroy (1993). # Engineering a sort function. SP&E. Requires 8/3 comparisons on average. cdef DTYPE_t a = feature_values[0], b = feature_values[n / 2], c = feature_values[n - 1] @@ -452,7 +452,7 @@ cdef inline DTYPE_t median3(DTYPE_t* feature_values, SIZE_t n) nogil: # Introsort with median of 3 pivot selection and 3-way partition function # (robust to repeated elements, e.g. lots of zero features). cdef void introsort(DTYPE_t* feature_values, SIZE_t *samples, - SIZE_t n, int maxd) nogil: + SIZE_t n, int maxd) noexcept nogil: cdef DTYPE_t pivot cdef SIZE_t i, l, r @@ -485,7 +485,7 @@ cdef void introsort(DTYPE_t* feature_values, SIZE_t *samples, cdef inline void sift_down(DTYPE_t* feature_values, SIZE_t* samples, - SIZE_t start, SIZE_t end) nogil: + SIZE_t start, SIZE_t end) noexcept nogil: # Restore heap order in feature_values[start:end] by moving the max element to start. cdef SIZE_t child, maxind, root @@ -507,7 +507,7 @@ cdef inline void sift_down(DTYPE_t* feature_values, SIZE_t* samples, root = maxind -cdef void heapsort(DTYPE_t* feature_values, SIZE_t* samples, SIZE_t n) nogil: +cdef void heapsort(DTYPE_t* feature_values, SIZE_t* samples, SIZE_t n) noexcept nogil: cdef SIZE_t start, end # heapify @@ -533,7 +533,7 @@ cdef inline int node_split_random( double impurity, SplitRecord* split, SIZE_t* n_constant_features -) nogil except -1: +) except -1 nogil: """Find the best random split on node samples[start:end] Returns -1 in case of failure to allocate memory (and raise MemoryError) @@ -721,14 +721,14 @@ cdef class DensePartitioner: self.samples = samples self.feature_values = feature_values - cdef inline void init_node_split(self, SIZE_t start, SIZE_t end) nogil: + cdef inline void init_node_split(self, SIZE_t start, SIZE_t end) noexcept nogil: """Initialize splitter at the beginning of node_split.""" self.start = start self.end = end cdef inline void sort_samples_and_feature_values( self, SIZE_t current_feature - ) nogil: + ) noexcept nogil: """Simultaneously sort based on the feature_values.""" cdef: SIZE_t i @@ -749,7 +749,7 @@ cdef class DensePartitioner: SIZE_t current_feature, DTYPE_t* min_feature_value_out, DTYPE_t* max_feature_value_out, - ) nogil: + ) noexcept nogil: """Find the minimum and maximum value for current_feature.""" cdef: SIZE_t p @@ -774,7 +774,7 @@ cdef class DensePartitioner: min_feature_value_out[0] = min_feature_value max_feature_value_out[0] = max_feature_value - cdef inline void next_p(self, SIZE_t* p_prev, SIZE_t* p) nogil: + cdef inline void next_p(self, SIZE_t* p_prev, SIZE_t* p) noexcept nogil: """Compute the next p_prev and p for iteratiing over feature values.""" cdef DTYPE_t[::1] feature_values = self.feature_values @@ -790,7 +790,7 @@ cdef class DensePartitioner: # (feature_values[p] >= end) or (feature_values[p] > feature_values[p - 1]) p[0] += 1 - cdef inline SIZE_t partition_samples(self, double current_threshold) nogil: + cdef inline SIZE_t partition_samples(self, double current_threshold) noexcept nogil: """Partition samples for feature_values at the current_threshold.""" cdef: SIZE_t p = self.start @@ -816,7 +816,7 @@ cdef class DensePartitioner: SIZE_t best_pos, double best_threshold, SIZE_t best_feature, - ) nogil: + ) noexcept nogil: """Partition samples for X at the best_threshold and best_feature.""" cdef: SIZE_t p = self.start @@ -884,7 +884,7 @@ cdef class SparsePartitioner: for p in range(n_samples): self.index_to_samples[samples[p]] = p - cdef inline void init_node_split(self, SIZE_t start, SIZE_t end) nogil: + cdef inline void init_node_split(self, SIZE_t start, SIZE_t end) noexcept nogil: """Initialize splitter at the beginning of node_split.""" self.start = start self.end = end @@ -892,7 +892,7 @@ cdef class SparsePartitioner: cdef inline void sort_samples_and_feature_values( self, SIZE_t current_feature - ) nogil: + ) noexcept nogil: """Simultaneously sort based on the feature_values.""" cdef: DTYPE_t[::1] feature_values = self.feature_values @@ -926,7 +926,7 @@ cdef class SparsePartitioner: SIZE_t current_feature, DTYPE_t* min_feature_value_out, DTYPE_t* max_feature_value_out, - ) nogil: + ) noexcept nogil: """Find the minimum and maximum value for current_feature.""" cdef: SIZE_t p @@ -964,7 +964,7 @@ cdef class SparsePartitioner: min_feature_value_out[0] = min_feature_value max_feature_value_out[0] = max_feature_value - cdef inline void next_p(self, SIZE_t* p_prev, SIZE_t* p) nogil: + cdef inline void next_p(self, SIZE_t* p_prev, SIZE_t* p) noexcept nogil: """Compute the next p_prev and p for iteratiing over feature values.""" cdef: SIZE_t p_next @@ -986,7 +986,7 @@ cdef class SparsePartitioner: p_prev[0] = p[0] p[0] = p_next - cdef inline SIZE_t partition_samples(self, double current_threshold) nogil: + cdef inline SIZE_t partition_samples(self, double current_threshold) noexcept nogil: """Partition samples for feature_values at the current_threshold.""" return self._partition(current_threshold, self.start_positive) @@ -995,12 +995,12 @@ cdef class SparsePartitioner: SIZE_t best_pos, double best_threshold, SIZE_t best_feature, - ) nogil: + ) noexcept nogil: """Partition samples for X at the best_threshold and best_feature.""" self.extract_nnz(best_feature) self._partition(best_threshold, best_pos) - cdef inline SIZE_t _partition(self, double threshold, SIZE_t zero_pos) nogil: + cdef inline SIZE_t _partition(self, double threshold, SIZE_t zero_pos) noexcept nogil: """Partition samples[start:end] based on threshold.""" cdef: SIZE_t p, partition_end @@ -1032,7 +1032,7 @@ cdef class SparsePartitioner: return partition_end - cdef inline void extract_nnz(self, SIZE_t feature) nogil: + cdef inline void extract_nnz(self, SIZE_t feature) noexcept nogil: """Extract and partition values for a given feature. The extracted values are partitioned between negative values @@ -1088,7 +1088,7 @@ cdef class SparsePartitioner: &self.end_negative, &self.start_positive) -cdef int compare_SIZE_t(const void* a, const void* b) nogil: +cdef int compare_SIZE_t(const void* a, const void* b) noexcept nogil: """Comparison function for sort.""" return ((a)[0] - (b)[0]) @@ -1096,7 +1096,7 @@ cdef int compare_SIZE_t(const void* a, const void* b) nogil: cdef inline void binary_search(const INT32_t[::1] sorted_array, INT32_t start, INT32_t end, SIZE_t value, SIZE_t* index, - INT32_t* new_start) nogil: + INT32_t* new_start) noexcept nogil: """Return the index of value in the sorted array. If not found, return -1. new_start is the last pivot + 1 @@ -1128,7 +1128,7 @@ cdef inline void extract_nnz_index_to_samples(const INT32_t[::1] X_indices, SIZE_t[::1] index_to_samples, DTYPE_t[::1] feature_values, SIZE_t* end_negative, - SIZE_t* start_positive) nogil: + SIZE_t* start_positive) noexcept nogil: """Extract and partition values for a feature using index_to_samples. Complexity is O(indptr_end - indptr_start). @@ -1170,7 +1170,7 @@ cdef inline void extract_nnz_binary_search(const INT32_t[::1] X_indices, SIZE_t* end_negative, SIZE_t* start_positive, SIZE_t[::1] sorted_samples, - bint* is_samples_sorted) nogil: + bint* is_samples_sorted) noexcept nogil: """Extract and partition values for a given feature using binary search. If n_samples = end - start and n_indices = indptr_end - indptr_start, @@ -1231,7 +1231,7 @@ cdef inline void extract_nnz_binary_search(const INT32_t[::1] X_indices, cdef inline void sparse_swap(SIZE_t[::1] index_to_samples, SIZE_t[::1] samples, - SIZE_t pos_1, SIZE_t pos_2) nogil: + SIZE_t pos_1, SIZE_t pos_2) noexcept nogil: """Swap sample pos_1 and pos_2 preserving sparse invariant.""" samples[pos_1], samples[pos_2] = samples[pos_2], samples[pos_1] index_to_samples[samples[pos_1]] = pos_1 @@ -1251,7 +1251,7 @@ cdef class BestSplitter(Splitter): self.partitioner = DensePartitioner(X, self.samples, self.feature_values) cdef int node_split(self, double impurity, SplitRecord* split, - SIZE_t* n_constant_features) nogil except -1: + SIZE_t* n_constant_features) except -1 nogil: return node_split_best( self, self.partitioner, @@ -1276,7 +1276,7 @@ cdef class BestSparseSplitter(Splitter): ) cdef int node_split(self, double impurity, SplitRecord* split, - SIZE_t* n_constant_features) nogil except -1: + SIZE_t* n_constant_features) except -1 nogil: return node_split_best( self, self.partitioner, @@ -1299,7 +1299,7 @@ cdef class RandomSplitter(Splitter): self.partitioner = DensePartitioner(X, self.samples, self.feature_values) cdef int node_split(self, double impurity, SplitRecord* split, - SIZE_t* n_constant_features) nogil except -1: + SIZE_t* n_constant_features) except -1 nogil: return node_split_random( self, self.partitioner, @@ -1324,7 +1324,7 @@ cdef class RandomSparseSplitter(Splitter): ) cdef int node_split(self, double impurity, SplitRecord* split, - SIZE_t* n_constant_features) nogil except -1: + SIZE_t* n_constant_features) except -1 nogil: return node_split_random( self, self.partitioner, diff --git a/sklearn/tree/_tree.pxd b/sklearn/tree/_tree.pxd index 3e60e91d6940a..1966651d8c89a 100644 --- a/sklearn/tree/_tree.pxd +++ b/sklearn/tree/_tree.pxd @@ -58,9 +58,9 @@ cdef class Tree: cdef SIZE_t _add_node(self, SIZE_t parent, bint is_left, bint is_leaf, SIZE_t feature, double threshold, double impurity, SIZE_t n_node_samples, - double weighted_n_node_samples) nogil except -1 - cdef int _resize(self, SIZE_t capacity) nogil except -1 - cdef int _resize_c(self, SIZE_t capacity=*) nogil except -1 + double weighted_n_node_samples) except -1 nogil + cdef int _resize(self, SIZE_t capacity) except -1 nogil + cdef int _resize_c(self, SIZE_t capacity=*) except -1 nogil cdef cnp.ndarray _get_value_ndarray(self) cdef cnp.ndarray _get_node_ndarray(self) diff --git a/sklearn/tree/_tree.pyx b/sklearn/tree/_tree.pyx index 3176d9c1a7abf..75eed058bfd4e 100644 --- a/sklearn/tree/_tree.pyx +++ b/sklearn/tree/_tree.pyx @@ -326,7 +326,7 @@ cdef inline bool _compare_records( cdef inline void _add_to_frontier( FrontierRecord rec, vector[FrontierRecord]& frontier, -) nogil: +) noexcept nogil: """Adds record `rec` to the priority queue `frontier`.""" frontier.push_back(rec) push_heap(frontier.begin(), frontier.end(), &_compare_records) @@ -459,7 +459,7 @@ cdef class BestFirstTreeBuilder(TreeBuilder): SIZE_t start, SIZE_t end, double impurity, bint is_first, bint is_left, Node* parent, SIZE_t depth, - FrontierRecord* res) nogil except -1: + FrontierRecord* res) except -1 nogil: """Adds node w/ partition ``[start, end)`` to the frontier. """ cdef SplitRecord split cdef SIZE_t node_id @@ -713,7 +713,7 @@ cdef class Tree: value = memcpy(self.value, cnp.PyArray_DATA(value_ndarray), self.capacity * self.value_stride * sizeof(double)) - cdef int _resize(self, SIZE_t capacity) nogil except -1: + cdef int _resize(self, SIZE_t capacity) except -1 nogil: """Resize all inner arrays to `capacity`, if `capacity` == -1, then double the size of the inner arrays. @@ -725,7 +725,7 @@ cdef class Tree: with gil: raise MemoryError() - cdef int _resize_c(self, SIZE_t capacity=INTPTR_MAX) nogil except -1: + cdef int _resize_c(self, SIZE_t capacity=INTPTR_MAX) except -1 nogil: """Guts of _resize Returns -1 in case of failure to allocate memory (and raise MemoryError) @@ -759,7 +759,7 @@ cdef class Tree: cdef SIZE_t _add_node(self, SIZE_t parent, bint is_left, bint is_leaf, SIZE_t feature, double threshold, double impurity, SIZE_t n_node_samples, - double weighted_n_node_samples) nogil except -1: + double weighted_n_node_samples) except -1 nogil: """Add a node to the tree. The new node registers itself as the child of its parent. @@ -1410,16 +1410,16 @@ cdef class _CCPPruneController: """Base class used by build_pruned_tree_ccp and ccp_pruning_path to control pruning. """ - cdef bint stop_pruning(self, DOUBLE_t effective_alpha) nogil: + cdef bint stop_pruning(self, DOUBLE_t effective_alpha) noexcept nogil: """Return 1 to stop pruning and 0 to continue pruning""" return 0 cdef void save_metrics(self, DOUBLE_t effective_alpha, - DOUBLE_t subtree_impurities) nogil: + DOUBLE_t subtree_impurities) noexcept nogil: """Save metrics when pruning""" pass - cdef void after_pruning(self, unsigned char[:] in_subtree) nogil: + cdef void after_pruning(self, unsigned char[:] in_subtree) noexcept nogil: """Called after pruning""" pass @@ -1433,12 +1433,12 @@ cdef class _AlphaPruner(_CCPPruneController): self.ccp_alpha = ccp_alpha self.capacity = 0 - cdef bint stop_pruning(self, DOUBLE_t effective_alpha) nogil: + cdef bint stop_pruning(self, DOUBLE_t effective_alpha) noexcept nogil: # The subtree on the previous iteration has the greatest ccp_alpha # less than or equal to self.ccp_alpha return self.ccp_alpha < effective_alpha - cdef void after_pruning(self, unsigned char[:] in_subtree) nogil: + cdef void after_pruning(self, unsigned char[:] in_subtree) noexcept nogil: """Updates the number of leaves in subtree""" for i in range(in_subtree.shape[0]): if in_subtree[i]: @@ -1458,7 +1458,7 @@ cdef class _PathFinder(_CCPPruneController): cdef void save_metrics(self, DOUBLE_t effective_alpha, - DOUBLE_t subtree_impurities) nogil: + DOUBLE_t subtree_impurities) noexcept nogil: self.ccp_alphas[self.count] = effective_alpha self.impurities[self.count] = subtree_impurities self.count += 1 diff --git a/sklearn/tree/_utils.pxd b/sklearn/tree/_utils.pxd index 9d41b757d85dc..b8f2b71513bd2 100644 --- a/sklearn/tree/_utils.pxd +++ b/sklearn/tree/_utils.pxd @@ -43,21 +43,21 @@ ctypedef fused realloc_ptr: (Cell*) (Node**) -cdef realloc_ptr safe_realloc(realloc_ptr* p, size_t nelems) nogil except * +cdef realloc_ptr safe_realloc(realloc_ptr* p, size_t nelems) except * nogil cdef cnp.ndarray sizet_ptr_to_ndarray(SIZE_t* data, SIZE_t size) cdef SIZE_t rand_int(SIZE_t low, SIZE_t high, - UINT32_t* random_state) nogil + UINT32_t* random_state) noexcept nogil cdef double rand_uniform(double low, double high, - UINT32_t* random_state) nogil + UINT32_t* random_state) noexcept nogil -cdef double log(double x) nogil +cdef double log(double x) noexcept nogil # ============================================================================= # WeightedPQueue data structure @@ -73,15 +73,15 @@ cdef class WeightedPQueue: cdef SIZE_t array_ptr cdef WeightedPQueueRecord* array_ - cdef bint is_empty(self) nogil - cdef int reset(self) nogil except -1 - cdef SIZE_t size(self) nogil - cdef int push(self, DOUBLE_t data, DOUBLE_t weight) nogil except -1 - cdef int remove(self, DOUBLE_t data, DOUBLE_t weight) nogil - cdef int pop(self, DOUBLE_t* data, DOUBLE_t* weight) nogil - cdef int peek(self, DOUBLE_t* data, DOUBLE_t* weight) nogil - cdef DOUBLE_t get_weight_from_index(self, SIZE_t index) nogil - cdef DOUBLE_t get_value_from_index(self, SIZE_t index) nogil + cdef bint is_empty(self) noexcept nogil + cdef int reset(self) except -1 nogil + cdef SIZE_t size(self) noexcept nogil + cdef int push(self, DOUBLE_t data, DOUBLE_t weight) except -1 nogil + cdef int remove(self, DOUBLE_t data, DOUBLE_t weight) noexcept nogil + cdef int pop(self, DOUBLE_t* data, DOUBLE_t* weight) noexcept nogil + cdef int peek(self, DOUBLE_t* data, DOUBLE_t* weight) noexcept nogil + cdef DOUBLE_t get_weight_from_index(self, SIZE_t index) noexcept nogil + cdef DOUBLE_t get_value_from_index(self, SIZE_t index) noexcept nogil # ============================================================================= @@ -96,15 +96,15 @@ cdef class WeightedMedianCalculator: cdef DOUBLE_t sum_w_0_k # represents sum(weights[0:k]) # = w[0] + w[1] + ... + w[k-1] - cdef SIZE_t size(self) nogil - cdef int push(self, DOUBLE_t data, DOUBLE_t weight) nogil except -1 - cdef int reset(self) nogil except -1 + cdef SIZE_t size(self) noexcept nogil + cdef int push(self, DOUBLE_t data, DOUBLE_t weight) except -1 nogil + cdef int reset(self) except -1 nogil cdef int update_median_parameters_post_push( self, DOUBLE_t data, DOUBLE_t weight, - DOUBLE_t original_median) nogil - cdef int remove(self, DOUBLE_t data, DOUBLE_t weight) nogil - cdef int pop(self, DOUBLE_t* data, DOUBLE_t* weight) nogil + DOUBLE_t original_median) noexcept nogil + cdef int remove(self, DOUBLE_t data, DOUBLE_t weight) noexcept nogil + cdef int pop(self, DOUBLE_t* data, DOUBLE_t* weight) noexcept nogil cdef int update_median_parameters_post_remove( self, DOUBLE_t data, DOUBLE_t weight, - DOUBLE_t original_median) nogil - cdef DOUBLE_t get_median(self) nogil + DOUBLE_t original_median) noexcept nogil + cdef DOUBLE_t get_median(self) noexcept nogil diff --git a/sklearn/tree/_utils.pyx b/sklearn/tree/_utils.pyx index cf4d6aebf78c3..0bde50c315ee8 100644 --- a/sklearn/tree/_utils.pyx +++ b/sklearn/tree/_utils.pyx @@ -20,7 +20,7 @@ from ..utils._random cimport our_rand_r # Helper functions # ============================================================================= -cdef realloc_ptr safe_realloc(realloc_ptr* p, size_t nelems) nogil except *: +cdef realloc_ptr safe_realloc(realloc_ptr* p, size_t nelems) except * nogil: # sizeof(realloc_ptr[0]) would be more like idiomatic C, but causes Cython # 0.20.1 to crash. cdef size_t nbytes = nelems * sizeof(p[0][0]) @@ -56,19 +56,19 @@ cdef inline cnp.ndarray sizet_ptr_to_ndarray(SIZE_t* data, SIZE_t size): cdef inline SIZE_t rand_int(SIZE_t low, SIZE_t high, - UINT32_t* random_state) nogil: + UINT32_t* random_state) noexcept nogil: """Generate a random integer in [low; end).""" return low + our_rand_r(random_state) % (high - low) cdef inline double rand_uniform(double low, double high, - UINT32_t* random_state) nogil: + UINT32_t* random_state) noexcept nogil: """Generate a random double in [low; high).""" return ((high - low) * our_rand_r(random_state) / RAND_R_MAX) + low -cdef inline double log(double x) nogil: +cdef inline double log(double x) noexcept nogil: return ln(x) / ln(2.0) # ============================================================================= @@ -102,7 +102,7 @@ cdef class WeightedPQueue: def __dealloc__(self): free(self.array_) - cdef int reset(self) nogil except -1: + cdef int reset(self) except -1 nogil: """Reset the WeightedPQueue to its state at construction Return -1 in case of failure to allocate memory (and raise MemoryError) @@ -113,13 +113,13 @@ cdef class WeightedPQueue: safe_realloc(&self.array_, self.capacity) return 0 - cdef bint is_empty(self) nogil: + cdef bint is_empty(self) noexcept nogil: return self.array_ptr <= 0 - cdef SIZE_t size(self) nogil: + cdef SIZE_t size(self) noexcept nogil: return self.array_ptr - cdef int push(self, DOUBLE_t data, DOUBLE_t weight) nogil except -1: + cdef int push(self, DOUBLE_t data, DOUBLE_t weight) except -1 nogil: """Push record on the array. Return -1 in case of failure to allocate memory (and raise MemoryError) @@ -151,7 +151,7 @@ cdef class WeightedPQueue: self.array_ptr = array_ptr + 1 return 0 - cdef int remove(self, DOUBLE_t data, DOUBLE_t weight) nogil: + cdef int remove(self, DOUBLE_t data, DOUBLE_t weight) noexcept nogil: """Remove a specific value/weight record from the array. Returns 0 if successful, -1 if record not found.""" cdef SIZE_t array_ptr = self.array_ptr @@ -179,7 +179,7 @@ cdef class WeightedPQueue: self.array_ptr = array_ptr - 1 return 0 - cdef int pop(self, DOUBLE_t* data, DOUBLE_t* weight) nogil: + cdef int pop(self, DOUBLE_t* data, DOUBLE_t* weight) noexcept nogil: """Remove the top (minimum) element from array. Returns 0 if successful, -1 if nothing to remove.""" cdef SIZE_t array_ptr = self.array_ptr @@ -200,7 +200,7 @@ cdef class WeightedPQueue: self.array_ptr = array_ptr - 1 return 0 - cdef int peek(self, DOUBLE_t* data, DOUBLE_t* weight) nogil: + cdef int peek(self, DOUBLE_t* data, DOUBLE_t* weight) noexcept nogil: """Write the top element from array to a pointer. Returns 0 if successful, -1 if nothing to write.""" cdef WeightedPQueueRecord* array = self.array_ @@ -211,7 +211,7 @@ cdef class WeightedPQueue: weight[0] = array[0].weight return 0 - cdef DOUBLE_t get_weight_from_index(self, SIZE_t index) nogil: + cdef DOUBLE_t get_weight_from_index(self, SIZE_t index) noexcept nogil: """Given an index between [0,self.current_capacity], access the appropriate heap and return the requested weight""" cdef WeightedPQueueRecord* array = self.array_ @@ -219,7 +219,7 @@ cdef class WeightedPQueue: # get weight at index return array[index].weight - cdef DOUBLE_t get_value_from_index(self, SIZE_t index) nogil: + cdef DOUBLE_t get_value_from_index(self, SIZE_t index) noexcept nogil: """Given an index between [0,self.current_capacity], access the appropriate heap and return the requested value""" cdef WeightedPQueueRecord* array = self.array_ @@ -272,12 +272,12 @@ cdef class WeightedMedianCalculator: self.k = 0 self.sum_w_0_k = 0 - cdef SIZE_t size(self) nogil: + cdef SIZE_t size(self) noexcept nogil: """Return the number of samples in the WeightedMedianCalculator""" return self.samples.size() - cdef int reset(self) nogil except -1: + cdef int reset(self) except -1 nogil: """Reset the WeightedMedianCalculator to its state at construction Return -1 in case of failure to allocate memory (and raise MemoryError) @@ -291,7 +291,7 @@ cdef class WeightedMedianCalculator: self.sum_w_0_k = 0 return 0 - cdef int push(self, DOUBLE_t data, DOUBLE_t weight) nogil except -1: + cdef int push(self, DOUBLE_t data, DOUBLE_t weight) except -1 nogil: """Push a value and its associated weight to the WeightedMedianCalculator Return -1 in case of failure to allocate memory (and raise MemoryError) @@ -310,7 +310,7 @@ cdef class WeightedMedianCalculator: cdef int update_median_parameters_post_push( self, DOUBLE_t data, DOUBLE_t weight, - DOUBLE_t original_median) nogil: + DOUBLE_t original_median) noexcept nogil: """Update the parameters used in the median calculation, namely `k` and `sum_w_0_k` after an insertion""" @@ -350,7 +350,7 @@ cdef class WeightedMedianCalculator: self.sum_w_0_k += self.samples.get_weight_from_index(self.k-1) return 0 - cdef int remove(self, DOUBLE_t data, DOUBLE_t weight) nogil: + cdef int remove(self, DOUBLE_t data, DOUBLE_t weight) noexcept nogil: """Remove a value from the MedianHeap, removing it from consideration in the median calculation """ @@ -365,7 +365,7 @@ cdef class WeightedMedianCalculator: original_median) return return_value - cdef int pop(self, DOUBLE_t* data, DOUBLE_t* weight) nogil: + cdef int pop(self, DOUBLE_t* data, DOUBLE_t* weight) noexcept nogil: """Pop a value from the MedianHeap, starting from the left and moving to the right. """ @@ -387,7 +387,7 @@ cdef class WeightedMedianCalculator: cdef int update_median_parameters_post_remove( self, DOUBLE_t data, DOUBLE_t weight, - double original_median) nogil: + double original_median) noexcept nogil: """Update the parameters used in the median calculation, namely `k` and `sum_w_0_k` after a removal""" # reset parameters because it there are no elements @@ -435,7 +435,7 @@ cdef class WeightedMedianCalculator: self.sum_w_0_k -= self.samples.get_weight_from_index(self.k) return 0 - cdef DOUBLE_t get_median(self) nogil: + cdef DOUBLE_t get_median(self) noexcept nogil: """Write the median to a pointer, taking into account sample weights.""" if self.sum_w_0_k == (self.total_weight / 2.0): diff --git a/sklearn/utils/_cython_blas.pxd b/sklearn/utils/_cython_blas.pxd index e43cb81269aa6..bf5350b156b5a 100644 --- a/sklearn/utils/_cython_blas.pxd +++ b/sklearn/utils/_cython_blas.pxd @@ -12,30 +12,30 @@ cpdef enum BLAS_Trans: # BLAS Level 1 ################################################################ -cdef floating _dot(int, floating*, int, floating*, int) nogil +cdef floating _dot(int, floating*, int, floating*, int) noexcept nogil -cdef floating _asum(int, floating*, int) nogil +cdef floating _asum(int, floating*, int) noexcept nogil -cdef void _axpy(int, floating, floating*, int, floating*, int) nogil +cdef void _axpy(int, floating, floating*, int, floating*, int) noexcept nogil -cdef floating _nrm2(int, floating*, int) nogil +cdef floating _nrm2(int, floating*, int) noexcept nogil -cdef void _copy(int, floating*, int, floating*, int) nogil +cdef void _copy(int, floating*, int, floating*, int) noexcept nogil -cdef void _scal(int, floating, floating*, int) nogil +cdef void _scal(int, floating, floating*, int) noexcept nogil -cdef void _rotg(floating*, floating*, floating*, floating*) nogil +cdef void _rotg(floating*, floating*, floating*, floating*) noexcept nogil -cdef void _rot(int, floating*, int, floating*, int, floating, floating) nogil +cdef void _rot(int, floating*, int, floating*, int, floating, floating) noexcept nogil # BLAS Level 2 ################################################################ cdef void _gemv(BLAS_Order, BLAS_Trans, int, int, floating, floating*, int, - floating*, int, floating, floating*, int) nogil + floating*, int, floating, floating*, int) noexcept nogil cdef void _ger(BLAS_Order, int, int, floating, floating*, int, floating*, int, - floating*, int) nogil + floating*, int) noexcept nogil # BLASLevel 3 ################################################################ cdef void _gemm(BLAS_Order, BLAS_Trans, BLAS_Trans, int, int, int, floating, const floating*, int, const floating*, int, floating, floating*, - int) nogil + int) noexcept nogil diff --git a/sklearn/utils/_cython_blas.pyx b/sklearn/utils/_cython_blas.pyx index c32d9fde2ebf1..dd2fd0697ab67 100644 --- a/sklearn/utils/_cython_blas.pyx +++ b/sklearn/utils/_cython_blas.pyx @@ -18,7 +18,7 @@ from scipy.linalg.cython_blas cimport sgemm, dgemm ################ cdef floating _dot(int n, floating *x, int incx, - floating *y, int incy) nogil: + floating *y, int incy) noexcept nogil: """x.T.y""" if floating is float: return sdot(&n, x, &incx, y, &incy) @@ -30,7 +30,7 @@ cpdef _dot_memview(floating[::1] x, floating[::1] y): return _dot(x.shape[0], &x[0], 1, &y[0], 1) -cdef floating _asum(int n, floating *x, int incx) nogil: +cdef floating _asum(int n, floating *x, int incx) noexcept nogil: """sum(|x_i|)""" if floating is float: return sasum(&n, x, &incx) @@ -43,7 +43,7 @@ cpdef _asum_memview(floating[::1] x): cdef void _axpy(int n, floating alpha, floating *x, int incx, - floating *y, int incy) nogil: + floating *y, int incy) noexcept nogil: """y := alpha * x + y""" if floating is float: saxpy(&n, &alpha, x, &incx, y, &incy) @@ -55,7 +55,7 @@ cpdef _axpy_memview(floating alpha, floating[::1] x, floating[::1] y): _axpy(x.shape[0], alpha, &x[0], 1, &y[0], 1) -cdef floating _nrm2(int n, floating *x, int incx) nogil: +cdef floating _nrm2(int n, floating *x, int incx) noexcept nogil: """sqrt(sum((x_i)^2))""" if floating is float: return snrm2(&n, x, &incx) @@ -67,7 +67,7 @@ cpdef _nrm2_memview(floating[::1] x): return _nrm2(x.shape[0], &x[0], 1) -cdef void _copy(int n, floating *x, int incx, floating *y, int incy) nogil: +cdef void _copy(int n, floating *x, int incx, floating *y, int incy) noexcept nogil: """y := x""" if floating is float: scopy(&n, x, &incx, y, &incy) @@ -79,7 +79,7 @@ cpdef _copy_memview(floating[::1] x, floating[::1] y): _copy(x.shape[0], &x[0], 1, &y[0], 1) -cdef void _scal(int n, floating alpha, floating *x, int incx) nogil: +cdef void _scal(int n, floating alpha, floating *x, int incx) noexcept nogil: """x := alpha * x""" if floating is float: sscal(&n, &alpha, x, &incx) @@ -91,7 +91,7 @@ cpdef _scal_memview(floating alpha, floating[::1] x): _scal(x.shape[0], alpha, &x[0], 1) -cdef void _rotg(floating *a, floating *b, floating *c, floating *s) nogil: +cdef void _rotg(floating *a, floating *b, floating *c, floating *s) noexcept nogil: """Generate plane rotation""" if floating is float: srotg(a, b, c, s) @@ -105,7 +105,7 @@ cpdef _rotg_memview(floating a, floating b, floating c, floating s): cdef void _rot(int n, floating *x, int incx, floating *y, int incy, - floating c, floating s) nogil: + floating c, floating s) noexcept nogil: """Apply plane rotation""" if floating is float: srot(&n, x, &incx, y, &incy, &c, &s) @@ -123,7 +123,7 @@ cpdef _rot_memview(floating[::1] x, floating[::1] y, floating c, floating s): cdef void _gemv(BLAS_Order order, BLAS_Trans ta, int m, int n, floating alpha, floating *A, int lda, floating *x, int incx, - floating beta, floating *y, int incy) nogil: + floating beta, floating *y, int incy) noexcept nogil: """y := alpha * op(A).x + beta * y""" cdef char ta_ = ta if order == RowMajor: @@ -151,7 +151,7 @@ cpdef _gemv_memview(BLAS_Trans ta, floating alpha, floating[:, :] A, cdef void _ger(BLAS_Order order, int m, int n, floating alpha, floating *x, - int incx, floating *y, int incy, floating *A, int lda) nogil: + int incx, floating *y, int incy, floating *A, int lda) noexcept nogil: """A := alpha * x.y.T + A""" if order == RowMajor: if floating is float: @@ -182,7 +182,7 @@ cpdef _ger_memview(floating alpha, floating[::1] x, floating[::1] y, cdef void _gemm(BLAS_Order order, BLAS_Trans ta, BLAS_Trans tb, int m, int n, int k, floating alpha, const floating *A, int lda, const floating *B, - int ldb, floating beta, floating *C, int ldc) nogil: + int ldb, floating beta, floating *C, int ldc) noexcept nogil: """C := alpha * op(A).op(B) + beta * C""" # TODO: Remove the pointer casts below once SciPy uses const-qualification. # See: https://github.com/scipy/scipy/issues/14262 diff --git a/sklearn/utils/_heap.pxd b/sklearn/utils/_heap.pxd index 064b62f977f9c..2f1b9b71d59ce 100644 --- a/sklearn/utils/_heap.pxd +++ b/sklearn/utils/_heap.pxd @@ -11,4 +11,4 @@ cdef int heap_push( ITYPE_t size, floating val, ITYPE_t val_idx, -) nogil +) noexcept nogil diff --git a/sklearn/utils/_heap.pyx b/sklearn/utils/_heap.pyx index 573f9925065ea..14cb7722ef793 100644 --- a/sklearn/utils/_heap.pyx +++ b/sklearn/utils/_heap.pyx @@ -9,7 +9,7 @@ cdef inline int heap_push( ITYPE_t size, floating val, ITYPE_t val_idx, -) nogil: +) noexcept nogil: """Push a tuple (val, val_idx) onto a fixed-size max-heap. The max-heap is represented as a Structure of Arrays where: diff --git a/sklearn/utils/_isfinite.pyx b/sklearn/utils/_isfinite.pyx index d4cd7cb59e19b..41fb71aee40c0 100644 --- a/sklearn/utils/_isfinite.pyx +++ b/sklearn/utils/_isfinite.pyx @@ -17,7 +17,7 @@ def cy_isfinite(floating[::1] a, bint allow_nan=False): return result -cdef inline FiniteStatus _isfinite(floating[::1] a, bint allow_nan) nogil: +cdef inline FiniteStatus _isfinite(floating[::1] a, bint allow_nan) noexcept nogil: cdef floating* a_ptr = &a[0] cdef Py_ssize_t length = len(a) if allow_nan: @@ -27,7 +27,7 @@ cdef inline FiniteStatus _isfinite(floating[::1] a, bint allow_nan) nogil: cdef inline FiniteStatus _isfinite_allow_nan(floating* a_ptr, - Py_ssize_t length) nogil: + Py_ssize_t length) noexcept nogil: cdef Py_ssize_t i cdef floating v for i in range(length): @@ -38,7 +38,7 @@ cdef inline FiniteStatus _isfinite_allow_nan(floating* a_ptr, cdef inline FiniteStatus _isfinite_disable_nan(floating* a_ptr, - Py_ssize_t length) nogil: + Py_ssize_t length) noexcept nogil: cdef Py_ssize_t i cdef floating v for i in range(length): diff --git a/sklearn/utils/_openmp_helpers.pxd b/sklearn/utils/_openmp_helpers.pxd index e57fc9bfa6bf5..6819824785424 100644 --- a/sklearn/utils/_openmp_helpers.pxd +++ b/sklearn/utils/_openmp_helpers.pxd @@ -3,4 +3,4 @@ # Those interfaces act as indirections which allows the non-support of OpenMP # for implementations which have been written for it. -cdef int _openmp_thread_num() nogil +cdef int _openmp_thread_num() noexcept nogil diff --git a/sklearn/utils/_openmp_helpers.pyx b/sklearn/utils/_openmp_helpers.pyx index cddd77ac42746..25f57021c9fa9 100644 --- a/sklearn/utils/_openmp_helpers.pyx +++ b/sklearn/utils/_openmp_helpers.pyx @@ -60,7 +60,7 @@ cpdef _openmp_effective_n_threads(n_threads=None): return 1 -cdef inline int _openmp_thread_num() nogil: +cdef inline int _openmp_thread_num() noexcept nogil: """Return the number of the thread calling this function. If scikit-learn is built without OpenMP support, always return 0. diff --git a/sklearn/utils/_seq_dataset.pxd.tp b/sklearn/utils/_seq_dataset.pxd.tp index 6783a2da2c3ce..e6c46a7ac73ca 100644 --- a/sklearn/utils/_seq_dataset.pxd.tp +++ b/sklearn/utils/_seq_dataset.pxd.tp @@ -39,17 +39,17 @@ cdef class SequentialDataset{{name_suffix}}: cdef Py_ssize_t n_samples cdef cnp.uint32_t seed - cdef void shuffle(self, cnp.uint32_t seed) nogil - cdef int _get_next_index(self) nogil - cdef int _get_random_index(self) nogil + cdef void shuffle(self, cnp.uint32_t seed) noexcept nogil + cdef int _get_next_index(self) noexcept nogil + cdef int _get_random_index(self) noexcept nogil cdef void _sample(self, {{c_type}} **x_data_ptr, int **x_ind_ptr, int *nnz, {{c_type}} *y, {{c_type}} *sample_weight, - int current_index) nogil + int current_index) noexcept nogil cdef void next(self, {{c_type}} **x_data_ptr, int **x_ind_ptr, - int *nnz, {{c_type}} *y, {{c_type}} *sample_weight) nogil + int *nnz, {{c_type}} *y, {{c_type}} *sample_weight) noexcept nogil cdef int random(self, {{c_type}} **x_data_ptr, int **x_ind_ptr, - int *nnz, {{c_type}} *y, {{c_type}} *sample_weight) nogil + int *nnz, {{c_type}} *y, {{c_type}} *sample_weight) noexcept nogil cdef class ArrayDataset{{name_suffix}}(SequentialDataset{{name_suffix}}): diff --git a/sklearn/utils/_seq_dataset.pyx.tp b/sklearn/utils/_seq_dataset.pyx.tp index 89cea4690c982..ae302b7565fb5 100644 --- a/sklearn/utils/_seq_dataset.pyx.tp +++ b/sklearn/utils/_seq_dataset.pyx.tp @@ -71,7 +71,7 @@ cdef class SequentialDataset{{name_suffix}}: """ cdef void next(self, {{c_type}} **x_data_ptr, int **x_ind_ptr, - int *nnz, {{c_type}} *y, {{c_type}} *sample_weight) nogil: + int *nnz, {{c_type}} *y, {{c_type}} *sample_weight) noexcept nogil: """Get the next example ``x`` from the dataset. This method gets the next sample looping sequentially over all samples. @@ -104,7 +104,7 @@ cdef class SequentialDataset{{name_suffix}}: current_index) cdef int random(self, {{c_type}} **x_data_ptr, int **x_ind_ptr, - int *nnz, {{c_type}} *y, {{c_type}} *sample_weight) nogil: + int *nnz, {{c_type}} *y, {{c_type}} *sample_weight) noexcept nogil: """Get a random example ``x`` from the dataset. This method gets next sample chosen randomly over a uniform @@ -141,7 +141,7 @@ cdef class SequentialDataset{{name_suffix}}: current_index) return current_index - cdef void shuffle(self, cnp.uint32_t seed) nogil: + cdef void shuffle(self, cnp.uint32_t seed) noexcept nogil: """Permutes the ordering of examples.""" # Fisher-Yates shuffle cdef int *ind = self.index_data_ptr @@ -151,7 +151,7 @@ cdef class SequentialDataset{{name_suffix}}: j = i + our_rand_r(&seed) % (n - i) ind[i], ind[j] = ind[j], ind[i] - cdef int _get_next_index(self) nogil: + cdef int _get_next_index(self) noexcept nogil: cdef int current_index = self.current_index if current_index >= (self.n_samples - 1): current_index = -1 @@ -160,7 +160,7 @@ cdef class SequentialDataset{{name_suffix}}: self.current_index = current_index return self.current_index - cdef int _get_random_index(self) nogil: + cdef int _get_random_index(self) noexcept nogil: cdef int n = self.n_samples cdef int current_index = our_rand_r(&self.seed) % n self.current_index = current_index @@ -168,7 +168,7 @@ cdef class SequentialDataset{{name_suffix}}: cdef void _sample(self, {{c_type}} **x_data_ptr, int **x_ind_ptr, int *nnz, {{c_type}} *y, {{c_type}} *sample_weight, - int current_index) nogil: + int current_index) noexcept nogil: pass def _shuffle_py(self, cnp.uint32_t seed): @@ -272,7 +272,7 @@ cdef class ArrayDataset{{name_suffix}}(SequentialDataset{{name_suffix}}): cdef void _sample(self, {{c_type}} **x_data_ptr, int **x_ind_ptr, int *nnz, {{c_type}} *y, {{c_type}} *sample_weight, - int current_index) nogil: + int current_index) noexcept nogil: cdef long long sample_idx = self.index_data_ptr[current_index] cdef long long offset = sample_idx * self.X_stride @@ -342,7 +342,7 @@ cdef class CSRDataset{{name_suffix}}(SequentialDataset{{name_suffix}}): cdef void _sample(self, {{c_type}} **x_data_ptr, int **x_ind_ptr, int *nnz, {{c_type}} *y, {{c_type}} *sample_weight, - int current_index) nogil: + int current_index) noexcept nogil: cdef long long sample_idx = self.index_data_ptr[current_index] cdef long long offset = self.X_indptr_ptr[sample_idx] y[0] = self.Y_data_ptr[sample_idx] diff --git a/sklearn/utils/_sorting.pxd b/sklearn/utils/_sorting.pxd index 412d67c479fac..9a199ef2be182 100644 --- a/sklearn/utils/_sorting.pxd +++ b/sklearn/utils/_sorting.pxd @@ -6,4 +6,4 @@ cdef int simultaneous_sort( floating *dist, ITYPE_t *idx, ITYPE_t size, -) nogil +) noexcept nogil diff --git a/sklearn/utils/_sorting.pyx b/sklearn/utils/_sorting.pyx index 367448b5cb91b..9a9eaebcf2dd2 100644 --- a/sklearn/utils/_sorting.pyx +++ b/sklearn/utils/_sorting.pyx @@ -5,7 +5,7 @@ cdef inline void dual_swap( ITYPE_t *iarr, ITYPE_t a, ITYPE_t b, -) nogil: +) noexcept nogil: """Swap the values at index a and b of both darr and iarr""" cdef floating dtmp = darr[a] darr[a] = darr[b] @@ -20,7 +20,7 @@ cdef int simultaneous_sort( floating* values, ITYPE_t* indices, ITYPE_t size, -) nogil: +) noexcept nogil: """ Perform a recursive quicksort on the values array as to sort them ascendingly. This simultaneously performs the swaps on both the values and the indices arrays. diff --git a/sklearn/utils/_weight_vector.pxd.tp b/sklearn/utils/_weight_vector.pxd.tp index e4de2ae33ea16..9d1779373cbf4 100644 --- a/sklearn/utils/_weight_vector.pxd.tp +++ b/sklearn/utils/_weight_vector.pxd.tp @@ -34,13 +34,13 @@ cdef class WeightVector{{name_suffix}}(object): cdef {{c_type}} sq_norm cdef void add(self, {{c_type}} *x_data_ptr, int *x_ind_ptr, - int xnnz, {{c_type}} c) nogil + int xnnz, {{c_type}} c) noexcept nogil cdef void add_average(self, {{c_type}} *x_data_ptr, int *x_ind_ptr, - int xnnz, {{c_type}} c, {{c_type}} num_iter) nogil + int xnnz, {{c_type}} c, {{c_type}} num_iter) noexcept nogil cdef {{c_type}} dot(self, {{c_type}} *x_data_ptr, int *x_ind_ptr, - int xnnz) nogil - cdef void scale(self, {{c_type}} c) nogil - cdef void reset_wscale(self) nogil - cdef {{c_type}} norm(self) nogil + int xnnz) noexcept nogil + cdef void scale(self, {{c_type}} c) noexcept nogil + cdef void reset_wscale(self) noexcept nogil + cdef {{c_type}} norm(self) noexcept nogil {{endfor}} diff --git a/sklearn/utils/_weight_vector.pyx.tp b/sklearn/utils/_weight_vector.pyx.tp index 9e305c0b366d2..e2d374813a5b4 100644 --- a/sklearn/utils/_weight_vector.pyx.tp +++ b/sklearn/utils/_weight_vector.pyx.tp @@ -80,7 +80,7 @@ cdef class WeightVector{{name_suffix}}(object): self.average_b = 1.0 cdef void add(self, {{c_type}} *x_data_ptr, int *x_ind_ptr, int xnnz, - {{c_type}} c) nogil: + {{c_type}} c) noexcept nogil: """Scales sample x by constant c and adds it to the weight vector. This operation updates ``sq_norm``. @@ -119,7 +119,7 @@ cdef class WeightVector{{name_suffix}}(object): # here: https://research.microsoft.com/pubs/192769/tricks-2012.pdf # by Leon Bottou cdef void add_average(self, {{c_type}} *x_data_ptr, int *x_ind_ptr, int xnnz, - {{c_type}} c, {{c_type}} num_iter) nogil: + {{c_type}} c, {{c_type}} num_iter) noexcept nogil: """Updates the average weight vector. Parameters @@ -155,7 +155,7 @@ cdef class WeightVector{{name_suffix}}(object): self.average_a += mu * self.average_b * wscale cdef {{c_type}} dot(self, {{c_type}} *x_data_ptr, int *x_ind_ptr, - int xnnz) nogil: + int xnnz) noexcept nogil: """Computes the dot product of a sample x and the weight vector. Parameters @@ -182,7 +182,7 @@ cdef class WeightVector{{name_suffix}}(object): innerprod *= self.wscale return innerprod - cdef void scale(self, {{c_type}} c) nogil: + cdef void scale(self, {{c_type}} c) noexcept nogil: """Scales the weight vector by a constant ``c``. It updates ``wscale`` and ``sq_norm``. If ``wscale`` gets too @@ -193,7 +193,7 @@ cdef class WeightVector{{name_suffix}}(object): if self.wscale < {{reset_wscale_threshold}}: self.reset_wscale() - cdef void reset_wscale(self) nogil: + cdef void reset_wscale(self) noexcept nogil: """Scales each coef of ``w`` by ``wscale`` and resets it to 1. """ if self.aw_data_ptr != NULL: _axpy(self.n_features, self.average_a, @@ -205,7 +205,7 @@ cdef class WeightVector{{name_suffix}}(object): _scal(self.n_features, self.wscale, self.w_data_ptr, 1) self.wscale = 1.0 - cdef {{c_type}} norm(self) nogil: + cdef {{c_type}} norm(self) noexcept nogil: """The L2 norm of the weight vector. """ return sqrt(self.sq_norm)